Friday, December 29, 2023

Adapter Design Pattern in C#

The Adapter Design Pattern is a structural pattern that allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces, enabling them to collaborate seamlessly without modifying their existing code.The adapter plays the role of converter or translator.

This pattern is particularly useful when integrating new components or systems that have different interfaces from the ones already in use.

To handle the incompatibility, we use different approaches, and based on that, we can classify the Adapter Pattern into 2 parts.

  • Object Adapter Pattern
  • Class Adapter Pattern

Thursday, December 28, 2023

Response Caching in .NET Core with Example

Response Caching in .NET Core

Caching responses is a powerful technique to improve the performance and scalability of web applications. In .NET Core, response caching is a feature that helps store the output of an action method for a specified duration, allowing subsequent requests to retrieve the cached result instead of re-executing the action.

How to Implement Response Caching in .NET Core?

  1. Enable Response Caching in Startup.cs

    In the ConfigureServices method of Startup.cs, enable response caching by adding the required services.

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCaching();
        // Other configurations...
    }
        

Wednesday, December 27, 2023

Distributed Caching in .NET Core with Example

Distributed Caching in .NET Core

In .NET Core, managing caching efficiently can significantly enhance the performance of applications.IDistributedCache interface provides a unified approach to caching data in a distributed environment, allowing seamless integration with various caching systems like Redis, SQL Server, or in-memory cache.

What is IDistributedCache?

IDistributedCache is an abstraction in .NET Core that enables applications to interact with distributed cache stores. It offers methods to set, retrieve, and remove cached data in a consistent manner across different cache providers.

Monday, December 25, 2023

IMemoryCache in .NET Core with Example

IMemoryCache in .NET Core

In .NET Core, managing caching efficiently can significantly enhance the performance of applications. The IMemoryCache interface plays a pivotal role in caching data in memory, providing a simple and effective way to store and retrieve cached data within your applications. This post aims to provide an in-depth understanding of IMemoryCache and its implementation with illustrative examples.

What is IMemoryCache?

IMemoryCache is an interface provided by the .NET Core framework, designed to cache data in memory within an application. It enables developers to temporarily store frequently accessed data, reducing the need to fetch it from the original source repeatedly.

Monday, December 18, 2023

What is the difference between IMemoryCache and IDistributedCache?

IMemoryCache and IDistributedCache are both interfaces in ASP.NET Core used for caching data, but they differ in terms of scope and storage.

IMemoryCache

  • Scope: Local to the application instance.
  • Storage: Caches data in the memory of the local application.
  • Usage: Ideal for scenarios where data needs to be cached within the same application instance and doesn't need to be shared across multiple instances or servers.
  • Pros: Faster access since it operates within the application's memory.
  • Cons: Limited to a single instance and doesn't support sharing data between different instances or servers.

Sunday, December 17, 2023

What is CacheEntryOptions in .NET Core

CacheEntryOptions in .NET Core

Caching plays a crucial role in enhancing the performance and scalability of applications. In .NET Core, MemoryCache class enables storing frequently accessed data in memory, facilitating quick retrieval. To tailor cached item behavior, developers can utilize CacheEntryOptions. This post delves into CacheEntryOptions and its role in customizing caching behavior in .NET core applications.



What are CacheEntryOptions?

CacheEntryOptions, found in the Microsoft.Extensions.Caching.Memory namespace, empowers developers to configure various settings related to cached items in MemoryCache. These options allow control over properties such as expiration time, priority, and post-eviction callbacks for cached items.

Key Properties of CacheEntryOptions

  1. AbsoluteExpiration and AbsoluteExpirationRelativeToNow:These properties allow specifying when a cached item should expire, either at an absolute time or after a certain duration from its addition to the cache.
  2. SlidingExpiration:SlidingExpiration enables defining a time window after which the cached item expires if not accessed. Each access to the item resets the sliding window.
  3. Priority:CacheEntryOptions lets you set the priority of cached items, affecting their likelihood of being removed from the cache upon expiration or when the cache needs space for new items.

Monday, December 11, 2023

Prototype Design Pattern in C#

What is Prototype Design Pattern?

The prototype design pattern is a creational design pattern that allows creating new objects by cloning an existing object. This pattern is useful when the creation of an object is costly or complex, and we want to avoid repeating the same process for each new instance. By using the prototype pattern, we can create new objects by copying the properties and behaviors of an existing object, and then modifying them as needed.

One of the benefits of the prototype pattern is that it reduces the dependency on subclasses and factory methods. Instead of creating objects using specific constructors or factory methods, we can use a generic prototype object that can be cloned and customized. This makes the code more flexible and extensible, as we can add new types of objects without changing the existing code.

Components of Prototype Pattern

  • Prototype: This will be an interface or abstract class used for the types of objects that can be cloned. In our example, it is going to be the Employee Abstract Class.
  • ConcretePrototype: This class will implement the Prototype abstract class or interface for cloning. In our example, it will be the PermanetEmployee and TemporaryEmployee Classes.
  • Client: The client is the class that creates a new object by asking a prototype to clone itself.

Monday, December 4, 2023

Builder Design Pattern in C#

What is the Builder Design Pattern?

The Builder Design Pattern is a creational design pattern that helps in constructing complex objects step by step. It separates the construction of an object from its representation, allowing the same construction process to create different representations. In C#, the Builder pattern is widely used to create objects with varying configurations while keeping the construction process unchanged.

The key idea is to separate the construction of a complex object from its representation, allowing the same construction process to create different representations.

So, the Builder Design Pattern is all about separating the construction process from its representation. When the construction process of your object is very complex, only you need to use the Builder Design Pattern.

COmponents of Builder Design Pattern

  • Abstract Builder: The Builder is an interface defining all the steps to make the concrete product.
  • Concrete Builder: The Concrete Builder Classes implements the Abstract Builder interface and provides implementation to all the abstract methods. The Concrete Builder is responsible for constructing and assembling the individual parts of the product by implementing the Builder interface. It also defines and tracks the representation it creates.
  • Director: The Director takes those individual processes from the Builder and defines the sequence to build the product.
  • Product: The Product is a class, and we want to create this product object using the builder design pattern. This class defines different parts that will make the product.

Monday, November 27, 2023

Angular17 - Deferred Loading Using Defer Block

Angular17 - Deferred Loading Using Defer Block

Angular 17 recently came out with several exciting updates.it has an exciting new feature called deferred loading

Lazy loading is a method that helps web apps load things like scripts only when necessary. Instead of loading everything at the start, it waits to load less important stuff until the user does something like interacting with the page or scrolling to a certain point.

Lazy loading improves the user experience by making the initial page load faster. This means users can begin using the app sooner while the less important parts load quietly in the background. It also decreases the amount of internet data needed and eases the strain on the server.

In earlier versions of Angular, we were able to load a specific part of the application later using the Router, or by using dynamic imports along with ngComponentOutlet.

Angular17 now has a @defer control block enabling lazy-loading of the content of the block. Lazy-loading also applies to the dependencies of the content of the block: all the components, directives and pipes will be lazy-loaded, too.

I will demonstrate the key aspects of lazy loading in Angular 17, such as

  • Using @defer with a logical expression
  • Using @defer with a declarative trigger condition

Sunday, November 19, 2023

Angular 17 : New control flow syntax

Angular17- New control flow

Angular 17 recently came out with several exciting updates. One notable addition is the Control Flow feature. This new feature simplifies template writing by introducing a direct way to handle control flow within the template itself. Now, there's no need to rely on directives like *ngIf, *ngFor, and *ngSwitch for control flow as this new syntax streamlines the process.

This post will demonstrate a basic project using a new control flow method, moving away from the traditional directive-based approach. You can go through my other Angular post here.Let's begin right away!

Angular Project Setup

Before we start using the new feature, let's make sure you have an Angular project set up and ready to go. If you haven't done so yet, create a new Angular project using these commands with the Angular CLI:

npm install -g @angular/cli@latest
ng new ng17-control-flows

This command creates a fresh Angular project, including all the essential files and dependencies with the latest version.

Once it's set up, open the app.component.html file and remove the default Angular code. Let's add a basic HTML structure to it instead.

<h1>NG -17 :New Control Flows</h1>

Conditionally rendered control blocks: @if and @else

Let’s start with the replacement of *ngIf.

In the first example, I create a checkbox and bind it to the isChecked property.Starting with a default value of true, the checkbox appears checked, displaying the content within the @if block.The examples below are from the app.component.html template file:

Sunday, November 5, 2023

Abstract Factory Design Pattern in C#

In this article, I will explain the Abstract Factory Design Pattern in C# with practical examples. I encourage you to check out our previous article, which covers the Factory Design Pattern in C# along with an example.The Abstract Factory Design Pattern falls under the category of creational design patterns and is widely applied in real-world software development. In this article, we'll explore the following topics

What is the Abstract Factory Design Pattern?

The Abstract Factory Design Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is a higher-level pattern than the Factory Method pattern, which deals with creating individual objects, while the Abstract Factory creates families of objects.

"Abstract" means hiding details, "Factory" refers to the entity that creates things, and "Pattern" indicates a design approach. Therefore, the Abstract Factory Pattern is a method in software design that allows you to wrap a set of factories with a shared theme.

Put simply, the Abstract Factory serves as a high-level factory that generates other factories. It's often referred to as the "Factory of Factories." This design pattern, the Abstract Factory, offers a way to create groups of related products without specifying the actual objects to be created.

Sunday, October 22, 2023

Factory Method Design Pattern in C#

The Factory Method Design Pattern belongs to the Creational Design Pattern Category.As part of this article, we will discuss this design pattern in detail with example

What is Factory Method Design Pattern

As per Gang of Four, the Factory Method Design Pattern states that Defines an interface for creating an object but lets the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

In simple words, The Factory Method Design Pattern is used when we create the object without exposing the object creation logic to the client. In the factory method design pattern, we will create an abstract class as the Factory class, which will create and return the product instance, but it will let the subclasses decide which class to instantiate.

The Key Components:

  1. Factory Interface/Abstract Class:This serves as a blueprint for an interface or an abstract class that contains a method for creating objects. Typically, this method is named something like 'createProduct()' or 'factoryMethod()'.
  2. Concrete Factories:These are tangible classes that implement the factory interface. They provide specific implementations of the 'createProduct()' method. Each concrete factory is responsible for producing a particular type of product.
  3. Product Interface/Abstract Class:This defines an interface or an abstract class for the products generated by the factories. Product classes usually share common attributes or methods.
  4. Concrete Products:These are the real-deal classes that implement the product interface. Each concrete product embodies a specific type of object.

Sunday, October 1, 2023

Factory Design Pattern in C#

The Factory Design Pattern is one of the most frequently used design patterns in real-time applications. The Factory Design Pattern in C# falls under the Creational Design Patterns Category.

What is Factory Design Pattern in C#?

Let us first try to understand the definitions of the factory design pattern.

According to Gang of Four (GoF), the Factory Design Pattern states that A factory is an object used for creating other objects. In technical terms, we can say that a factory is a class with a method. That method will create and return different objects based on the received input parameter.

In simple words, when we have a main class(super class) and several different types of classes(subclasses) that are related to it, and we want to make an object from one of these related classes based on some information, we use something called the Factory Design Pattern in C#.

The Key Components:

  1. Product Interface/Abstract Class:This defines an interface or an abstract class for the products generated by the factories. Product classes usually share common attributes or methods.
  2. Concrete Products:These are the real-deal classes that implement the product interface. Each concrete product embodies a specific type of object.
  3. Factory Class:This class contains a method for creating objects.Typically, this method is named something like 'createProduct()' or 'factoryMethod()'.

Sunday, September 10, 2023

Thread-Safe Singleton Design Pattern in C#

In this post, we are going to discuss How to Implement Thread-Safe Singleton Design Pattern in C# with Examples. Please read our previous article where we discussed Singleton Design Pattern. In that post, the way we have implemented the Singleton Design Pattern is not Thread Safe in a Multithread Environment.

Understand Thread-Safe in Singleton Design Pattern in C#.

Before deep dive in to Thread-Safe Singleton Pattern, let us first see the problem that we face in a multithread environment if the Singleton Class is not Thread-Safe. Below is the Singleton Class which we have created in our last post.

    /// <summary>
    /// Sealed class to ensure that it cannot be inherited
    /// </summary>
    public sealed class Singleton
    {
        /// <summary>
        /// To store the Singleton Instance
        /// </summary>
        private static Singleton instance = null;

        /// <summary>
        /// Counter value will be increment by 1 each time the object of the class is created
        /// </summary>
        private static int counter = 0;

        /// <summary>
        /// Private constructor to restrict the class to be instantiated from outside the class
        /// </summary>
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }

        /// <summary>
        /// Static Method to return the Singleton Instance
        /// </summary>
        public static Singleton Instance()
        {
            if (instance == null) { instance = new Singleton(); }
            return instance;
        }

        /// <summary>
        /// Method to accessed from outside of the class by using the Singleton Instance
        /// </summary>
        /// <param name="message"></param>
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }
    }

Let’s modify the Program.cs as follows to use multithread programming. As you can see in the below code, we are using Parallel.Invoke method and call PrintCoachDetails() and PrintPlayerDetails() methods parallelly.

Parallel.Invoke(() => PrintCoachDetails(),
                () => PrintPlayerDetails());

Console.ReadLine();

static void PrintCoachDetails()
{
    //Thread-1 Calling the GetInstance() Method of the Singleton class
    Singleton fromCoach = Singleton.Instance();
    fromCoach.PrintDetails("From Coach");
}
static void PrintPlayerDetails()
{
    //At the same time, Thread-2 also Calling the GetInstance() Method of the Singleton Class
    Singleton fromPlayer = Singleton.Instance();
    fromPlayer.PrintDetails("From Player");
}

So in above example, we are using the Parallel.Invoke method to access the Instance() Method parallelly. That means at the same time multiple threads are accessing the Instance() Method. The above code is not Thread-Safe because the way we have written the code here two different threads can evaluate the condition if (instance == null) at the same time and both threads found it to be true and they both will create the instances, which violates the singleton design pattern. So, now run the application and it will give you the following output.

singleton design pattern

The above output clearly shows that the counter value has incremented to 2, which proves that the constructor of the Singleton class is executed two times as a result two instances of the singleton class have been created. So, if the Singleton class is not Thread-Safe, then we may end up creating multiple instances of the Singleton class in a Multithread Environment.

Thursday, August 31, 2023

Singleton Design Pattern in C#

The Singleton design pattern stands as one of the most commonly used creation patterns in software development. It guarantees that a class exists in only one instance and grants a universal way to reach that instance. This proves especially handy when aiming to establish a singular hub of control or coordination within your application. Let's explore the Singleton pattern through a practical C# example.

What is Singleton Pattern?

We need to use the Singleton Design Pattern in C# when we need to ensure that only one instance of a particular class is going to be created and then provide simple global access to that instance for the entire application. This pattern becomes invaluable when handling resources like database connections, thread pools, configuration settings, and more—minus the complication of creating numerous instances.

Implementation Guidelines of Singleton Design Pattern

Following are the guidelines to implement the Singleton Design Pattern

  1. Declare a constructor that should be private and parameterless. This is required to restrict the class to be instantiated from outside the class.
  2. The class should be declared as sealed which will ensure that it cannot be inherited.
  3. We need to create a private static variable that is going to hold a reference to the singleton instance of the class.
  4. We also need to create a public static property/method which will return the singleton instance of the class.

Implement the Singleton Pattern in C#

There are many ways, we can implement the Singleton Design Pattern in C#. They are as follows.

  1. No Thread-Safe Singleton Design Pattern
  2. Thread-Safety Singleton Implementation using Lock.
  3. Implementing Thread-Safety Singleton Design Pattern using Double-Check Locking.
  4. Using Eager Loading to Implement Thread-Safety Singleton Design Pattern.
  5. Using Lazy<T> Generic Class to Implement Lazy Loading in Singleton Design Pattern.

Wednesday, August 23, 2023

Design Patterns: Building Robust and Flexible Software

What Are Design Patterns?

At their core, design patterns are proven solutions to recurring design problems. They offer developers a common vocabulary and a set of guidelines to approach and tackle issues that frequently arise during software development. These patterns are not specific to a particular programming language or framework; rather, they provide general templates that can be adapted to different contexts.

Why Do Design Patterns Matter?

1.Code Reusability: Design patterns encapsulate solutions to common problems. By using these patterns, developers can reuse tried-and-tested solutions, saving time and reducing the likelihood of bugs.

2.Scalability and Maintainability: Implementing design patterns leads to cleaner, more organized code that is easier to understand and maintain. This is crucial as projects grow in complexity.

3.Communication: Design patterns offer a common language for developers to discuss and document solutions. This leads to better collaboration within teams and across different projects.

4.Flexibility: Design patterns promote loosely coupled components, allowing you to swap out parts of your system without causing cascading changes.

Thursday, August 17, 2023

Angular - Understanding ReplaySubject in Angular

ReplaySubject in angulars

In this article, we'll delve into the core concepts of ReplaySubject and how it can enhance your Angular applications by granting access to historical data. Regardless of your expertise level, this guide will help you effectively harness the capabilities of ReplaySubject.

Understanding ReplaySubject

At its core, a ReplaySubject is a specialized type of Subject in the RxJS library. Like all Subjects, it serves as both an Observable and an Observer. What sets ReplaySubject apart is its unique ability to buffer a specific number of values and replay them to future subscribers. Think of it as a time-travel device that captures past emissions and shares them with new subscribers.

Key Features and Benefits

1.Time-Travel for Subscribers: Imagine welcoming latecomers to a party who wish to experience the excitement from the beginning. ReplaySubject allows subscribers to access historical data, even if they arrive after the data was emitted.
2.Customizable Buffer Size: ReplaySubject empowers you to determine how many values to store in its buffer. By setting the buffer size during creation, you have control over the amount of historical data you retain.
3.No Initial Value Required: Unlike BehaviorSubject, which mandates an initial value, ReplaySubject doesn't demand this, making it perfect for scenarios where an initial value isn't available.
4.Efficient Caching Mechanism: ReplaySubject can act as an intelligent caching mechanism, ensuring that expensive data requests are made only once. Subsequent subscribers receive cached data instead of triggering new requests.

Sunday, August 13, 2023

Understanding Data Sharing Between Angular Components using BehaviorSubject

BehaviorSubject in angulars

In the realm of complex Angular applications, one of the prevalent challenges that developers encounter is the efficient sharing of data among distinct components. Angular offers a potent tool to address this predicament: the 'BehaviorSubject'. This article delves into the practical utilization of 'BehaviorSubject' to facilitate data sharing across components within an Angular application.

What is BehaviorSubject?

In straightforward terms, a 'BehaviorSubject' is a variant of RxJS subject that retains a current value and transmits it to newly subscribing entities. It resembles a conventional 'Subject', but with a pivotal distinction – it constantly holds a value, even when no subscribers are present. When fresh components subscribe to the 'BehaviorSubject', they promptly receive the prevailing value. This characteristic renders it an optimal solution for data sharing that necessitates accessibility and updates across diverse parts of an application.

Establishing the BehaviorSubject

The initial step involves creating an Angular service called 'SharedDataService' to accommodate the shared data and the 'BehaviorSubject'.

// shared-data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SharedDataService {
  private dataSubject: BehaviorSubject<string> = new BehaviorSubject<string>('Initial Value');

  public data$ = this.dataSubject.asObservable();

  public updateData(newValue: string): void {
    this.dataSubject.next(newValue);
  }
}

Thursday, August 10, 2023

Angular : Understanding Subject in Angular for Managing Data Streams

subject in angulars

Subject is a powerful class in Angular, part of RxJS, used to manage asynchronous data streams. It enables you to create an observable and observer simultaneously, simplifying data flow management in your application. Here's a step-by-step guide on how to use Subject in Angular:

Step 1: Import the necessary modules Ensure you import the required modules in the component or service where you intend to use Subject.
import { Subject } from 'rxjs';
Step 2: Create a Subject instance In your component or service, create a Subject instance by declaring a variable and assigning it a new Subject.
private dataSubject: Subject<any> = new Subject<any>();

Friday, August 4, 2023

Understanding Caching in .NET Core API: Improving Performance and Scalability

Caching in .NET Core API

Caching is a crucial aspect of optimizing web application performance and scalability. When building efficient APIs with .NET Core, understanding caching techniques is essential. This post aims to demystify caching in .NET Core API, exploring its benefits, and offering insights into leveraging caching to enhance overall application performance.

The Importance of Caching:

Caching involves storing frequently accessed data in memory, reducing the need to repeatedly fetch it from the original data source. By employing caching, we can significantly improve response times, reduce database load, and enhance API scalability. Caching is especially beneficial for data that doesn't change often, such as reference data, configuration settings, or computed results.

Caching Strategies in .NET Core:

.NET Core provides several caching mechanisms suited to different application requirements:

1. In-Memory Caching: In-memory caching is the simplest form, where data is stored in the application's memory. This approach is ideal for scenarios that demand fast, short-term caching. Using the `IMemoryCache` interface in .NET Core, we can conveniently store and retrieve cached data within the application, complete with expiration policies and basic cache management capabilities.

2. Distributed Caching: For scenarios involving multiple API instances across different servers or sharing cache across various applications, distributed caching is crucial. .NET Core's `IDistributedCache` interface abstracts various distributed caching implementations like Redis, SQL Server, or Azure Cache for Redis. Leveraging distributed caching enables us to share cache across instances and ensure data consistency.

Wednesday, August 2, 2023

Angular : Transforming Data Using Custom Pipe

custom angular pipes

In Angular, pipes are essential for transforming data in templates. Custom pipes enable you to create personalized logic for data transformation. Let's go through an example of how to create a custom Angular pipe that converts a string to uppercase and adds an exclamation mark at the end.

Step 1: Create a new TypeScript file for the custom pipe:
//'uppercase-exclamation.pipe.ts'
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'uppercaseExclamation' })
export class UppercaseExclamationPipe implements PipeTransform {
  transform(value: string): string {
    if (!value) {
      return value;
    }
    return value.toUpperCase() + '!';
  }
}

Monday, July 31, 2023

Introduction to Angular Pipes: Simplifying Data Transformation

Angular pipes

Angular is a robust front-end framework that empowers developers to create dynamic and interactive web applications. Among its key features lies the concept of 'pipes'. You might be curious about what these 'pipes' are and why they hold significance.

In simple terms, Angular pipes are efficient tools that enable you to modify and format data directly within your HTML templates. They take input data, process it, and then display the transformed data. Think of pipes as filters for your data, making it more presentable and user-friendly.

How Pipes Work: Turning Raw Data into Refined Information

Imagine you have raw data that you want to display on your web page, such as a date, a number, or some text. Often, the raw data isn't in the ideal format for presentation, so you need to process it before showing it to the user. This is where pipes come to the rescue.

Using a pipe is straightforward - you add it to an expression in your HTML template, and Angular handles the rest. The basic syntax for using a pipe looks like this:

{{ data | pipeName }}

Here, 'data' represents the input value you want to transform, and 'pipeName' is the specific pipe you want to apply. Angular offers built-in pipes, like 'DatePipe', 'UpperCasePipe', 'LowerCasePipe', and 'CurrencyPipe', which you can use right away. Additionally, you can create custom pipes for more specialized transformations.

Friday, July 28, 2023

Angular TypedForm: Building Strongly Typed Forms in Angular

Angular typed form

Angular is a powerful framework used for developing modern web applications, where forms play a critical role in data processing and user interactions. To ensure a smooth user experience and maintain data integrity, effective handling of form data is essential. Angular provides various mechanisms for form management, and one of the most robust approaches is utilizing Angular TypedForm.

What is Angular TypedForm?

Angular TypedForm is a library specifically designed for Angular that enhances the standard Angular Reactive Forms with strong typing capabilities. This means that you can define your form models using TypeScript interfaces or classes, resulting in more robust and maintainable forms with fewer errors.

Benefits of Angular TypedForm:
1.Type Safety: TypedForm allows you to define the structure of your form data using TypeScript interfaces or classes. By doing so, the form data will adhere to the specified types, preventing runtime errors caused by incorrect data.
2.Code Completion and IntelliSense: Utilizing TypeScript provides the advantage of code autocompletion and IntelliSense in modern code editors. This feature streamlines form development by providing suggestions for available properties and methods of the form model directly from the editor.
3.Refactoring Support: Defining the form model as a TypeScript interface or class makes refactoring more manageable. Any changes, such as renaming or modifying a property in the form model, will be automatically reflected throughout your codebase.

Wednesday, July 26, 2023

Angular - How to create custom structural directive?

Angular custom structural directive

Creating a custom structural directive in Angular allows you to modify the DOM based on certain conditions, extending the template syntax. Structural directives are identified by the asterisk (*) preceding the directive name in the HTML template. Let's go through the steps to create your own custom structural directive in Angular.

Step 1: Set up the Angular project: Ensure that you have Angular CLI installed. If not, you can install it using npm:
npm install -g @angular/cli
Create a new Angular project:
ng new custom-structural-directive-demo
cd custom-structural-directive-demo
Step 2: Generate the directive: Next, generate a new directive using Angular CLI:
ng generate directive customIf

This generates a new directive file named 'custom-if.directive.ts' in the 'src/app' folder.

Monday, July 24, 2023

Angular - An Introduction to Structural Directives in Angular

Angular structural directive

In post Directive in Angular, we tried to understand what is directive? In this post, we'll explore Structural Directives and understand how they enhance the functionality and flexibility of Angular applications.

What are Structural Directives?

Structural Directives in Angular are a type of directive that modify the layout and structure of the DOM by adding or removing elements based on conditions. Unlike Attribute Directives, which change an element's behavior or appearance, Structural Directives directly impact the DOM's structure. The most commonly used Structural Directives in Angular are 'ngIf', 'ngFor', and 'ngSwitch'.

1. ngIf: The 'ngIf' directive conditionally adds or removes an element from the DOM based on the evaluation of an expression. It proves particularly useful when you need to show or hide specific parts of your template depending on your application's state. Example:
<ng-container *ngIf="isLoggedIn">
  <p>Welcome, {{ username }}!</p>
</ng-container>
In this example, the '<p>' element will only be rendered if the 'isLoggedIn' variable is true.

Friday, July 21, 2023

Angular - Understanding ng-template and ng-content in Angular

Angular ng-template and ng-content

In Angular, the features 'ng-template' and 'ng-content' are valuable tools that facilitate the creation of dynamic and reusable components. They significantly contribute to improving code modularity, reusability, and maintainability. Let's explore each of these features to comprehend their importance in Angular development.

1. ng-template:

In Angular, 'ng-template' is a directive that allows the definition of a template block within a component without immediate rendering. It serves as a placeholder for content that can be instantiated later, based on different conditions. Think of it as a blueprint for creating content that will only be activated when explicitly used.

Usage:
<ng-template #myTemplate>
  
</ng-template>
How to use ng-template:

The true power of 'ng-template' comes into play when used in conjunction with other Angular directives such as 'ngIf', 'ngFor', and custom structural directives. For example, with 'ngIf', you can conditionally render content based on specific logic:

Thursday, July 20, 2023

Angular - Understanding Directives in Angular

Angular directives

Angular is a widely used front-end framework known for its ability to create dynamic web applications. One of its essential features is directives, enabling developers to extend HTML and build reusable components with customized behavior and functionality. In this post, we'll deep dive into what directives are, the various types available in Angular, and how to utilize them efficiently in your projects.

What are Directives?

In Angular, directives serve as markers on DOM elements, instructing Angular's compiler to attach specific behavior or functionality to those elements. They are instrumental in manipulating the DOM, adding or modifying elements, applying styles, handling events, and more. By using directives, you can extend HTML with your own custom attributes or tags, making your code more expressive and easier to maintain.

Types of Directives in Angular

Angular provides three primary types of directives:

  1. Component Directives: Components are the most commonly used type of directive. They are essentially directives that come with an associated template. Components encapsulate the template, styles, and behavior of a specific part of the user interface, acting as reusable building blocks throughout your application.
  2. Attribute Directives: Attribute directives modify the behavior or appearance of existing elements or components. They are used as attributes on elements and are denoted by square brackets, such as '[ngStyle]' or '[ngClass]'. Attribute directives are useful for applying conditional styles, enabling/disabling elements, or performing other transformations on elements.
  3. Structural Directives: Structural directives modify the DOM's structure by adding or removing elements. They are also used as attributes but are denoted by an asterisk ('*') before the directive name. Some examples include '*ngIf', '*ngFor', and '*ngSwitch'. These directives are commonly employed for rendering lists, conditionally displaying content, and handling template rendering.

Tuesday, July 18, 2023

Angular - Utilizing the @ViewChild Decorator in Angular for Enhanced Component Interaction

Angular viewchild decorator

Angular, a robust web application framework, offers developers a vast array of tools and features to boost productivity. One such feature is the @ViewChild decorator, which facilitates the access of child components, directives, or DOM elements within Angular components. In this article, we will explore the capabilities of @ViewChild and delve into its practical applications for interacting with child elements and components in your Angular applications.

Understanding @ViewChild:

The @ViewChild decorator enables developers to obtain references to child components, directives, or DOM elements residing within the template of a parent component. It grants access to properties and methods of the child component, facilitates interaction with the child directive, and allows direct manipulation of the DOM element.

Syntax: The syntax for implementing the @ViewChild decorator is as follows:
@ViewChild(selector, options) propertyName: Type;
  1. The selector represents the CSS selector or component class used to identify the child element/component.
  2. The options parameter is optional and allows for the specification of additional view query options.

Example 1: Accessing a Child Component

Let's consider a scenario where we have a parent component, ParentComponent, that includes a child component named ChildComponent. To access the child component from the parent component, we can utilize the @ViewChild decorator as illustrated below:

Sunday, July 16, 2023

Angular - Understanding @Input and @Output Decorators

Angular Input and Output

Angular is a widely-used framework for creating web applications, offering powerful features for component-based development. Two important decorators in Angular are '@Input' and '@Output'. These decorators facilitate communication between components. In this post, we'll explore these decorators and learn how to utilize them effectively.

@Input Decorator

The '@Input' decorator is employed to define an input property on a component, enabling the flow of data from a parent component to a child component. By utilizing '@Input', you can bind values to properties within a child component, allowing for dynamic data exchange.

To define an input property, simply add the '@Input()' decorator above the property declaration within the child component. Here's an example:

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

@Component({
  selector: 'child-component',
  template: `Child Component: {{ childProperty }}`
})
export class ChildComponent {
  @Input() childProperty: string;
}

Monday, July 3, 2023

Understanding Attributes and Properties in HTML

html attributes and properties

When working with HTML, it's crucial to understand the concepts of attributes and properties.The terms "attribute" and "property" can be confusing in HTML. In the Angular framework, there are concepts called Property Binding and Attribute Binding, and understanding the difference between the two is important.

The main difference between attributes and properties is as follows: attributes are related to HTML, while properties are related to the DOM (Document Object Model). In HTML, we only have attributes, not properties. Similarly, in the DOM, we only have properties, not attributes.

Attributes in HTML:

Attributes are characteristics or metadata that we assign to HTML elements. They provide additional information about an element, defining its behavior, appearance, or specific details. Attributes are placed within the opening tag of an element and are written as name-value pairs. The attribute name represents its purpose, while the value specifies the particular setting.

Example of an attribute:
<a href="https://www.example.com">Click here</a>

In the above example, the "href" attribute is used to define the destination of the hyperlink. The attribute value is set to "https://www.example.com" indicating the URL the link should navigate to.

Properties in HTML:

Properties, on the other hand, are characteristics of HTML elements that can be accessed and manipulated using JavaScript. Unlike attributes, properties are part of the Document Object Model (DOM), which represents the web page as a structured tree of objects. Properties enable developers to dynamically modify element behavior and content through scripting.

Thursday, June 29, 2023

Angular - Understanding the Attribute Binding

Angular attribute binding

Angular, a robust JavaScript framework, empowers developers to build dynamic and interactive web applications. Among its key features, attribute binding stands out, enabling the manipulation of HTML attributes within Angular components. In this blog post, we'll dive into AnAngulargular attribute binding, exploring its usage, syntax, and practical applications.

Understanding Attribute Binding:

Attribute binding in Angular provides a means to dynamically set or update attribute values of HTML elements. It allows for the binding of component properties to HTML attributes, enhancing application flexibility and responsiveness. Attribute binding works with any HTML attribute, including standard ones like 'src', 'href', and 'disabled', as well as custom attributes.

Syntax and Usage:

Attribute binding syntax resembles property binding, but instead of an element property between brackets, you precede the name of the attribute with the prefix attr, followed by a dot.

Tuesday, June 27, 2023

Angular - Simplifying Data Flow in Angular Applications with Property Binding

Angular property binding

Property binding in Angular application allows developers to establish a connection between the properties of HTML elements and the data in a component, enabling smooth data flow and dynamic updates within an Angular application. In this blog post, we will explore the concept of Angular property binding, its syntax, and how it can enhance your development workflow.

Understanding Property Binding:

Property binding in Angular enables you to bind data from a component to properties of HTML elements, such as attributes, properties, and events. It offers a convenient way to update these properties dynamically based on changes in the component's data.

With property binding, you can create interactive and responsive applications by passing data between components and templates. This bidirectional flow allows you to manipulate data in the component and instantly reflect the changes in the template.

Syntax and Usage:

To use property binding in Angular, you enclose the desired property within square brackets ('[]') on the HTML element. The expression within the brackets is evaluated and assigned to the specified property. Let's look at a simple example:

<input [value]="name">

In the above example, we bind the 'value' property of the 'input' element to a property named 'name' in the component. Whenever the 'name' property in the component changes, the corresponding value in the input field is automatically updated.

You can also bind to other properties like 'src', 'href', 'disabled', and more. Property binding is not limited to HTML attributes alone; you can also bind to properties of custom Angular directives and components.

Sunday, June 25, 2023

.NET Core - Understanding Scoped, Transient, and Singleton Lifetime

Scoped, Transient, and Singleton Lifetime

Scoped, Transient, and Singleton are three lifetime options available in .NET Core for registering and managing services within the dependency injection container. Understanding these options is crucial for building scalable and maintainable applications. Let's explore each of them:

  1. Transient Lifetime:

    A transient service is created each time it is requested from the dependency injection container. This means a new instance is created for every resolution. Transient services are suitable for lightweight and stateless components that don't require shared state. For instance, if you have a service that performs simple calculations or generates random numbers, using the transient lifetime is appropriate.

    To register a transient service in .NET Core, you can use the 'AddTransient' method during service registration:

    services.AddTransient<ITransientService, TransientService>();

Friday, June 23, 2023

Understanding the Use, Run, and Map Functions for Middleware in .NET Core

use,run and map in .net core

Introduction:

Middleware plays a vital role in handling and processing HTTP requests within a .NET Core application's request pipeline. It enables developers to customize and extend the application's behavior. In this post, we will delve into three crucial functions used for configuring middleware: Use, Run, and Map.



  1. Use:

    The Use function is extensively used when configuring middleware in .NET Core. It allows the addition of middleware components to the request pipeline. This function accepts a delegate or a middleware class as a parameter. The delegate or middleware class is responsible for processing an HTTP request and generating an appropriate response.

    Consider the following example that demonstrates the Use function in adding custom middleware:

    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            // Perform some logic before the request reaches the next middleware
            await next.Invoke();
            // Perform some logic after the request has been processed by subsequent middleware
        });
        // Add more middleware components using the Use function if necessary
    }
    

Wednesday, June 21, 2023

Middleware in .NET Core: A Developer's Guide

middleware .net core

Introduction:

Middleware plays a vital role in web development, and having a clear understanding of its concept and implementation is crucial for .NET Core developers. Middleware acts as a bridge between incoming requests and outgoing responses in an application, enabling developers to customize and extend the request-processing pipeline. In this article, we will explore the world of middleware in .NET Core, discussing its significance, usage, and providing practical examples.


Understanding Middleware:

In the context of .NET Core, middleware refers to a software component or a set of components that are executed sequentially to process HTTP requests and responses. It forms a chain of components that intercept requests, perform specific actions, and pass control to the next component in the pipeline. Middleware empowers developers to add, remove, or modify behavior at various stages of request processing without altering the core application code.

Middleware in .NET Core:

In .NET Core, the request pipeline is constructed using middleware components. It comprises a series of middleware components that receive an incoming HTTP request and pass it along until a response is generated. Each middleware component can inspect, modify, or terminate the request pipeline.

Middleware components in .NET Core are represented by classes that implement either the IMiddleware interface or the RequestDelegate delegate. The IMiddleware interface provides a convenient way to encapsulate middleware logic, while the RequestDelegate delegate offers finer control over middleware behavior.

Saturday, June 10, 2023

Angular CLI and Essential Commands for Efficient Development

Angular CLI and Essential Commands

Angular CLI (Command Line Interface) is a powerful tool that aids in the streamlining of Angular development by automating various tasks and providing a standardized project structure. In this post, we will explore the Angular CLI and highlight some of the most useful commands that can enhance your productivity as an Angular developer.

  1. Installation: To begin using Angular CLI, ensure that you have Node.js installed on your system. Once Node.js is installed, open your terminal or command prompt and execute the following command to install Angular CLI globally:
    npm install -g @angular/cli
    
    This command installs the CLI tool globally, making it accessible as a command-line tool.
  2. Creating a New Angular Project: Angular CLI simplifies project creation through a straightforward command. To create a new Angular project, navigate to your desired directory in the terminal and execute the following command:
    ng new my-angular-app
    
    This command generates a new Angular project named "my-angular-app" and sets up the necessary files and dependencies.

Monday, June 5, 2023

Angular Trackby to improve ngFor Performance

Angular Trackby to improve ngFor Performance

Do you utilize ngFor in Angular to iterate over arrays or collections? If that's the case, you might have come across performance issues or unexpected behavior when updating or deleting items. But fret not! Angular offers a practical solution known as trackBy that can greatly enhance the performance and stability of your ngFor loops. Let's delve into it and learn how to effectively use it.


The Challenge

By default, Angular employs the index of each item in an array to track changes in ngFor loops. This implies that if the array's order changes or items are added or removed, Angular will re-render the entire list. Such a scenario can lead to performance bottlenecks, particularly when dealing with large arrays or complex components within the loop.

The following example shows what happens when we refresh the entire list. The App displays the list of names. it has option to add a name, remove a name and refresh the entire name list.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  names = new Array<string>();

  name: string = '';

  ngOnInit() {
    this.Refresh();
  }

  remove(i: number) {
    this.names.splice(i, 1);
  }

  addMovie() {
    this.names.push(this.name);
    this.name = '';
  }

  Refresh() {
    console.log('refresh');
    this.names = ['Manish', 'Rahul', 'Ashish', 'Aditya', 'Rohan'];
  }
}

HTML

<p>App Component</p>
<ul>
    <li *ngFor="let name of names; index as i">
        {{i}}. {{name}} <button (click)="remove(i)">remove</button>
    </li>
</ul>

<button (click)="Refresh()">Refresh>/<button> <br/>

Name : <input type="text" [(ngModel)]="name">
<button (click)="addMovie()">Add Name</button>

Sunday, June 4, 2023

Angular - @HostBinding and @HostListener

Today, let's explore two powerful decorators in Angular: @HostBinding and @HostListener.The HostBinding and HostListener are decorators in Angular. HostListener listens to host events, while HostBinding allows us to bind to a property of the host element.

These decorators allow us to enhance the behavior of a component by interacting with its host element. Let's understand how they work and how we can effectively use them.

HostElement

The host element is the element on which we attach our directive or component. Remember components are directives with a view (template).

@HostBinding

The @HostBinding decorator enables us to bind a class property to a property of the host element. This way, we can dynamically modify the properties of the host element based on changes in our component's logic.

By utilizing this decorator, we can seamlessly update attributes, classes, or styles of the host element. Let's take a look at an example to illustrate the usage of @HostBinding:

import { Directive, HostBinding, OnInit } from '@angular/core';
@Directive({ selector: '[hostBindingExample]' })
export class HostBindingExampleDirective implements OnInit {
  @HostBinding('style.border') border: string = '';

  ngOnInit() {
    this.border = '5px solid green';
  }
}

In the above code snippet, hostBindingExample directive, uses the HostBinding on style.border property of the parent element to the border property.Whenever we change the value of the border, the angular will update the border property of the host element.

Sunday, May 28, 2023

Angular- Directive to Allow Number Only in Input Textbox

Directive to Allow Number Only in Input Textbox

In this post, we will create a directive which will allow only numbers to input textbox. User will not allow to enter any other value, only numbers.

Below is the code of directive which will check the input value and allow if the input value is number-

import { Directive, HostListener } from '@angular/core';

@Directive({ selector: '[allowNumberOnly]' })
export class AllowNumberOnly {
  readonly NUMBER_REGEX = '^[0-9]';
  @HostListener('keypress', ['$event'])
  onKeyPress(event: any): boolean {
    if (!new RegExp(this.NUMBER_REGEX).test(event.key)) {
      return false;
    }
    return true;
  }
}

To use the directive in application, we need to add the directive under declarations array of App Module file.

Monday, May 15, 2023

Basics of Web API- HTTP

Hyer-Text Transfer Protocol(HTTP)

  • HTTP(Hyer-Text Transfer Protocol) is a communication protocol on the web that is used to transmit data.
  • Extensible using Headers to send/receive extra information
  • Stateless, doesn’t maintain state unless using HTTP cookies to maintain the communication session or state.

HTTPS

S stands for secure, which means communication between client and server will happen via a secure channel using SSL\TLS encryption protocol.

TLS is the successor of SSL. TLS v1.3 is the latest version. The minimum recommended version of TLS is TLS v1.2, which the website should use to maintain a secure website.

HTTP Request Methods

  1. GET-Used to retrieve data. We can pass the parameter via query string to retrieve data based on the parameter.
  2. POST-Used to submit data within request body. This is usually used to pass personal or confidential data.
  3. PUT-Used to edit record to resource server without creating new record.
  4. DELETE-Used to delete a record in resource server.

Other methods are PATCH, OPTIONS, HEAD, TUNNEL, TRACE.

Content Types

  1. Plain-Data will be sent ‘as-is’ in plain text without any encryption, serialization or encoding.
  2. json-Data will be serialize in JSON format when sent from POST or PUT request body.
  3. form-url-encoded-This is represented as key-value pair of request parameter that are sent as request body.
  4. form-data-Used when uploading form fields that includes file upload. It uploads data in multiple parts. Use it when sending binary or large payload.

Tuesday, May 9, 2023

Angular - Bind Route Info to Component Inputs (Angular16)

In building Angular application,most of the time we use the Router to render different pages for different urls, and based on the url we also load the data based on its path parameters or query parameters.

In the latest version of Angular v16, we will get a new feature that will simplify the process of retrieving route information in the component and make it way easier.Now we can bind route parameters to the corresponding component’s inputs

You can pass the following data to a routing component’s inputs-

  1. Route data — resolvers and data properties
  2. Path parameters
  3. Query parameters

We will be able to pass the route information to the component inputs, so we don’t need to inject the ActivatedRoute service anymore.

Below are some examples-

Route data — resolvers and data properties

// Routes
const routes: Routes = [
  {
    path: 'about',
    component: MyComponentComponent,
    resolve: { elementId: () => 'elementId1' },
  },
];
// Component Code
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})
export class MyComponentComponent implements OnInit {
  @Input() elementId: string = ''; //this will come from the resolved data
  ngOnInit(): void {
    console.log(this.elementId); // get elementId here
  }
}

Sunday, May 7, 2023

Angular- Required Component Inputs in Angular16

Angular16 has introduced a new feature to define the inputs as required for component and directives. We can now specify that a component or directive requires certain inputs to function properly.

By using this new feature, we can insure that all necessary data is present before the component or directive logic/functionality executed, resulting better code quality, fewer errors. To use it we can set the new required option in our input:

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

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})
export class MyComponentComponent {
  @Input({ required: true }) elementId: string;
}

There will be a compilation error if the consumer doesn’t initialize this input:

Saturday, May 6, 2023

Default values for lambda expressions - C#12

In C#12, you can now define default values for parameters on lambda expressions. The syntax and rules are the same as adding default values for arguments to any method or local function.For example:

var addWithDefault = (int addTo = 2) => addTo + 1;
addWithDefault(); // 3
addWithDefault(5); // 6

Prior to C# 12 you needed to use a local function or the unwieldy DefaultParameterValue from the System.Runtime.InteropServices namespace to provide a default value for lambda expression parameters.

Using directives for additional types - C#12

C# 12 extends using directive support to any type.Now you can use the using alias directive to alias any type, not just named types. That means you can create semantic aliases for tuple types, array types, pointer types, or other unsafe types. Below are few examples :

using Measurement = (string, int);
using PathOfPoints = int[];
using DatabaseInt = int?;

You can now alias almost any type. You can alias nullable value types, although you cannot alias nullable reference types.

Friday, May 5, 2023

Primary Constructor - C# 12

Primary constructor allows you to add parameters to calss declaration itself and use these values in class body. Promary constructor was introduced for records in C#9. C#12 extends it to all classes and structs.

c sharp primary constructor
^ Scroll to Top