Next.js is a framework for building server-rendered React applications. It provides a powerful set of features for web development such as automatic code splitting, server-side rendering, and static site generation. In this blog post, we will be creating a simple Todo application using Next.js.
Setting up the project
To get started, you will need to have Node.js and npm (or yarn) installed on your machine. Once you have these dependencies set up, you can create a new Next.js project using the following command:
npx create-next-app my-todo-app
This will create a new directory called “my-todo-app” with the basic file structure and dependencies for a Next.js app.
Creating the Todo List component
In this step, we will create a TodoList component that will display a list of todo items. Create a new file called TodoList.js in the components folder and add the following code:
In this code, we are rendering an unordered list and mapping over the todos prop to create a list item for each todo item. We also added a button to delete the todo item.
Adding the Todo Form
Now that we have the TodoList component, we need to create a form to add new todo items. Create a new file called TodoForm.js in the components folder and add the following code:
In this code, we are creating a form with an input that allows the user to enter a new todo item. When the form is submitted, it calls the addTodo function with the text of the input as an argument. We are also reset the text state after adding the todo item.
Creating the TodoPage
Create a new file called TodoPage.js in the pages folder and add the following code:
In this file, we are creating a TodoPage component that contains the TodoForm and TodoList components. We are also using React’s useState hook to manage the state of the todo items. The addTodo function is passed down to the TodoForm component as a prop and is called when a new todo item is added. The deleteTodo function is passed down to the TodoList component as a prop and is called when a todo item is deleted.
Adding Routing
Add the following code in your pages/index.js file to redirect users to the TodoPage by default
import TodoPage from './TodoPage';
export default function Home() {
return <TodoPage />;
}
Now the user will be able to access the TodoPage by visiting the root of your application.
That’s it! You now have a working Todo application built with Next.js. You can customize the application further by adding styles, saving the todo items to a database, or adding more features.
Adding Styles
You can add styles to your Todo application using a CSS preprocessor like SASS or using CSS-in-JS libraries like styled-components.
If you decide to use a CSS preprocessor, you will need to install the necessary dependencies and configure Next.js to use it. You can add the CSS files to the styles directory in the root of your project.
If you prefer to use styled-components, you can install it using npm or yarn by running the following command:
npm install styled-components
And then you can import it in your TodoForm.js and TodoList.js and add styles to your components.
To save the todo items to a database, you will need to create a backend service that the Next.js app can communicate with. You can use a variety of technologies to build the backend, such as Node.js with Express, Python with Flask or Ruby on Rails.
In your backend service, you will need to create a REST API that the frontend can send requests to for creating, reading, updating, and deleting todo items.
Then you need to call the API in the TodoPage component’s functions like addTodo, deleteTodo to perform the CRUD operations on todo items.
Additionally, you can also use a library like axios or fetch to communicate with the backend service.
In summary, creating a Todo application using Next.js is a straightforward process, but you can also add further functionality like styles, routing, and saving the data to a database. It’s a great way to learn more about building web applications with React and Next.js and you can use the concepts you learn to build more advanced applications in the future.
Next.js is a popular framework for building web applications with React. It provides a lot of powerful features out of the box, such as server-rendered React components, automatic code splitting, and easy-to-use development tools. In this blog post, we’re going to take a look at how to get started with Next.js and build a simple web application. By the end of this post, you should have a good understanding of the basic concepts behind Next.js, and be able to start building your own applications with the framework.
Creating a New Next.js Project
The first step in building a Next.js application is to create a new project. You can do this using the Next.js CLI, which can be installed using npm:
npm init next-app my-app
This command will create a new directory called “my-app” that contains the basic file structure for a Next.js application. You should now be able to start the development server by running the following command:
npm run dev
If everything is set up correctly, you should see the message “ready on http://localhost:3000” in your terminal, and be able to view the default “Hello World” Next.js app in your browser.
Understanding the File Structure
Once you have created a new Next.js project, it’s a good idea to take a look at the file structure to understand how the application is organized. The most important directories and files in a Next.js project are:
pages/: This directory contains the pages of your web application. Each file in this directory represents a page on your site, and its filename is used as the path for that page. For example, the file pages/about.js represents the “about” page of your site, and can be accessed at the url “/about”.
public/: This directory contains files that should be served as-is, such as images and fonts.
package.json: This file contains information about your project, such as its dependencies and scripts.
next.config.js: This file is used to configure advanced settings for your Next.js application.
Creating a Simple Page
Now that you have a basic understanding of the file structure of a Next.js project, let’s create our first page.
In the pages directory, create a new file called “about.js”. Inside this file, add the following code:
import React from "react";
export default function About() {
return <h1>About Page</h1>;
}
This is a simple React component that renders an h1 tag with the text “About Page”. Next.js uses the file name of this component to define the path of the page. So, this component will be rendered when the application is accessed at the “/about” path.
If you start the development server with “npm run dev” and access “http://localhost:3000/about” in your browser, you should see the “About Page” text on the page.
Adding Routing
In a more complex application, you’ll likely have more than one page and you’ll need a way to navigate between them. Next.js provides an easy way to do this through the use of dynamic routing.
To add dynamic routing, you’ll need to create a new file in the pages directory, and add a special syntax to the file name.
For example, create a new file called “users/[userId].js”. Inside the file, you can access the userId variable through the useRouter hook from the next/router package and use it to fetch data from an API or display information about a specific user.
Now, when you visit the “/users/1” or “/users/2” path, the userId variable will be set to “1” or “2” respectively, and the corresponding user information can be displayed on the page.
To create the navigation links between pages, you can use the Link component from the next/link package.
import Link from 'next/link'
export default function Navigation() {
return (
<nav>
<Link href="/">
<a>Home</a>
</Link>
<Link href="/about">
<a>About</a>
</Link>
<Link href="/users/1">
<a>User 1</a>
</Link>
</nav>
)
}
Building a Server-rendered React App with Next.js
Next.js also allows you to build server-rendered React apps, which can improve the performance and SEO of your application. To do this, you can use the getServerSideProps function in a page to fetch data on the server and then pass it down to the component as props.
import axios from 'axios'
export default function User({ user }) {
return <h1>User: {user.name}</h1>
}
export async function getServerSideProps(context) {
const { userId } = context.params
const res = await axios.get(`https://my-api.com/users/${userId}`)
const user = res.data
return {
props: {
user
}
}
}
In this example, the getServerSideProps function is making a request to an API to fetch the user data and passing it down to the component as a prop. This way, the user data will be available on the initial render of the component on the server, improving the performance and SEO of your application.
Conclusion
In this blog post, we’ve covered the basics of getting started with Next.js. We’ve looked at how to create a new project, the file structure of a Next.js project, creating a simple page, adding routing, and building a server-rendered React app. With the knowledge from this post, you should be well on your way to building your own web applications with Next.js.
Next.js is a powerful framework that makes it easy to build high-performance web applications. With its built-in features like automatic code splitting, server-rendering, and easy-to-use development tools, it can save you a lot of time and effort compared to building a similar application from scratch. I hope this post has been helpful in getting you started with Next.js, and I encourage you to continue learning more about the framework and experimenting with building your own projects.
To take your Next.js skills to the next level, I recommend checking out the official documentation, which provides a lot of valuable information and examples. Additionally, there are many tutorials and courses available online that can help you learn more about the framework.
Another useful tool that can be used with Next.js is Vercel, it’s a cloud platform for static site generators and serverless functions that can greatly simplify the deployment process of your Next.js application. With Vercel, you can deploy your application with a single command, and it will handle everything from building your application to provisioning the necessary resources.
In addition, there are many libraries and packages that have been built for Next.js, such as next-i18next for internationalization and next-redux for state management. These can greatly enhance the functionality of your application and make development more efficient.
In summary, Next.js is a powerful framework that makes it easy to build high-performance web applications. With its built-in features, it can save you a lot of time and effort. However, if you are just getting started, it can be difficult to know where to start. I hope that this post has provided you with a solid foundation and a good starting point for your Next.js journey.
With the help of twitter app credentials, i have started working on another set of sentiment analysis.
I have used couple of popular libraries this time.
TextBlob
Tweepy
TextBlob is used to check the polarity of the given text.
And tweepy is used to get the tweets from real-time data.
To use tweepy, first we need to create an app in twitter environment. This can be done in their developers site. Once app is created we need to get the following tokens from it.
api_key = 'XXXX'
api_key_secret = 'XXXX'
access_token = 'XXXX'
access_token_secret = 'XXXX'
You can find the entire main.py file content below.
for tweet in tweets: cleaned_up_text = tweet.text.replace('RT', '') if cleaned_up_text.startswith(' @'): position = cleaned_up_text.index(':') cleaned_up_text = cleaned_up_text[position + 2:] if cleaned_up_text.startswith('@'): position = cleaned_up_text.index(' ') cleaned_up_text = cleaned_up_text[position + 2:]
I used to do data analysis regularly with different data.
By the way, I did my masters at BITS Pilani on Data Analytics. So I keep doing some analysis on data.
Example: Earlier I have analysed my skype history data. I captured some of fun facts like
How many times my name was pronounced wrongly?
Who is the leading person to do that?
How time good morning message is received in the evenings?
How many times received urgent call from contacts?
What is average, mean, min, max time people waited for me to reply hi to their hi message? (actually people should not wait for other end person to salute for their message)
Likewise, did some more analysis and captured some fun facts.
So now, the ongoing social media topic is “Elon Musk buys twitter”.
Lets do some sentiment analysis with twitter data.
I haven’t invloved in sentiment analysis before. I was referring internet to do those with the help of python libraries.
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
class TwitterClient(object):
'''
Generic Twitter Class for sentiment analysis.
'''
def __init__(self):
'''
Class constructor or initialization method.
'''
# keys and tokens from the Twitter Dev Console
consumer_key = 'xxxxxxxxxxxxxxxxxxxxxx'
consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxx'
access_token = 'xxxxxxxxxxxxxxxxxxxxxx'
access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxx
# attempt authentication
try:
# create OAuthHandler object
self.auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api = tweepy.API(self.auth)
except:
print("Error: Authentication Failed")
def clean_tweet(self, tweet):
'''
Utility function to clean tweet text by removing links, special characters
using simple regex statements.
'''
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
def get_tweet_sentiment(self, tweet):
'''
Utility function to classify sentiment of passed tweet
using textblob's sentiment method
'''
# create TextBlob object of passed tweet text
analysis = TextBlob(self.clean_tweet(tweet))
# set sentiment
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'
def get_tweets(self, query, count = 10):
'''
Main function to fetch tweets and parse them.
'''
# empty list to store parsed tweets
tweets = []
try:
# call twitter api to fetch tweets
fetched_tweets = self.api.search_tweets(q = query, count = count)
# parsing tweets one by one
for tweet in fetched_tweets:
# empty dictionary to store required params of a tweet
parsed_tweet = {}
# saving text of tweet
parsed_tweet['text'] = tweet.text
# saving sentiment of tweet
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
# appending parsed tweet to tweets list
if tweet.retweet_count > 0:
# if tweet has retweets, ensure that it is appended only once
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)
# return parsed tweets
return tweets
except tweepy.TweepError as e:
# print error (if any)
print("Error : " + str(e))
def main():
# creating object of TwitterClient Class
api = TwitterClient()
# calling function to get tweets
tweets = api.get_tweets(query = 'elon musk bought twitter', count = 200)
# picking positive tweets from tweets
ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
# percentage of positive tweets
print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
# picking negative tweets from tweets
ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
# percentage of negative tweets
print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
# percentage of neutral tweets
print("Neutral tweets percentage: {} % \
".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))
# printing first 5 positive tweets
print("\n\nPositive tweets:")
for tweet in ptweets[:10]:
print(tweet['text'])
print("-------------------")
# printing first 5 negative tweets
print("\n\nNegative tweets:")
for tweet in ntweets[:10]:
print(tweet['text'])
if __name__ == "__main__":
# calling main function
main()
Output
Connected to pydev debugger (build 213.7172.26)
Positive tweets percentage: 42.1875 %
Negative tweets percentage: 12.5 %
Neutral tweets percentage: 45.3125 %
Positive tweets:
@realDond_Trump It’s interesting how this new position came right after Elon Musk bought Twitter. Wow! When they co… https://t.co/Nua5PamFnJ
-------------------
RT @BelindaW75: So did all of you come to Twitter only after Elon Musk bought it? I already had an account but didn't really use it til Elo…
-------------------
@rtenews Irish billionaire Denis o brien owns most the Irish media.
Amazon creator Jeff benzos owns washington pos… https://t.co/uUs13EaSrd
-------------------
I and many other people bought into it. But the fact of the matter is, he can post as many silly memes on Twitter a… https://t.co/IBqdu1MDVt
-------------------
RT @OlympTrade: 🦾 Elon Musk bought 9.2% of the Twitter stock. The stock rose by more than 20% immediately after that.
🤑 Our traders mad…
-------------------
RT @amtvmedia: Elon Musk started PayPal that censors conservative political speech now he bought Twitter because free speech. Hahaha!! Amer…
-------------------
RT @hqfNFT: (5/10) With Twitter getting bought out by Elon Musk, he'd be pushing Twitter's boundaries in many aspects, and I believe one sm…
-------------------
RT @TrungTPhan: Larry Ellison and Elon Musk are buds.
Larry bought $1B of Tesla in December 2018. The stake is worth ~$15B now.
He just p…
-------------------
My hot take: Elon Musk bought twitter soley to delete @ElonJet instead of giving him this 50k
-------------------
RT @Freedom9369: Elon Musk just bought Instagram (after acquiring Twitter and Pepsi, plus owning the new Starlink Satellite System. Humm. W…
-------------------
Negative tweets:
RT @azidan_GOS: Elon Musk bought twitter yesterday, and in less than 24hours he has already changed the colour of the like and Retweet butt…
Arsenal is playing better Barca style than us right now.
Our last games were absolute dog shit, shocking to see the… https://t.co/3k1nLY1v2p
RT @Dream: Elon Musk bought Twitter when it’s literally free 🤣🤣😂😂🤣😝😝 what an idiot
RT @TimRunsHisMouth: It took the Biden administration less than 3 days to create a Ministry of Truth after Elon Musk bought Twitter... Ima…
elon musk bought twitter and some weird troll kept banging on my youtube channel and not my brand site
@mfer4lyfe Maybe … anything can happen .. Elon Musk bought twitter for 4billy and if he’s been secretly buying into… https://t.co/zAup584dAA
@3nyoom @mfer4lyfe What if … Elon Musk has secretly been buying into Bayc and just bought twitter ; then he goes fo… https://t.co/aEMDzCviZq
RT @_TheShawn: Wait hold up, so you mean to tell me that we can tweet whatever we want now without worrying about a suspension since Elon M…
Process finished with exit code 0
Happy coding!
This is just a experiment I have made. I will keep posted the improvised edition once I complete.
When we prefix a constructor parameter with an access modifier, it is getting promoted as class property in Typescript.
Without any access modifier prefix the constructor parameter is just the method parameter. We should manually assign it to declared class property from the constructor.
Method #1
In the following snippet, we have added a class property and assigned the the parameter and used it later on.
In this blog post, we are going to discuss about “how we can deploy an angular app on GitHub Pages for free”
To discuss further, lets create a angular application using the Angular CLI. You can checkout one of our detailed post on how to create angular app using CLI here.
Create an angular application using angular CLI
The flow is we are going to generate an angular app using angular CLI. The CLI will generate us a sample application and we will push that boilerplate into GitHub with a new repo.
And then we will look into the steps to deploy that application in github pages.
Create GitHub Repository
I’m going to create an repository with a name “angular-hosting-demo”
Once I create repo, I’m going to push all codes here.
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.
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.
And also we can create multiple lists of the same syntax with unique id as well.
We can generate lorem ipsum text with the default number of words or a certain number of text by mentioning the word count.
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.
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 -vnpm -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.
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 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.
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.
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
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.
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
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 skeleton
The key parts available in angular architecture are
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.
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
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 init
If you are afraid of questions, we have another quick option.
Enter command npm init –yes
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.
xi18n (i18n-extract) – Extracts i18n messages from source code.
Creating new angular project
ng new timer-project
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.
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.
Specifies intentionally untracked files that Git should ignore.
README.md
Introductory documentation for the root app.
angular.json
CLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses, such as TSLint, Karma, and Protractor. For details, see Angular Workspace Configuration.
Provides 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.json
Default TypeScript configuration for projects in the workspace.
tslint.json
Default 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 FILES
PURPOSE
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.ico
An icon to use for this application in the bookmark bar.
index.html
The 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.ts
The 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.ts
Provides polyfill scripts for browser support.
styles.sass
Lists CSS files that supply styles for a project. The extension reflects the style preprocessor you have configured for the project.
test.ts
The 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
SRC/APP/ FILES
PURPOSE
app/app.component.ts
Defines 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.html
Defines the HTML template associated with the root AppComponent.
app/app.component.css
Defines the base CSS stylesheet for the root AppComponent.
app/app.component.spec.ts
Defines a unit test for the root AppComponent.
app/app.module.ts
Defines 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 FILES
PURPOSE
browserslist
Configures sharing of target browsers and Node.js versions among various front-end tools. See Browserslist on GitHub for more information.
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!
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
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).
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.
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.
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
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.
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.
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
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
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.
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
These DefaultApiConventions can also be extended and defined separately based on our needs.
DefaultApiConventions covers some basic commonly used convention types in APIs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!
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
And in the next prompt select ASP.NET Core 2.2 in the topmost drop-down and click.
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,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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
Once we have clicked the Visual studio will start scaffolding our new controller in a few seconds. And our controller will look like below
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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
Once installed, we can verify the installation using the following command
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.
To Add in web browser list, click browse with the option and click Add and fill the required as follows.
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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
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
Once installed
In the ConfigureServices method of Startup.cs, register the Swagger generator, defining one or more Swagger documents.
Once we have set the default editor, we can make post call as follows by typing command POST
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.
Get call
We can make GET call as follows,
Cool! That’s it for now. we can discuss API Analyzer in the next post.
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.
Updated our web templates to Bootstrap 4 and Angular 6
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
We can download the .NET Core 2.2 SDK from the link,
We can download and start Installation based on our system environment.
Once installed we can check whether the latest version is available or not with the same command which we have earlier in this post.
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
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.
The files have been generated with the following structure,
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
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
When we run the latest angular application template, we have got following UI pages,
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.
Software development is an ever-evolving process with many considerations to be taken. One of these considerations is the accumulation of tech debt, which can be a major burden on development teams. In this blog post, we’ll explore the concept of tech debt and how it applies to C# development.
Technical debt is a term used to describe the cost of maintaining and fixing the code of a software system over time. It is a result of making shortcuts and trade-offs during the development process in order to meet deadlines, save time and budget, or make a product available to the market as soon as possible. However, these shortcuts can accumulate over time and make the code base more difficult to work with, leading to increased maintenance costs, reduced quality, and reduced agility.
Technical debt can be thought of as a loan that needs to be paid back with interest. The longer it takes to pay back the debt, the more it will cost in the long run. Therefore, it is important to keep technical debt under control and to address it as soon as possible.
Why does Technical Debt Occur?
Here are a few examples of technical debt in C#:
Code duplication
Duplicated code is a common source of technical debt. This happens when developers write similar code multiple times instead of creating a reusable function or class. This increases the amount of code to maintain and makes it more difficult to make changes that affect multiple parts of the codebase.
Example
public void printMessage1()
{
Console.WriteLine("Hello World!");
}
public void printMessage2()
{
Console.WriteLine("Hello World!");
}
Instead, the code can be refactored to use a single method:
public void printMessage()
{
Console.WriteLine("Hello World!");
}
Poorly named variables and functions
Variable and function names that are unclear, misleading, or not descriptive can make code difficult to understand and maintain.
Example
public void calc(int a, int b)
{
int c = a + b;
Console.WriteLine(c);
}
Refactored code
public void calculateSum(int firstNumber, int secondNumber)
{
int sum = firstNumber + secondNumber;
Console.WriteLine(sum);
}
Hardcoded values
Hardcoded values are values that are embedded directly in the code, making it difficult to change them later. This creates technical debt because if the value needs to change, the code must be updated in multiple places.
Example
public void calculateTax(int salary)
{
int tax = salary * 0.1;
Console.WriteLine(tax);
}
Refactored code
private const double TAX_RATE = 0.1;
public void calculateTax(int salary)
{
int tax = salary * TAX_RATE;
Console.WriteLine(tax);
}
How to Manage Technical Debt in Software Development
In order to manage technical debt effectively, it is important to adopt a proactive approach. Here are a few best practices that can help you keep technical debt under control:
Regular code review: Regular code reviews can help identify and address technical debt early on. Code review is a collaborative process where code is reviewed by other team members to identify any areas that could be improved.
Automated testing: Automated tests can help catch bugs and issues early on in the development process, reducing the amount of technical debt that is accumulated. It also helps to ensure that changes to the code do not break existing functionality.
Continuous integration and continuous deployment (CI/CD): CI/CD helps to ensure that code changes are automatically built, tested, and deployed. This helps to catch issues early on in the development process, reducing the amount of technical debt that is accumulated.
Refactoring: Refactoring is the process of changing the structure of code without changing its functionality. It can help to reduce technical debt by making code more maintainable, easier to understand, and easier to change.
Establish clear coding standards: Having clear coding standards can help to ensure that all code is written in a consistent and maintainable way, reducing the amount of technical debt that is accumulated.
Plan for technical debt: Finally, it is important to plan for technical debt. This means considering the long-term impact of shortcuts and trade-offs during the development process, and making sure that there is a plan in place to address technical debt when it arises.
It is also important to keep in mind that technical debt is not always a bad thing. In some cases, taking on technical debt can be necessary in order to meet deadlines or bring a product to market quickly. The key is to make informed decisions about when and how to take on technical debt, and to have a plan in place to address it in a timely manner.
When taking on technical debt, it is important to consider the following factors:
The impact on the codebase: What is the long-term impact of the shortcut or trade-off on the codebase? Will it make it more difficult to maintain or change in the future?
The potential return on investment (ROI): What is the potential return on investment from taking on this technical debt? Will the product be more successful or profitable as a result?
The cost of paying back the debt: What is the cost of paying back the technical debt in the future? Will it be worth it in the long run?
The timeline for paying back the debt: When will the technical debt need to be paid back? Can it be addressed in a timely manner?
By considering these factors and making informed decisions about when and how to take on technical debt, you can help ensure that your codebase remains maintainable and of high quality over time.
In conclusion, technical debt is an important aspect of software development that should be taken seriously. By following best practices, making informed decisions about when and how to take on technical debt, and having a plan in place to address it, you can help ensure that your code is maintainable and of high quality, and that the long-term costs of maintaining and fixing code are kept under control.
Images play a crucial role in web design, and with CSS, we can enhance their appearance and add effects to them to make them look more attractive. CSS provides a variety of image effects and filters that can be used to manipulate images in different ways.
In this article, we’ll explore some of the most common CSS image effects and filters, with examples of each.
Blur Effect
The blur effect is used to blur the image and make it look slightly out of focus. The CSS blur function can be used to create a blur effect on an image. The function accepts a length value that represents the amount of blur.
img {
filter: blur(5px);
}
Grayscale Effect
The grayscale effect is used to convert the image to a grayscale image, where all the colors in the image are represented in different shades of gray. The CSS grayscale function can be used to create a grayscale effect on an image. The function accepts a value between 0 and 1, where 0 is the original image and 1 is the fully grayscale image.
img {
filter: grayscale(1);
}
Brightness Effect
The brightness effect is used to change the brightness of an image. The CSS brightness function can be used to create a brightness effect on an image. The function accepts a value between 0 and 1, where 0 is the darkest and 1 is the original brightness.
img {
filter: brightness(0.5);
}
Contrast Effect
The contrast effect is used to change the contrast of an image. The CSS contrast function can be used to create a contrast effect on an image. The function accepts a value between 0 and 1, where 0 is the lowest contrast and 1 is the original contrast.
img {
filter: contrast(1.5);
}
Saturate Effect
The saturate effect is used to change the saturation of an image. The CSS saturate function can be used to create a saturation effect on an image. The function accepts a value between 0 and 1, where 0 is the least saturated and 1 is the original saturation.
img {
filter: saturate(0.5);
}
Hue-Rotate Effect
The hue-rotate effect is used to change the hue of an image. The CSS hue-rotate function can be used to create a hue-rotate effect on an image. The function accepts a degree value that represents the amount of hue rotation.
img {
filter: hue-rotate(90deg);
}
Invert Effect
The invert effect is used to invert the colors of an image. The CSS invert function can be used to create an invert effect on an image. The function accepts a value between 0 and 1, where 0 is the original image and 1 is the fully inverted image.
img {
filter: invert(1);
}
Opacity Effect
The opacity effect is used to change the opacity of an image. The CSS opacity property can be used to create an opacity effect on an image. The property accepts a value between 0 and 1, where 0 is fully transparent and 1 is fully opaque.
img {
opacity: 0.5;
}
Drop Shadow Effect
The drop shadow effect is used to add a shadow to an image. The CSS box-shadow property can be used to create a drop shadow effect on an image. The property accepts several values that determine the shadow’s position, size, and color.
img {
box-shadow: 10px 10px 5px #888888;
}
Border Effect
The border effect is used to add a border to an image. The CSS border property can be used to create a border effect on an image. The property accepts several values that determine the border’s width, style, and color.
img {
border: 5px solid #000000;
}
Demo
Codepen of all css effects together.
In conclusion, CSS provides a wide range of image effects and filters that can be used to enhance the appearance of images in a website. By combining these effects and filters, you can create unique and eye-catching images that will enhance the overall look and feel of your website.
I hope this article helps you understand the basics of CSS image effects and filters. Try experimenting with these effects and filters and see how you can incorporate them into your web design projects.