Category: Tech

  • Ep. 004 – Lists, Quotations, and Comments – Learn HTML and HTML5

    In the previous post, we have discussed paragraphs, headings, and anchor tags. In this post, we will learn about how to add ordered lists, unordered lists, quotations (Blockquotes), and HTML comments.

    Lists:

    Lists are used to group related items. Lists can be ordered or unordered.

    Ordered Lists:

    To add ordered lists in an HTML page, we use <ol> tag. Then to add items to the ordered list we can use the <li> tag. See the following example code:

    Example Code:

    <ol>
       <li>List Item 1</li>
       <li>List Item 2</li>
       <li>List Item 3</li>
    </ol>

    Output:

    1. List Item 1
    2. List Item 2
    3. List Item 3

    Unordered Lists:

    To add unordered lists in an HTML page, we use <ul> tag. Then to add items to the unordered list we can use the <li> tag. See the following example code:

    Example Code:

    <ul>
       <li>List Item 1</li>
       <li>List Item 2</li>
       <li>List Item 3</li>
    </ul>

    Output:

    • List Item 1
    • List Item 2
    • List Item 3

    Blockquotes (Quotations)

    Blockquotes are used when text is copied from an external source/author. To add blockquote to an HTML page, we use the <blockquote> tag. See the following example with an output:

    Example Code:

    <blockquote>Some quotation from external source</blockquote>

    Output:

    Some quotation from external source

    HTML Comments:

    HTML comments are written inside the HTML page for reference and they are not displayed on the actual web page. The HTML comments are helpful when you are working with a team. The other members of the team can understand why a particular piece of code was added by seeing the HTML comments. See the following example:

    Example Code:

    <!--This is a sample HTML comment-->

    Output:

    The output is empty because HTML comments are not displayed on the actual page.

    Video Tutorial:

    Got Stuck? Any Questions?

    In case of any questions, please free to ask in the comments section below. Thanks for reading!

  • Ep. 005 – Images and Videos – Learn HTML & HTML5

    In the previous post, we have learned how to add lists, quotations, and comments to an HTML page. In this post, we will learn how to add images and videos to an HTML page.

    Images:

    Images are used to display the information graphically. To add images, we use the <img> tag. The “src” attribute is used to define the source/URL of the image. The “alt” attribute is used to add alternate text for the image. The alternate text is shown when the image is not loaded due to any reason. The width and height attributes are used to define the width and height of the image. See the following code example.

    <img src="demo.jpg" alt="This is a demo image" width="350" height="300"/>

    Please make sure that you have placed an image named “demo.jpg” inside the folder where you have your “index.html” file.

    Videos:

    We use the <video> tag to add videos to an HTML page. The width and height attributes can be used to adjust the width and height of the video. The “controls” attribute can be used to decide whether to show video controls or not. The <source> tag is added inside the <video> tag to define the source/URL of the video. The type attribute of the source tag is used to define the type of the video e.g. “video/mp4”. The text was written before the </video> tag i.e. ” Your browser does not support HTML videos ” and is displayed when the browser of the user doesn’t support HTML videos. See the following code example:

    <video width="350" controls>
            <source src="demo.mp4" type="video/mp4"/>
            Your browser does not support HTML videos
    </video>

    Please make sure that you have placed a video named “demo.mp4” inside the folder where you have your “index.html” file.

    Video Tutorial:

    Images and Videos – Learn HTML and HTML5

    Got Stuck? Any Questions?

    In case of any questions, please feel free to ask in the comments section. Thanks

  • WordPress Plugin Development Boilerplate

    Another contribution to the open-source community. We have developed and released a boilerplate template to develop a new WordPress plugin using Object Oriented Programming (OOP) approach. If you are a WordPress developer and want to develop a custom WordPress plugin from scratch, then this boilerplate may act as a good starting point for your new WordPress plugin.

    Folder Structure

    The boilerplate code is very well structured and organized into folders based on the type of functionality. Following is the folder structure of the boilerplate plugin:

    • assets
      • images
      • css
      • js
    • includes
      • admin
        • class-codowppb-admin.php (handle admin-specific functionality)
      • common
        • class-codowppb-common.php (handle common functionality for both admin and frontend)
      • public
        • class-codowppb-public.php (handle public facing functionality)
      • class-codowppb.php (handle core functionality of the plugin)
    • codowppb.php (main plugin file)
    • index.php
    • LICENSE.txt
    • README.md
    • README.txt
    • uninstall.php

    As can be seen from the folder structure that we have organized the folders and classes so that the functionality is loaded conditionally based on the requirements. This feature makes the plugin more organized and optimized in terms of performance.

    Features

    • Object Oriented Programming (OOP) approach
    • Folders and Classes are organised based on the type of functionality i.e. public-facing or admin-specific
    • Assets (CSS and JS) are included and properly enqueued for admin, public, and common functionality
    • Admin settings page functionality is also added to add an admin page menu for the plugin

    How To Use It?

    • Clone/download the github repository inside the wp-content/plugins folder
    • Replace the ‘codowppb’ word with your plugin name in all files, file names or folder names etc.
    • Add/modify the relevant codes according to your custom requirements

    The boilerplate plugin is hosted on GitHub as a public repository and will be updated with more features soon. The suggestions and recommendations are welcome! Thanks

  • WordPress and jQuery. What’s the Future?

    WordPress is planning major jQuery changes in version 5.5 and future versions. Since WordPress relies on jQuery which is a popular JavaScript framework, the WordPress team wants to update jQuery to the latest possible version. In the long term, they want to minimize or completely remove the reliance on the jQuery framework as mentioned in this blog post. Following are some short notes about this topic:

    • Currently, WordPress provides jQuery with version 1.12.4 released in 2016.
    • The WordPress team wants to update the jQuery version gradually because many themes and plugins are using an older version of jQuery as a dependency.
    • In the long term, the WordPress team is planning to move WordPress admin to vanilla JavaScript.
    • The WordPress team has released a plugin named Test jQuery Update which can be used to test themes and plugins compatibility with the latest jQuery update.
    • The first step in this process was the removal of jQuery Migrate 1.4.1 script from the core WordPress version 5.5 which will break some plugins and themes code.
    • The WordPress team has released a helper plugin Enable jQuery Migrate Helper which can be used if there are any issues after updating to version 5.5. This plugin re-enables jQuery Migrate and warns about the deprecated code used by themes or plugins.
    • As a second step, the WordPress version 5.6 is shipped with the updated versions of jQuery (3.5.1), jQuery Migrate (3.3.2), and jQuery UI (1.12.1).
    • The third step would be to remove jQuery Migrate dependency from the core.
    • Enabling SCRIPT_DEBUG constant in wp-config.php file can be helpful for debugging the compatibility issues due to the jQuery upgrades.

    Actionable Steps:

    • If you are a website owner, then test your website’s functionality using Test jQuery Update and Enable jQuery Migrate Helper plugins, before updating to the latest version 5.5 or later.
    • If you are a developer, then make sure to test your plugins or themes and make sure that they are compatible with the versions of jQuery, jQuery Migrate and jQuery UI bundled with the latest version of WordPress.

    References:

    • https://wptavern.com/major-jquery-changes-on-the-way-for-wordpress-5-5-and-beyond
    • https://wptavern.com/wordpress-5-6-will-ship-with-another-major-jquery-change
  • Interview Questions for WordPress Developer

    I have prepared a list of possible questions which are commonly asked or should be asked from a candidate applying for the position of a WordPress developer.

    1. What are WordPress plugins?
    2. What are WordPress themes?
    3. What are WordPress child themes?
    4. What is Gutenberg?
    5. How to choose a best WordPress plugin?
    6. Can you develop a WordPress plugin from scratch?
    7. Can you design a WordPress theme from scratch?
    8. Can you customize WordPress plugins developed using OOP concepts?
    9. What is the difference between OOP and Structural programming?
    10. What are hooks?
    11. Can you define a custom hook?
    12. What are actions?
    13. What are filters?
    14. What is the difference between actions and filters?
    15. How to extend the existing functionality of a WordPress plugin?
    16. How and where to register custom CSS/JS files with WordPress?
    17. How to make sure that the plugin you are developing, is secure?
    18. Can you give some example functions provided by WordPress to secure input fields?
    19. What do you know about _e() and __e() functions?
    20. How can we make a WordPress theme or plugin, multilingual compatible?
    21. Can you use CSS frameworks while designing custom WordPress theme?
    22. Can you use React inside a WordPress theme or plugin?
    23. Can you develop a custom Gutenberg block?
    24. What are widgets? Can you develop one from scratch?
    25. What are short-codes? Can you develop one from scratch?
    26. Should we echo or return data from the short-code?
    27. What do you know about ob_start(), ob_get_clean() functions?
    28. Which hook is used on plugin activation or deactivation?
    29. Should we use a custom database table to save our custom data or should we use post meta or other default tables provided by WordPress?
    30. Can you create a custom post type from scratch?
    31. How to create a custom archive page for custom post type?
    32. How to create a custom single post page for custom post type?
    33. Do you have experience working with WooCommerce plugin?
    34. How can we implement ajax calls in WordPress?
    35. Can you use WordPress REST API to display data on the front-end of the website?
    36. How can we expose a custom endpoint in WordPress REST API?
    37. There is “something” wrong in our website and we are seeing a death screen (white screen without any warnings or errors). How to start the debugging process?
    38. How can we enable log messages in WordPress?
    39. How can we use default jQuery provided by the WordPress?
    40. Which class is provided by WordPress to query database?
  • #01 – Introduction – TypeScript

    What is TypeScript?

    • TypeScript is a typed super-set of JavaScript
      • It means that any JavaScript code is a legal TypeScript code
      • Also we can write any JavaScript code in a Typescript file (.ts) without any error
      • It add rules about how different type of values can be used
      • It preserves the run-time behavior of JavaScript code, which means that TypeScript will not throw any “type” errors on run-time
    • TypeScript is a static type checker for JavaScript
      • Detecting errors in code without running is known as static checking
      • Determining the nature or type of error based on the type of values is known as static type checking
      • So TypeScript checks a program for errors before execution based on the type of values
    • So the bottom line is that
      • We can use TypeScript to develop our JavaScript programs
        • TypeScript provides types, classes and OOP concepts
        • TypeScript give details about errors or warnings produced by the code before the execution of the code
        • It highlights the unexpected behavior in code, lowering the chance of bugs
      • Then TypeScript compiler converts the code back to JavaScript code without the TYPES information
    //Example Code:
    
    const obj = { width: 10, height: 15 };
    const area = obj.width * obj.heigth;

    Error: Property ‘heigth’ does not exist on type ‘{ width: number; height: number; }’. Did you mean ‘height’?

    Above code will produce this error in TypeScript

    Types in TypeScript

    • TypeScript (TS) can infer types from existing JavaScript (JS) variables using their values
      • So TS automatically assign types to the existing JS code
      • Which means that now TS will warn us about warnings or errors in the JS code before execution (Excellent! Not?)
    • TS also allows to define types manually
    • TS provides Unions and Generics to create complex types combining simple types

    References:

    • https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html
  • #00 – Concepts and Notes – JavaScript

    Following is a list of core JavaScript concepts:

    • History
      • Developed in 1995 by Brendan Eich
      • Initially named as LiveScript
      • Also known as ECMAScript
      • JS has no concept of input or output
      • It runs in an hosted environment like Node Server or Browsers
    • Overview
      • JS is a multi-paradigm, dynamic language
      • Syntax is similar to Java and C languages
      • It supports object oriented approach using objects prototypes instead of classes
      • It also supports functional programming
    • Types
      • Number
      • String
      • Boolean
      • Symbol
      • Object
        • Function
          • Inner Functions
        • Array
        • Date
        • RegExp
      • Null
      • Undefined
    • Variables
      • Let
      • Const
      • Var
    • Operators
      • Numberic
      • Plus (+)
      • Comparison
      • Bitwise
    • Control Structures
      • if-else
      • while loop
      • do-while loop
      • for loop
      • for-of loop
      • for-in loop
      • switch

    References:

    • https://developer.mozilla.org/en-US/docs/Learn
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
  • #02 – Core Concepts – Learn GraphQL

    In this post, we have discussed the core GraphQL concepts e.g. schema, types, queries, mutations, and subscriptions with example codes.

    Core Concepts of GraphQL

    • Schema
    • Types
    • Queries
    • Mutations
    • Subscriptions
    • Resolvers

    Scheme

    • The schema defines how a client can read and manipulate (add, update, and delete) data
    • It represents a contract between client and server
    • It consists of GraphQL types and the special root types
    • Root types define the entry points for the API (type Query, type Mutation, type Subscription)

    Types

    • GraphQL provides schema definition language (SDL) to define simple types
    • Types define the structure of the data and how the data is manipulated
    • GraphQL allows creating relationships between types

    Example Code

    //User type
    type User{
       id: ID!
       name: String!
       courses: [Course!]!
    }
    //Course type
    type Course{
       id: ID!
       title: String!
       url: String
       author: User!
    }
    // ! indicates that the field is required
    // One to many relationship is defined between User and Course //types

    Queries

    • Queries are used to fetch (read) data from GraphQL API
    • A query specifically describes what data it needs in the response
    • Arguments are passed in the queries to return/alter data based on the arguments
    • Queries can be used to get nested or relational data as well

    Example Code

    type Query{
       getCourses(last: Int): [Course!]!
    }
    //get all courses with only title field
    {
       courses: {
          title
       }
    }
    //get all courses with author info i.e. name
    {
       courses: {
          title
          author: {
             name
          }
       }
    }

    Mutations

    • Mutations are used to modify data i.e. create, update or delete
    • Mutations accept arguments (input) and payload (expected output)

    Example Code

    type Mutation {
        addUser(name: String!): User
    !
    }
    mutation {
       addUser (name: "junaid", courses: []) {
          id
          name
       }
    }

    Subscriptions

    • GraphQL subscriptions provide real-time updates to the subscribers
    • Whenever new data is added, the subscriptions notified or pushes the data back to the subscriber in real-time
    type Subscription{
       addUser: User!
    }
    subscription {
      newUser{
        id
        name
      }
    }

    Resolvers

    • For each query and mutation, there is a resolver function with the same name as the query or mutation
    • The resolver function communicates with the appropriate data source and sends the response
    //import Course from "../../models/Course"; mongoose model
    Query: {
        async allCourses() {
          try {
            const courses = await Course.find();
            return courses;
          } catch (err) {
            throw new Error(err);
          }
        }
    },
    Mutation: {
        async addCourse(parent, { name, url }, context, info) {
          try {
            const course = await new Course({name, url});
            return course.save();
          } catch (err) {
            throw new Error(err);
          }
        }
    }
  • #01 – Introduction – Learn GraphQL

    In this post, we have discussed what is GraphQL, the differences between REST API’s and GraphQL API development architectures, and an example scenario to elaborate on the differences between the two approaches.

    What is GraphQL?

    • It is a new API development standard
    • It is a query language for API’s
    • It provides declarative syntax to fetch data from multiple data sources
    • It’s an alternate to REST API development architecture
    • Unlike REST, it exposes only a single endpoint to respond to queries
    • It solves the problem of over-fetching and under-fetching the data
    • It speeds up the development because we don’t need to adjust API every time the front-end app data requirements are adjusted

    What are the differences between REST and GraphQL architectures?

    • A REST endpoint provides all the data (fields) returned by the endpoint whereas the GraphQL endpoint only provides the requested data (fields) thus improving the performance
    • In the case of REST, multiple requests are made to fetch data from different REST endpoints whereas the GraphQL endpoint can combine and return data from multiple queries in a single request

    Example Scenario:

    Let’s say you have a front-end application page where you want to display the author’s name with 3 posts of that author and 3 comments on each post. If we have a REST API we will call 3 endpoints to implement this feature:

    1. Call /users/<id> endpoint to fetch the user (author) information
    2. Call /users/<id>/posts endpoint to fetch all posts by the user (author)
    3. Call /posts/<id>/comments endpoint to fetch all comments on each post

    As you can see that we need to call 3 endpoints separately to get all the required data. Moreover, we are fetching all user posts and all post comments whereas we only need to display 3 posts and 3 comments on each post.

    GraphQL simplifies this process and provides a more efficient way to handle these kind of scenarios. The above data can be received from single query to GraphQL API as follows:

    {
       user(id: "123"){
          name,
          posts(id: "12344...", last: 3){
             title,
             description,
             comments(id: "453355...", last: 3){
                text,
                author
             }
          }
       }
    }

    In the next post, we will learn about the core concepts of the GraphQL.

  • #02 – Data Fetching – Learn Next.js

    Next.js provides three functions to fetch data for pre-rendered pages:

    getStaticProps():

    1. Used for static generation (pre-rendering technique)
    2. Fetches data at build-time
    3. When an async function getStaticProps() is called from the page component, the next.js will pre-render this page at build time using the props returned by that function (see Examples)
    4. The context parameter used as an argument of getStaticProps() function is an object containing following parameters (see details here):
      1. params
      2. preview
      3. previewData
      4. locale
      5. locals
      6. defaultLocale
    5. getStaticProps() function returns an object with following parameters (see details here):
      1. props (required)
      2. revalidate
      3. notFound
      4. redirect
    6. Imports used inside the getStaticProps() function are not bundled for the client side
    7. Server side code can be written inside the getStaticProps() function e.g. to read files on the server or to communicate with the database
    8. API routes defined inside the next.js app should not be called inside getStaticProps() function using fetch() instead import the API route and call its function
    9. Incremental Static Regeneration
      1. Used to update the statically served page in the background after some interval defined as revalidate parameter
    10. Query parameters are not available inside the getStaticProps() function because it runs on the build-time instead of request-time
    11. Server-side code (e.g. database queries) can be written securely inside this function because this function only runs on the server side and is not included in client-side bundle
    12. This function saves the returned data inside a JSON file along with the HTML file which can then be used for future page requests using next/link or next/router
    13. This means that in client-side page transitions, the getStaticProps() function is not called instead the data saved in the JSON file is passed to the component
    14. getStaticProps() function can only be exported from pages
    15. In development (npm run dev), getStaticProps() function is called on every request

    Example (JavaScript):

    //https://nextjs.org/docs/basic-features/data-fetching
    // posts will be populated at build time by getStaticProps()
    function Blog({ posts }) {
      return (
        <ul>
          {posts.map((post) => (
            <li>{post.title}</li>
          ))}
        </ul>
      )
    }
    
    // This function gets called at build time on server-side.
    // It won't be called on client-side, so you can even do
    // direct database queries. See the "Technical details" section.
    export async function getStaticProps(context) {
      // Call an external API endpoint to get posts.
      // You can use any data fetching library
      const res = await fetch('https://.../posts')
      const posts = await res.json()
    
      // By returning { props: posts }, the Blog component
      // will receive `posts` as a prop at build time
      return {
        props: {
          posts,
        },
        // Next.js will attempt to re-generate the page:
        // - When a request comes in
        // - At most once every second
        revalidate: 1, // In seconds
      }
    }
    
    export default Blog

    Example (TypeScript):

    import { InferGetStaticPropsType } from 'next'
    
    type Post = {
      author: string
      content: string
    }
    
    export const getStaticProps = async (context) => {
      const res = await fetch('https://.../posts')
      const posts: Post[] = await res.json()
    
      return {
        props: {
          posts,
        },
        // Next.js will attempt to re-generate the page:
        // - When a request comes in
        // - At most once every second
        revalidate: 1, // In seconds
      }
    }
    
    function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
      // will resolve posts to type Post[]
    }
    
    export default Blog

    getStaticPaths():

    • Used for pre-rendering of paths (or dynamic routes e.g. /pages/posts/[id].js) at build-time
    • This function need to return paths object (required)
    • The paths returned using paths object are pre-rendered at build-time
    • Fallback key is also required and can have either true or false values
    • fallback: false means that the pages other than the returned from paths object will show 404
    • fallback: false is useful if there are small number of pages to be statically generated otherwise the build time will be increased
    • fallback: true can be used if you want to pre-render some pages at build-time then load the other pages when they are requested using the Fallback pages (see example – fallback: true)

    fallback: true is useful if your app has a very large number of static pages that depend on data (think: a very large e-commerce site). You want to pre-render all product pages, but then your builds would take forever.

    Instead, you may statically generate a small subset of pages and use fallback: true for the rest. When someone requests a page that’s not generated yet, the user will see the page with a loading indicator. Shortly after, getStaticProps finishes and the page will be rendered with the requested data. From now on, everyone who requests the same page will get the statically pre-rendered page.

    This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation.

    fallback: true will not update generated pages, for that take a look at Incremental Static Regeneration.

    https://nextjs.org/docs/basic-features/data-fetching#when-is-fallback-true-useful

    Example (fallback: false):

    // pages/posts/[id].js
    
    function Post({ post }) {
      // Render post...
    }
    
    // This function gets called at build time
    export async function getStaticPaths() {
      // Call an external API endpoint to get posts
      const res = await fetch('https://.../posts')
      const posts = await res.json()
    
      // Get the paths we want to pre-render based on posts
      const paths = posts.map((post) => ({
        params: { id: post.id },
      }))
    
      // We'll pre-render only these paths at build time.
      // { fallback: false } means other routes should 404.
      return { paths, fallback: false }
    }
    
    // This also gets called at build time
    export async function getStaticProps({ params }) {
      // params contains the post `id`.
      // If the route is like /posts/1, then params.id is 1
      const res = await fetch(`https://.../posts/${params.id}`)
      const post = await res.json()
    
      // Pass post data to the page via props
      return { props: { post } }
    }
    
    export default Post

    Example (fallback: true):

    // pages/posts/[id].js
    import { useRouter } from 'next/router'
    
    function Post({ post }) {
      const router = useRouter()
    
      // If the page is not yet generated, this will be displayed
      // initially until getStaticProps() finishes running
      if (router.isFallback) {
        return <div>Loading...</div>
      }
    
      // Render post...
    }
    
    // This function gets called at build time
    export async function getStaticPaths() {
      return {
        // Only `/posts/1` and `/posts/2` are generated at build time
        paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
        // Enable statically generating additional pages
        // For example: `/posts/3`
        fallback: true,
      }
    }
    
    // This also gets called at build time
    export async function getStaticProps({ params }) {
      // params contains the post `id`.
      // If the route is like /posts/1, then params.id is 1
      const res = await fetch(`https://.../posts/${params.id}`)
      const post = await res.json()
    
      // Pass post data to the page via props
      return {
        props: { post },
        // Re-generate the post at most once per second
        // if a request comes in
        revalidate: 1,
      }
    }
    
    export default Post

    getServerSideProps():

  • #01 Introduction – Learn Next.js

    What is Next.js?

    Next.js is a framework used to develop production ready React applications. Next.js provides many useful features e.g. pre-rendering, smart bundling, dynamic file-based routing, route pre-fetching and many more. In this blog post, we have discussed the prerequisites, how to create next.js application, next.js pages, and pre-rendering techniques.

    Prerequisites:

    Create New Application:

    • Open Command Prompt, CD into the folder where you want to create the application
    • Run the command:
    npx create-next-app
    • CD into the app folder
    • Run the command npm run dev to start the app in development mode
    • Run the command npm run build to generate the optimized build which can be used for production purposes
    • Run the command npm run start to start the production server

    Pages in Next.js:

    • In next.js, pages are React components and are available inside the pages folder
    • The names of the component files become the URL of the page
    • For example /pages/about.js component is accessible via /about URL
    • Dynamic routes can be implemented by creating dynamic files e.g. /pages/posts/[id].js which expose the URL like /posts/1, /posts/2 etc.

    Pre-rendering:

    In next.js, pages are pre-rendered before they are displayed in the browser which improves the performance and SEO of the web pages. Next.js let you choose the pre-rendering technique for each page. Next.js support two type of pre-rendering:

    • Static Generation
      • Recommended by Next.js
      • HTML of the page is generated once at build time and is reused on each request
      • Improved performance due to the CDN caching with no extra configuration
      • A page can be generated statically with or without data
      • Static Generation without Data
        • This is the default pre-rendering technique
        • These pages do not require to fetch any data from external sources
        • HTML page is generated at build time when we run npm run build
      • Static Generation with Data
        • These pages require to fetch data from external sources e.g. an API
        • If page contents are fetched from external source, then use getStaticProps() function
        • If page paths are fetched from external source, e.g. in case of dynamic routing, then use getStaticPaths() function
        • Some pages may require both features so both functions can also be used on that page
        • These functions gets called at build time and populate the dynamic content from external sources
      • Static generation is always recommended in the cases when the page can be pre-rendered ahead of a user’s request
      • Static generation is not recommended in the cases when the page data is frequently updated or if page content is updated on every request
        • In that case either use static generation with client-side rendering where some parts can be pre-rendered and the others on client-side
        • OR use server side rendering where all content of the page is populated on each request
    • Server side Rendering
      • The HTML of the page is generated on each request
      • To use server side rendering export async function getServerSideProps() from the bottom of the page
      • This function is called by the server on each request

    Client-side rendering is also supported in next.js where some parts of the pages can be rendered by the client side JavaScript.

    References:

    https://nextjs.org/docs/

  • Ep. 001: What is HTML? Learn HTML & HTML5

    This post belongs to the HTML course titled “Learn HTML & HTML5”. In this post, we have discussed what is HTML?

    • HTML stands for Hyper Text Markup Language
    • It’s not a programming language
    • HTML is used to define markup/contents of a web page
    • HTML provides tags for different type of contents e.g. link (<link>), paragraph (<p>), image (<img>), video (<video>) etc.
    What is HTML?

    All websites are built using HTML tags, so HTML is the most important language to learn.

    If you have any questions, please let us know in the comments section. Thanks

  • WordPress Security Checklist

    Following are some general recommendations to enhance security of a WordPress website.

    1. Use a security plugin e.g. Wordfence (if not already installed) and make sure that it’s updated to the latest version. Following is a short summary of recommended Wordfence settings:
      1. Make sure that the “Enabled and Protecting” mode is enabled after the “Learning” period is ended.
      1. In “Protection Level”, make sure to optimize the Wordfence firewall by enabling the Extended Protection mode.
      1. Upgrade the plugin to the premium version to enable the “Real Time IP Blacklist” feature to protect the website from malicious activities using the updated and latest database.
      1. The other default firewall settings are good to start with. These options can be changed in specific scenarios.
      1. The recommended scan type for most of the cases is “Standard”. The other options can be used in specific scenarios.
      1. Make sure to upgrade the plugin to the premium to use the latest malware signature during the scans. The free version of the plugin updates the malware signature list after 30 days.
      1. Moreover, the premium version enables the Reputation Checks (recommended) for ‘spamvertising’, spam identification and domain blacklist checking.
      1. Make sure the issues reported in the scan results are fixed.
      1. Wordfence tools like live traffic, whois lookup, import/export and diagnostics are really helpful in diagnosing the website’s traffic, IP address identification, sharing the Wordfence settings among WordPress websites and diagnosing the plugin conflicts or configuration issues respectively.
      1. Wordfence provide login security tools like Two Factor Authentication (2FA) which is the latest and most secure form of authentication and Google reCaptcha to protect the forms from bot attacks.
    2. Make sure that WordPress core, theme(s) and plugins are updated to the latest versions
    3. Make sure that PHP, MySQL and nginx are updated to the latest stable versions. There may be certain issues after updating the PHP version of the website. Please refer to this blog post about Important points to consider before and after updating PHP version for WordPress website
    4. IP Restriction at nginx level can also be applied to restrict access to the WordPress admin dashboard
    5. Remove all inactive theme(s) or plugins from the website
    6. Make sure that properly licensed themes and plugins are installed/activated on the website
    7. Visit Tools -> Site Health to see if there are any major issues reported to be fixed

  • NPM Commands Not Working in Integrated Terminal of VSCode

    Visual Studio Code (VSCode) provides an integrated terminal to run commands inside the current directory. Recently, I installed VSCode and tried to run the NPM commands and it shows following errors:

    internal/modules/cjs/loader.js:968
      throw err;
      ^
    
    Error: Cannot find module 'C:\Program Files\nodejs\node_modules\npm\bin\node_modules\npm\bin\npm-cli.js'
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
        at Function.Module._load (internal/modules/cjs/loader.js:841:27)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
        at internal/main/run_main_module.js:17:47 {
      code: 'MODULE_NOT_FOUND',
      requireStack: []
    }
    internal/modules/cjs/loader.js:968
      throw err;
      ^
    
    Error: Cannot find module 'C:\Program Files\nodejs\node_modules\npm\bin\node_modules\npm\bin\npm-cli.js'
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
        at Function.Module._load (internal/modules/cjs/loader.js:841:27)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
        at internal/main/run_main_module.js:17:47 {
      code: 'MODULE_NOT_FOUND',
      requireStack: []
    }

    Reasons:

    This error could be due to the following reasons:

    1. The Node/NPM path is not added in the Environment Variable PATH (for Windows)
    2. You are not running VSCode as an administrator

    Solutions:

    1. To add Node path to the Environment Variable PATH, follow the instructions here
    2. Change the default shell of Integrated Terminal to Command Prompt.
    3. Close VSCode and open VSCode as an administrator
    4. To automatically run VSCode as an administrator, follow the instructions listed here

    I hope it will help to resolve these errors. 🙂

  • Common PHP Warnings/ Errors and their Solutions

    Recently, we have updated our PHP version to the latest stable version (7.4.9) for our WordPress website. After the update we started getting PHP warnings. We have listed some of the warnings with their possible solutions in this blog post.

    E_WARNING:

    count(): Parameter must be an array or an object that implements Countable

    Solution:

    // replace this kind of code:
    if (count($array_name) > 0)
    // with
    if (is_countable($array_name) && count($array_name) > 0)

    E_WARNING:

    Invalid argument supplied for foreach()

    Solution:

    // replace following kid of code:
    foreach ($array_name as $item) {
     // ...
    }
    // with
    foreach ((array) $array_name as $item) {
     // ...
    }

    References:

    • https://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach
    • https://wordpress.org/support/topic/count-parameter-must-be-an-array-or-an-object-that-implements-countable-6/

  • Get Started with Redux in React Application

    npm install --save react-redux @reduxjs/toolkit

    Create a file src/store/index.js and add following code in it:

    import { configureStore } from '@reduxjs/toolkit';
    import { combineReducers } from 'redux';
    const reducer = combineReducers({
      // here we will be adding reducers
    })
    const store = configureStore({
      reducer,
    })
    export default store;

    To link our app with the redux store update the main app file as follows:

    ...
    ...
    import { Provider } from 'react-redux';
    import store from './store';
    
    ReactDOM.render(
      <Provider store={store}>
          <App />
        </Provider>
    ,
      document.getElementById('root')
    );
  • Angular Concepts

    In this blog post, we have discussed some JavaScript and Angular concepts.

    What is the difference between synchronous and asynchronous approach in programming?

    In synchronous approach, the next statement will not be executed until the completion of the previous statement. Whereas, in asynchronous approach, the next statement will not wait for the completion of the previous statement.

    What is observable?

    An observable is a declarative function which can be subscribed to take actions on the received results. The observables are/can be:

    • Declarative i.e. they are executed only when they are subscribed
    • Unsubscribed as well
    • Used for asynchronous processing of statements
    • Angular uses RxJS library for observables

    What is a Promise in JavaScript?

    A promise object can return values in an asynchronous way. A promise maybe in 1 of the 3 states: fulfilled, rejected or pending. Promises are executed at the same time when they are created.

    What is the Difference between Observable and Promise?

    • Observable is declarative which means it’s executed only when subscribed whereas the promise is imperative which is executed as soon as it’s created.
    • Observables provide many values whereas the promises provide single value.
    • Observables are cancellable whereas the promises are not.

    What is ForkJoins?

    Forkjoin is used to execute multiple promises (e.g. http requests) in parallel and returns a single array containing the response from each observable.

    References:

  • How to Optimize an Angular Application?

    In this blog post, we have listed some of the techniques which can be used to first measure the performance of an angular application and then optimize the speed, loading time and performance of an angular application.

    How to Measure the Performance of an Angular Application?

    To measure the performance of an angular application, generate a production build of the app using following command in the root directory of Angular CLI project:

    ng build --prod --source-map

    We can use an npm package source-map-explorer to analyze and generate a report of the performance of the angular application. To get started, install the npm package using the following command:

    npm install source-map-explorer

    Now add following line inside the scripts section of the package.json file:

    "bundle:report": "source-map-explorer dist/demo-app/**/*.js"

    Please change the project name i.e. ‘demo-app’ to the name of your project.

    Now we can run the following command to generate the performance report of the app:

    npm run bundle:report

    Following are some of the techniques to optimize the speed, loading time and performance of an angular application:

    1. Lazy Loading

    Lazy loading means loading the resources, required for the component, only when that particular component is requested to load. It improves the performance of the angular application. In an angular application, lazy loading is implemented by dividing the application into modules.

    Resources:

    2. Preloading

    Preloading helps to improves the performance of the angular application by preloading the resources in cache required for faster future navigation.

    Resources:

    3. Web Workers

    Web workers are used to offload certain heavy functionality from the main application thread thus improving the performance of the angular application.

    4. Optimization of Template Expressions

    Try not to use high computation functions/methods inside the template expressions to improve the performance of the angular application.

    5. Optimize the Use the NgZone/Zone for Change Detection

    ngzone/zone library is used to detect the changes and then reloading the component’s view with updated data. To avoid updating the reloading of the view on each small change runOutsideAngular method of ngzone can be used to improve the performance of the application.

  • Angular Application is not working in IE11?

    If your angular application is not working in IE11, then the following simple steps can be used to make it work.

    1. Install the following packages using npm
      1. npm install –save classlist.js
      2. npm install –save web-animations-js
    2. Go into polyfills.ts file and uncomment the following lines
      1. import ‘classlist.js’;
      2. import ‘web-animations-js’;
    3. Go into tsconfig.ts file and change the ‘target’ attribute to ‘es5’
    4. Go into index.html file and add the following meta tag in the head tag
      1. <meta http-equiv=”X-UA-Compatible” content=”IE=edge” />

    That’s all, I hope it will help.

  • Server Side Pagination Using NodeJS, MongoDB and Angular Material Tables

    Normally, we use Angular Material’s data tables with pagination (mat-paginator) to list the results. This is not an efficient and optimal approach particularly if there are lots of records to show in the table. Angular Material’s pagination just divides the received records into the paginated records. So, if we need to display lots of records in data tables, then the efficient and optimal approach is to use Server Side Pagination. Following, sections will demonstrate the server-side pagination using NodeJS (API), MongoDB (database), and Angular Material data tables.

    API using NodeJS and MongoDB

    Following is a sample code, written in NodeJS with MongoDB model which query records from a MongoDB collection based on the current page (page), number of records per page (pageSize), and page type (pageType) (first, last, page). Depending on the type of page, MongoDB query is prepared which then returns the total records (count) matching the query, paginated records (depending on pageSize) (data), and the current page (currentPage).

    router.post('/paginated/', (req, res) => {
        // get page from query params or default to first page
        const page = parseInt(req.query.page) || 1;
        const pageType = req.query.pageType || 'first';
        const pageSize = parseInt(req.query.pageSize) || 5;
        if(pageType == 'first'){
            PermissionUsage.countDocuments({}).exec(function(err, count) {
                if (err) return res.status(500).json({success: false, message: err.message});
                PermissionUsage.find({}).limit(pageSize).exec(function(err, permissionUsages) {
                    if (err) return res.status(500).json({success: false, message: err.message});
                    res.status(200).send(JSON.stringify({success: true, data: permissionUsages, pager: {total: count, currentPage: page}}));
                });
            });
        }else if(pageType == 'page'){
            PermissionUsage.countDocuments({}).exec(function(err, count) {
                if (err) return res.status(500).json({success: false, message: err.message});
                PermissionUsage.find({}).skip((page-1)*pageSize).limit(pageSize).exec(function(err, permissionUsages) {
                    if (err) return res.status(500).json({success: false, message: err.message});
                    res.status(200).send(JSON.stringify({success: true, data: permissionUsages, pager: {total: count, currentPage: page}}));
                });
            });
        }else{
            PermissionUsage.countDocuments({}).exec(function(err, count) {
                if (err) return res.status(500).json({success: false, message: err.message});
                PermissionUsage.find({}).skip((page-1)*pageSize).limit(pageSize).exec(function(err, permissionUsages) {
                    if (err) return res.status(500).json({success: false, message: err.message});
                    res.status(200).send(JSON.stringify({success: true, data: permissionUsages, pager: {total: count, currentPage: page}}));
                });
            });
        }
    });
    

    Requesting Paginated Data From Angular Application

    myService.service.ts

    getPaginatedPermissionUsage(page, pageType, pageSize){
        return this.http.get('http://localhost:3000/permission-usages/paginated/?page='+page+'&pageType='+pageType+'&pageSize='+pageSize);
      }

    In a service we have created a method which calls our API’s endpoint to receive the paginated records. Here page parameter represents the current page, pageType represents whether the page is first, last or normal page and pageSize represents the number of records per page.

    myComponent.component.ts

    pager:any = {currentPage: 1, total: 0};
    page: number = 1;
    pageType: string = 'first';
    totalPages: number = 1;
    pageSize: number = 5;
    ....
    ....
    ....
    getPaginatedResults(pageNumber = 1){
    this.page = pageNumber;
    if(this.page == 1){
          this.pageType = 'first';
    }else if(this.page == window.Math.ceil(this.pager.total/this.pageSize)){
          this.pageType = 'last';
    }else{
          this.pageType = 'page';
    }
    this.myService.getPaginatedPermissionUsage(this.page, this.pageType, this.pageSize).subscribe((res:any) => {
          this.pager = res.pager;
          this.totalPages = window.Math.ceil(this.pager.total/this.pageSize);
          this.dataSource.data = res.data;
    });
    }

    myComponent.component.html

    <ul *ngIf="pager.total && pager.total > pageSize" class="pagination">
            <li class="page-item first-item">
                <a routerLink="/reports" [queryParams]="{ page: 1 }" [ngClass]="{disabled:pager.currentPage == 1}" *ngIf="pager.currentPage != 1" (click)="getPaginatedResults(1)" class="page-link">First</a>
            </li>
            <li class="page-item previous-item">
                <a routerLink="/reports" [queryParams]="{ page: pager.currentPage - 1 }" [ngClass]="{disabled:pager.currentPage == 1}" *ngIf="pager.currentPage != 1" (click)="getPaginatedResults(pager.currentPage - 1)" class="page-link">&laquo;</a>
            </li>
            <li *ngFor="let dummy of ' '.repeat(totalPages).split(''), let x = index" class="page-item number-item">
                <a routerLink="/reports" [queryParams]="{ page: x+1 }" [ngClass]="{active:pager.currentPage == x+1}" class="page-link" (click)="getPaginatedResults(x+1)">{{x+1}}</a>
            </li>
            <li class="page-item next-item">
                <a routerLink="/reports" [queryParams]="{ page: pager.currentPage + 1 }" *ngIf="pager.currentPage != totalPages" (click)="getPaginatedResults(pager.currentPage + 1)" class="page-link">&raquo;</a>
            </li>
            <li class="page-item last-item">
                <a routerLink="/reports" [queryParams]="{ page: totalPages }" *ngIf="pager.currentPage != totalPages" class="page-link" (click)="getPaginatedResults(totalPages)">Last</a>
            </li>
    </ul>

    This might not be the best implementation of the server-side pagination with MongoDB and Angular Material data tables but it works. Please feel free to share any alternate or better implementation of the server-side pagination.