Tag - Architecture

Web Components: The Future of Modular UI Design
Jul 26, 2024

Have you ever wanted to create reusable JavaScript building blocks that work in any project, no matter what framework others are using? If so, then Web Components might be the solution you're looking for! This Guide is intended to dive into custom components. Web Components are a collection of tools that expand the web platform. This allows you to define new HTML elements with specific functionality and behavior. There’s a lot to think about, and writing a component can require a lot of boilerplate code. Fortunately, some great libraries can make creating custom elements more straightforward, and save you a lot of time and effort. However, if you’re writing lots and lots of custom elements, using a library can make your code simpler and cleaner, and your workflow more efficient. What are the Web Components? That allows developers to create custom, reusable, encapsulated HTML elements. Custom Elements: Enables the creation of new HTML tags. Shadow DOM: Provides encapsulation for custom elements, ensuring that their internal structure and styles do not interfere with the rest of the document. HTML Templates: Allows the definition of HTML templates that can be reused and instantiated in custom elements. Note: The name of a Web Component needs to contain a dash (-). This naming convention is put into place to enable the HTML parser to distinguish custom from regular elements and also avoid creating your own components that could be added as part of future HTML standards. <mycard></mycard>, <card></card> or <CardComponent></CardComponent> are all invalid names, while <my-card></my-card> is allowed.   Why Web Components? Web components allow us to take our frontend widgets off this cycle of getting rebuilt in the newest framework flavor Reuse is King: Ever build the same button style ten times? With Web Components, you define a button component once and use it everywhere! Framework Freedom: No more framework lock-in! Web Components work seamlessly with vanilla JavaScript, React, Angular, or any framework you choose. Encapsulation Power: Components keep their styles and functionality isolated, preventing conflicts and promoting cleaner code. To define a new custom element using the v1 implementation, you simply create a new class that extends HTMLElement using ES6 syntax and register it with the browser:   class MyElement extends HTMLElement {...} window.customElements.define('my-element, MyElement); //example usage in your app: <my-element></my-element> NOTE: Only Chrome V67 and up supports customized built-in elements! Let's Jump over the example, Building with LitElement. Certainly! Below is an example of a toggle switch web component using Lit. This example includes the essential parts: defining the component, its styles, and its template. Code Snippets for User Template:   // component's template render() { return html` <label class="switch"> <input type="checkbox" .checked="${this.checked}" @change="${this._toggle}"> <span class="slider"></span> </label> `; } // Method handler. // The toggle handler public _toggle(event): void { this.checked = event.target.checked; this.dispatchEvent(new CustomEvent('toggle', { detail: this.checked })); } Explanation: We import LitElement and the html function for templating. We define a AppToggle class that extends LitElement. We set the name property to accept a string value. The render method defines how the component looks using LitElement's HTML-like syntax. Finally, we register the app-toggle custom element.   Now, you can use your app-toggle component anywhere in your HTML: <div style="display: block; padding:200px"> <app-toggle name="toggle" checked="true"></app-toggle> <app-toggle name="World"></app-toggle> </div> The Future is Modular! Web Components offer a powerful and versatile approach to building user interfaces. With Reusability, framework independence, and clear separation of concerns, they are poised to be a significant force in the future of web development. So, start building your UI block party with Web Components today! I have included a screenshot below from WebComponents.org that shows the current browser support - a really nice community guide worth checking out and adding to your Bookmarks: Conclusion In this article, you took your first step into the world of web components. Web components have no third-party dependencies, so using them won't have a big impact on your bundle size. But for more complex components, you may want to reach for a library like Svelte or Lit.    

Angular App Hosting on IIS: Quick Guide
Jan 23, 2024

Hosting an Angular application on IIS involves a few straightforward steps.    Follow this step-by-step guide to seamlessly deploy your Angular project on IIS. Step 1: Open Your Angular Project in Visual Studio Code Review the build command in the package.json file. By default, it's usually set to ng build. Step 2: Run the Build Command Execute the ng build command in the terminal to compile your Angular application.  This command creates a 'dist' folder, typically located at the specified output path in the angular.json file. Step 3: Install IIS Ensure that IIS is installed on your machine. You can install it through the "Turn Windows features on or off" option in the Control Panel. Step 4: Create a New Site in IIS Open the IIS Manager. In the Connections pane, right-click on the "Sites" node and select "Add Website." Fill in the required information, such as the Site name, Physical path to the folder , and choose a port. Step 5: Configure URL Rewrite (Optional) If your Angular application uses routing, consider configuring URL Rewrite for proper routing.  Create a 'web.config' file in your 'dist' folder with the appropriate configurations. Here's a simple example of a web.config file for an Angular application with routing.This file helps configure how the server handles URL requests. ---------------------------------------------------------------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <configuration>   <system.webServer>     <rewrite>       <rules>         <rule name="Angular Routes" stopProcessing="true">           <match url=".*" />           <conditions logicalGrouping="MatchAll">             <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />             <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />           </conditions>           <action type="Rewrite" url="/" />         </rule>       </rules>     </rewrite>     <staticContent>       <remove fileExtension=".json" />       <mimeMap fileExtension=".json" mimeType="application/json" />     </staticContent>   </system.webServer> </configuration> ---------------------------------------------------------------------------------------------------------------- Step 6: Restart IIS After making these changes, restart IIS to apply the configurations. Step 7: Access Your Angular Application Open a web browser and navigate to http://localhost:yourport (replace 'yourport' with the specified port from Step 4). Now, your Angular application is hosted on IIS. Access it through the specified port. If any issues arise, check the IIS logs for more information.  Customize these instructions based on your specific requirements and environment. Thanks!

Learn the Basics of Kafka Installation
Jan 23, 2024

In the dynamic landscape of data processing, Apache Kafka stands out as a robust and scalable distributed event streaming platform. This blog post aims to demystify Kafka, guiding you through its installation process step by step, and unraveling the concepts of topics, producers, and consumers.  Understanding Kafka:  1. What is Kafka? Apache Kafka is an open-source distributed streaming platform that excels in handling real-time data feeds. Originally developed by LinkedIn, Kafka has evolved into a powerful solution for building scalable and fault-tolerant data pipelines.  Installing Kafka:  2. Step-by-Step Installation Guide: Let's dive into the installation process for Kafka:  Prerequisites: Before installing Kafka, ensure you have Java installed on your machine, as Kafka is built on Java.  Download Kafka: Visit the official Apache Kafka website (https://kafka.apache.org/) and download the latest stable release. Unzip the downloaded file to your preferred installation directory.  Start Zookeeper: Kafka relies on Zookeeper for distributed coordination. Navigate to the Kafka installation directory and start Zookeeper:  bin/zookeeper-server-start.sh config/zookeeper.properties    Start Kafka Broker: Open a new terminal window and start the Kafka broker:  bin/kafka-server-start.sh config/server.properties  Congratulations! You now have Kafka up and running on your machine.  Kafka Concepts:    3. Topics:  Definition: In Kafka, a topic is a category or feed name to which messages are published by producers and from which messages are consumed by consumers.  Creation: Create a topic using the following command:  kafka-topics.bat --create   --topic MyTopics --bootstrap-server localhost:9092 --partitions 3 --replication-factor 1  List out Topics : To see all the topics will use following command :  \bin\windows\kafka-topics.bat --list --bootstrap-server localhost:9092    4. Producers and Consumers:  Producers: Producers are responsible for publishing messages to Kafka topics. You can create a simple producer using the following command:  bin/kafka-console-producer.sh --topic myTopic --bootstrap-server localhost:9092  Consumers: Consumers subscribe to Kafka topics and process the messages. Create a consumer with:  bin/kafka-console-consumer.sh --topic myTopic --bootstrap-server localhost:9092 --from-beginning    Conclusion:  Apache Kafka is a game-changer in the world of real-time data processing. By following this step-by-step guide, you've successfully installed Kafka and gained insights into key concepts like topics, producers, and consumers. Stay tuned for more in-depth Kafka tutorials as you explore the vast possibilities of this powerful streaming platform. 

Quick Tips: Managing Expired Tokens
Jan 01, 2024

Here, I will explain how to restrict users from using expired tokens in a .NET Core application. Token expiration checks are crucial for ensuring the security of your application.   Here's a general outline of how you can achieve this: 1. Configure Token Expiration: When generating a token, such as a JWT, set an expiration time for the token. This is typically done during token creation. For example, when using JWTs, you can specify the expiration claim:   var tokenDescriptor = new SecurityTokenDescriptor {     Expires = DateTime.Now.AddMinutes(30) // Set expiration time }; 2. Token Validation Middleware: Create middleware in your application to validate the token on each request. This middleware should verify the token's expiration time. You can configure this middleware in the startup or program file on the .NET side.   public void Configure(IApplicationBuilder app, IHostingEnvironment env) {     app.UseMiddleware<TokenExpirationMiddleware>(); } 3. Token Expiration Middleware: Develop middleware to validate the token's expiration time. Take note of the following points: ValidateIssuerSigningKey: Set to true, indicating that the system should validate the issuer signing key. IssuerSigningKey: The byte array represents the secret key used for both signing and verifying the JWT token. ValidateIssuer and ValidateAudience: Set to false, indicating that validation of the issuer and audience is skipped. By setting ClockSkew to TimeSpan.Zero, you specify no tolerance for clock differences. If the current time on the server or client is not precisely within the token's validity period, the token is considered expired.      public class TokenExpirationMiddleware     {         private readonly RequestDelegate _next;         public TokenExpirationMiddleware(RequestDelegate next)         {             _next = next;         }         public async Task Invoke(HttpContext context)         {             // Check if the request has a valid token             var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();             if (token != null)             {                 var tokenHandler = new JwtSecurityTokenHandler();                 var key = Encoding.ASCII.GetBytes("YourSecretKey"); // Replace with your actual secret key of Issuer                 var tokenValidationParameters = new TokenValidationParameters                 {                     ValidateIssuerSigningKey = true,                     IssuerSigningKey = new SymmetricSecurityKey(key),                     ValidateIssuer = false,                     ValidateAudience = false,                     ClockSkew = TimeSpan.Zero                 };                 try                 {                     // Validate the token                     var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);                     // Check if the token is expired                     if (securityToken is JwtSecurityToken jwtSecurityToken)                     {                         if (jwtSecurityToken.ValidTo < DateTime.Now)                         {                             // Token is expired                             context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;                             return;                         }                     }                 }                 catch (SecurityTokenException)                 {                     // Token validation failed                     context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;                     return;                 }             }             await _next(context);         }     } Working fine with proper token time. Here is an example: I am providing an expired token, and it will result in a 401 Unauthorized status. You can also check the token in https://jwt.io/ for time expired (exp) . By following these steps, you can effectively implement checks to ensure that users are not able to use expired tokens within your .NET Core application.

Docker for Beginners: A Practical Guide
Dec 05, 2022

What Is a Docker? Let’s Say you created an application, and that’s working fine in your machine.??????? Figure 1: App Working Fine   But in production it doesn’t work properly, developers experience it a lot. Figure 2: Not Working in Production   That is when the developer’s famous words are spoken Client: Your application is not working Developer: It works on my machine Figure 3: Client Developer   The Reason could be due to: Dependencies Libraries and versions Framework OS Level features Microservices That the developer’s machine has but not there in the production environment.   We need a standardized way to package the application with its dependencies and deploy it on any environment. Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Figure 4: Docker Icon   How does docker work? Docker packages an application and all its dependencies in a virtual container that can run on any server. Figure 5: Container   Each container runs as an isolated process in the user space and take up less space than regular VMs due to their layered architecture. Figure 6: Architecture   So, it will always work the same regardless of its environment. Credit Goes to @codechips  

magnusminds website loader