<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rohit Cdy</title>
    <description>The latest articles on DEV Community by Rohit Cdy (@rohitchdy).</description>
    <link>https://dev.to/rohitchdy</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1103099%2F75ba559a-2905-4595-8418-1d0c9e9b2f99.jpeg</url>
      <title>DEV Community: Rohit Cdy</title>
      <link>https://dev.to/rohitchdy</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rohitchdy"/>
    <language>en</language>
    <item>
      <title>Advanced Optimization Techniques for High-Performance Angular Applications.</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Fri, 31 Jan 2025 11:17:49 +0000</pubDate>
      <link>https://dev.to/rohitchdy/advanced-optimization-techniques-for-high-performance-angular-applications-5gna</link>
      <guid>https://dev.to/rohitchdy/advanced-optimization-techniques-for-high-performance-angular-applications-5gna</guid>
      <description>&lt;p&gt;Angular is a powerful framework for building dynamic web applications, but as your app grows, performance issues can arise. Optimizing your Angular application ensures a better user experience, faster load times, and smoother interactions. Here are some essential tips to enhance the performance of your Angular application.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. &lt;strong&gt;Use OnPush Change Detection Strategy&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;By default, Angular has a &lt;code&gt;Default&lt;/code&gt; change detection strategy that checks all components for changes, even when there is no need. Changing it to &lt;code&gt;OnPush&lt;/code&gt; will make Angular check the component only when its input properties change, which can significantly boost performance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Component&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
&lt;span class="na"&gt;selector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;app-example&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="na"&gt;templateUrl&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./example.component.html&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="na"&gt;changeDetection&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ChangeDetectionStrategy&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;OnPush&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ExampleComponent&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Input&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;any&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. &lt;strong&gt;Lazy Load Modules&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Lazy loading loads modules only when they are required, reducing the initial bundle size and improving load times.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;routes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Routes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;feature&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;loadChildren&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./feature/feature.module&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;m&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;m&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;FeatureModule&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. &lt;strong&gt;Use Ahead-of-Time (AOT) Compilation&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;AOT compiles your Angular templates at build time rather than runtime, resulting in faster rendering and smaller bundle sizes. Enable AOT compilation in &lt;code&gt;angular.json&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"angularCompilerOptions"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="nl"&gt;"enableIvy"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. &lt;strong&gt;Minimize Bundle Size&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Analyze and reduce your application's bundle size by using tools like &lt;code&gt;webpack-bundle-analyzer&lt;/code&gt;. Remove unnecessary dependencies and also perform tree shaking to eliminate unused code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-g&lt;/span&gt; webpack-bundle-analyzer
ng build &lt;span class="nt"&gt;--prod&lt;/span&gt; &lt;span class="nt"&gt;--stats-json&lt;/span&gt;
webpack-bundle-analyzer dist/stats.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. &lt;strong&gt;Optimize DOM Manipulation with TrackBy in ngFor&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Using &lt;code&gt;trackBy&lt;/code&gt; improves performance by reducing DOM manipulations when updating lists.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="nf"&gt;trackByFn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;index&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. &lt;strong&gt;Use Server-Side Rendering (SSR) with Angular Universal&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;SSR enhances performance by rendering pages on the server, thus reducing the time it takes for users to load pages.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;ng add @nguniversal/express-engine
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  7. &lt;strong&gt;Minimize HTTP Requests by Implementing Caching&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Caching responses from APIs avoid redundant requests, hence improving application performance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;http&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;url&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;shareReplay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  8. &lt;strong&gt;Optimize Images and Assets&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Compressed images, lazy loading of images, and serving static assets efficiently.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. &lt;strong&gt;Enable Production Mode&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Always ensure your Angular application is running in production mode to enable optimizations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;production&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nf"&gt;enableProdMode&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  10. &lt;strong&gt;Use Web Workers for Heavy Tasks&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Offload expensive computations to web workers to avoid blocking the main thread.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;worker&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;URL&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./app.worker&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;meta&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;url&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;The implementation of these optimization techniques will definitely improve the performance of your Angular application, making it much faster and efficient. Profiling and monitoring regularly will keep your app responsive and scalable.&lt;/p&gt;

&lt;p&gt;This will enable you to deliver the best experience for your users and maintain a performance-optimized Angular application.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Mastering Angular Routing &amp; Guards: Secure and Seamless Navigation!</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Fri, 31 Jan 2025 10:37:22 +0000</pubDate>
      <link>https://dev.to/rohitchdy/mastering-angular-routing-guards-secure-and-seamless-navigation-5dgo</link>
      <guid>https://dev.to/rohitchdy/mastering-angular-routing-guards-secure-and-seamless-navigation-5dgo</guid>
      <description>&lt;p&gt;In an SPA, Angular routing is basically the functionality allowing users to travel between various parts of your app. At that point, the route guards, which will make navigation smarter and more secure.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Would We need Angular Guard Protection?
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Block Access&lt;/strong&gt;: Let unauthorized users have no access to the routes you select.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Role-Based Access Control&lt;/strong&gt;: Grant or deny access according to user roles.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoid Unsaved Data Loss&lt;/strong&gt;: Prompt the user for unsaved changes when navigating away from the page.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Preloading of Data Before Navigation&lt;/strong&gt;: Load data needed before a component is routed in.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lazy Loading Optimization&lt;/strong&gt;: Manage lazy loading of modules efficiently.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Types of Route Guards in Angular
&lt;/h2&gt;

&lt;p&gt;There are five different types of route guards in Angular:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;canActivate&lt;/strong&gt;: Checks whether the user can go to a certain route.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;canActivateChild&lt;/strong&gt;: Determines whether users should be able to reach child routes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;canDeactivate&lt;/strong&gt;: Prevents users from leaving a route unless they meet some condition.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;resolve&lt;/strong&gt;: It pre-loads data ahead of the route's activation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;canLoad&lt;/strong&gt;: Disallows loading of lazy-loaded modules if the condition is not met.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How to Use Route Guards in Angular
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. &lt;code&gt;canActivate&lt;/code&gt; - Block Access
&lt;/h3&gt;

&lt;p&gt;This guard prevents unauthorized access to certain routes.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementation:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;CanActivate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;Router&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/router&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;providedIn&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;root&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AuthGuard&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;CanActivate&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Router&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

  &lt;span class="nf"&gt;canActivate&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;isAuthenticated&lt;/span&gt; &lt;span class="o"&gt;=!!&lt;/span&gt;&lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;token&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;isAuthenticated&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;navigate&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/login&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Usage:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;dashboard&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;component&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;DashboardComponent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;canActivate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;AuthGuard&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. &lt;code&gt;canActivateChild&lt;/code&gt; - Protect Child Routes
&lt;/h3&gt;

&lt;p&gt;This guard restricts access to child routes just like &lt;code&gt;canActivate&lt;/code&gt; does for parent routes.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementation:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;CanActivateChild&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;Router&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/router&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;providedIn&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;root&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ChildAuthGuard&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;CanActivateChild&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Router&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

  &lt;span class="nf"&gt;canActivateChild&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;hasPermission&lt;/span&gt; &lt;span class="o"&gt;=!!&lt;/span&gt;&lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;hasPermission&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;navigate&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Usage:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;component&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;AdminComponent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;canActivateChild&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;ChildAuthGuard&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
  &lt;span class="nx"&gt;children&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;users&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;component&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UsersComponent&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;settings&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;component&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;SettingsComponent&lt;/span&gt; &lt;span class="p"&gt;}]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. &lt;code&gt;canDeactivate&lt;/code&gt; - Prevent Accidental Data Loss
&lt;/h3&gt;

&lt;p&gt;This guard prevents the user from navigating away from a certain component if there are unsaved changes.&lt;/p&gt;

&lt;h4&gt;
  
  
  Solution:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;CanDeactivate&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/router&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kr"&gt;interface&lt;/span&gt; &lt;span class="nx"&gt;CanComponentDeactivate&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;canDeactivate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;providedIn&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;root&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CanLeaveGuard&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;CanDeactivate&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;CanComponentDeactivate&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;canDeactivate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="na"&gt;component&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;CanComponentDeactivate&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;component&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;canDeactivate&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="nx"&gt;component&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;canDeactivate&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Component Implementation:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Component&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;CanComponentDeactivate&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./guards/can-leave.guard&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Component&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;selector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;app-profile&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;templateUrl&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./profile.component.html&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ProfileComponent&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;CanComponentDeactivate&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;unsavedChanges&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="nf"&gt;canDeactivate&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;unsavedChanges&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="nf"&gt;confirm&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;You have unsaved changes. Leave anyway?&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Usage:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;profile&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;component&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ProfileComponent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;canDeactivate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;CanLeaveGuard&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. &lt;code&gt;resolve&lt;/code&gt; - Fetch Data Before Route Activation
&lt;/h3&gt;

&lt;p&gt;This ensures that data are fetched before the route is activated.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementation:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Resolve&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/router&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;of&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;providedIn&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;root&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserResolver&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;Resolve&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kr"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kr"&gt;any&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;of&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;John Doe&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt; &lt;span class="c1"&gt;// Example API call&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Usage:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ path: 'user', component: UserComponent, resolve: { userData: UserResolver } }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  How to access resolved data in Component:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;ActivatedRoute&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/router&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;route&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;ActivatedRoute&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

&lt;span class="nf"&gt;ngOnInit&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;route&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;userData&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. &lt;code&gt;canLoad&lt;/code&gt; - Blocking Lazy Module Loading
&lt;/h3&gt;

&lt;p&gt;This guard prevents lazy-loaded modules to be loaded in case conditions aren't met.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementation:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;CanLoad&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;Route&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;UrlSegment&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;Router&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/router&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;providedIn&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;root&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AdminLoadGuard&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nx"&gt;CanLoad&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Router&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

  &lt;span class="nf"&gt;canLoad&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;route&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Route&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;segments&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;UrlSegment&lt;/span&gt;&lt;span class="p"&gt;[]):&lt;/span&gt; &lt;span class="nx"&gt;boolean&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;isAdmin&lt;/span&gt; &lt;span class="o"&gt;=!!&lt;/span&gt;&lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;isAdmin&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;navigate&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Usage:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;loadChildren&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./admin/admin.module&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;m&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;m&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;AdminModule&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nx"&gt;canLoad&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;AdminLoadGuard&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Route guards in Angular play a great role in route protection, navigation control, and optimization of performance. You will efficiently manage your users' access and data flow within your applications by implementing the different guards of &lt;code&gt;canActivate&lt;/code&gt;, &lt;code&gt;canActivateChild&lt;/code&gt;, &lt;code&gt;canDeactivate&lt;/code&gt;, &lt;code&gt;resolve&lt;/code&gt;, and &lt;code&gt;canLoad&lt;/code&gt;.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Advanced implementation of Licensing Validation in angular applications.</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Tue, 28 Jan 2025 08:16:27 +0000</pubDate>
      <link>https://dev.to/rohitchdy/advanced-implementation-of-licensing-validation-in-angular-c52</link>
      <guid>https://dev.to/rohitchdy/advanced-implementation-of-licensing-validation-in-angular-c52</guid>
      <description>&lt;p&gt;Licensing validation is any application's most important feature, allowing only authorized users to access its functionalities. In an Angular application, the licensing validation normally takes place by the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The Angular app is loaded.&lt;/li&gt;
&lt;li&gt;The licensing information is fetched from a backend API or local storage.&lt;/li&gt;
&lt;li&gt;The licensing data is validated.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That does the job but there's more grace in doing a license check without loading up the Angular application first. Using what's called an &lt;strong&gt;AppInitializer in Angular&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is AppInitializer in Angular?
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;AppInitializer&lt;/code&gt; is a special Angular provider for running some code before Angular has fully initialized the application. It's used everywhere when one needs for example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Loading settings.&lt;/li&gt;
&lt;li&gt;Services initialization.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can use &lt;code&gt;AppInitializer&lt;/code&gt; for license validation so that the application checks for a license before it loads up, adding to both security and user experience.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Use AppInitializer for Licensing Validation in Angular
&lt;/h2&gt;

&lt;p&gt;Here's how you can validate licensing using &lt;code&gt;AppInitializer&lt;/code&gt; in Angular:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Create a License Service
&lt;/h3&gt;

&lt;p&gt;The logic for validation will be carried out by the license service. This may call a license data from the local storage or from an external server. The implementation may look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Injectable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;HttpClient&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/common/http&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;rxjs&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;Injectable&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;providedIn&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;root&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LicenseService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nx"&gt;http&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;HttpClient&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

  &lt;span class="nf"&gt;validateLicense&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;Observable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;boolean&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;licenseService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;validateLicense&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;/api/validate-license&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;subscribe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="nx"&gt;success&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;success&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nf"&gt;alert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Invalid License!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="c1"&gt;// You can redirect or stop the app from initializing&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;alert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;License validation failed!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Implement the AppInitializer Function
The &lt;code&gt;AppInitializer&lt;/code&gt; function will make sure to validate the license before the app starts. It calls the &lt;code&gt;LicenseService&lt;/code&gt;'s &lt;code&gt;validateLicense&lt;/code&gt; method and waits for the result.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;LicenseService&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./license.service&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;APP_INITIALIZER&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;licenseInitializer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;licenseService&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;LicenseService&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;licenseService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;validateLicense&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;toPromise&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nf"&gt;alert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Invalid or missing license!&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="c1"&gt;// Handle invalid license (e.g., redirect or block app initialization)&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Provide the AppInitializer in the AppModule
&lt;/h3&gt;

&lt;p&gt;By providing &lt;code&gt;APP_INITIALIZER&lt;/code&gt; in the &lt;code&gt;AppModule&lt;/code&gt;, the app will wait for the license validation to complete before proceeding to load.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;NgModule&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/core&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;BrowserModule&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/platform-browser&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;AppComponent&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./app.component&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;LicenseService&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./license.service&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;licenseInitializer&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;./app-initializer&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;HttpClientModule&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@angular/common/http&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;@&lt;/span&gt;&lt;span class="nd"&gt;NgModule&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;declarations&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;AppComponent&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
  &lt;span class="na"&gt;imports&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;BrowserModule&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;HttpClientModule&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
  &lt;span class="na"&gt;providers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="na"&gt;provide&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;APP_INITIALIZER&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;useFactory&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;licenseInitializer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;deps&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;LicenseService&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
      &lt;span class="na"&gt;multi&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;],&lt;/span&gt;
  &lt;span class="na"&gt;bootstrap&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;AppComponent&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AppModule&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Handle Invalid License
&lt;/h3&gt;

&lt;p&gt;In the case of an invalid license or no license, the &lt;code&gt;AppInitializer&lt;/code&gt; can prevent the app from loading and inform the user. You may want to show an alert or navigate the user to a license activation page.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why AppInitializer for Licensing?
&lt;/h2&gt;

&lt;p&gt;Using &lt;code&gt;AppInitializer&lt;/code&gt; to validate licenses has several advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Avoids Unauthorized Access&lt;/strong&gt;: Because the app will only load if the license is valid.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enhanced Security&lt;/strong&gt;: The validation occurs before any application logic is executed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enhanced User Experience&lt;/strong&gt;: Provides appropriate messaging for invalid licenses without partially loading the app.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Centralized Logic&lt;/strong&gt;: All initialization tasks, including licensing, can be handled in a clean and organized manner.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;AppInitializer in Angular provides a very handy way to perform some crucial operations before the application is fully loaded. It can be combined with license validation to further increase the security, reliability, and user experience of your application. The approach will provide you with certainty that only valid users will access your application's features, which equals peace of mind for both you and the users.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Third-party API Integration using ASP.Net Core web API.</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Sat, 16 Mar 2024 12:48:56 +0000</pubDate>
      <link>https://dev.to/rohitchdy/third-party-api-integration-using-aspnet-core-web-api-3bbf</link>
      <guid>https://dev.to/rohitchdy/third-party-api-integration-using-aspnet-core-web-api-3bbf</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu5qlo470bglz8rtbm1up.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu5qlo470bglz8rtbm1up.png" alt="Third-party API integration guidelines" width="376" height="148"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Third-party API integration guidelines
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Identify the API&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read their documentation thoroughly and understand its features, authentication requirements, and request and response formats.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Create a Separate Service&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create a separate service or class to encapsulate the logic related to the third-party API integration. This will help to keep the code organized and maintainable.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Add necessary dependencies&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the third-party API requires additional dependencies or SDKs, install them using NuGet packages in our ASP.Net Core Web API.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Handle authentication&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Determine the authentication mechanism required by the third-party API. Implement the necessary authentication logic in our service. Store any sensitive information such as API keys or secrets in a secure configuration store, like environment variables.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Make HTTP Requests&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use the &lt;code&gt;HttpClient&lt;/code&gt; class in ASP.NET Core to send HTTP requests to the third-party API. Construct the request payload and headers according to the API documentation. You can use the &lt;code&gt;System.Net.Http&lt;/code&gt; namespace for this purpose. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Handle Responses&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Handle the responses from the third-party API by parsing the returned data according to the API documentation. If needed, map the response data to your domain models or DTOs (Data Transfer Objects).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Error handling&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Implement error handling logic to handle any exceptions or error responses from the third-party API.  Consider implementing retries for temporary failures or rate-limited scenarios. You can use policies provided by libraries like Polly to handle retries and transient errors.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Caching and rate limiting&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the third-party  API  has rate limits or if you want to optimize performance, consider implementing caching mechanisms to store and reuse API responses. Caching can be done using an in-memory cache or distributed cache options like Redis.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Unit Testing&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Write unit tests for your service to ensure that the integration with the third-party API works as expected. You can use mocking frameworks like Moq to mock the API responses and test various scenarios.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Logging and Monitoring&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Implement logging to record any important events, errors, or debug information related to the integration with the third-party API. Consider using a logging framework like Serilog or the built-in logging capabilities of ASP.NET Core. Additionally, you can monitor API usage and performance using tools like Application Insights.&lt;/p&gt;

&lt;p&gt;These are the guidelines for third-party API integration. &lt;br&gt;
&lt;em&gt;I will provide code implementation in the next part.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>thirdpartyapiintegration</category>
      <category>api</category>
      <category>apiintegration</category>
      <category>consumewebservices</category>
    </item>
    <item>
      <title>Implementing Soft Delete With EF Core.</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Sat, 16 Mar 2024 08:21:09 +0000</pubDate>
      <link>https://dev.to/rohitchdy/implementing-soft-delete-with-ef-core-1gmm</link>
      <guid>https://dev.to/rohitchdy/implementing-soft-delete-with-ef-core-1gmm</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwjqv1sfq2c3qztpv0pzz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwjqv1sfq2c3qztpv0pzz.png" alt="Soft Delete with EF Core." width="287" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is soft delete?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Prevents permanent deletion of records.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flag set on record, indicating "delete".&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Allows for easy restoration and maintains data integrity.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to implement:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Create Marker Interface.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Define a marker interface ISoftDelete to mark entities that support soft delete.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ISoftDelete
{
    bool IsDeleted { get; set; }
    DateTime? DeleteOnUtc { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Implement Soft Delete Interceptor.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create a class SoftDeleteInterceptor to handle soft deletes in EF Core.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public sealed class SoftDeleteInterceptor: SaveChangesInterceptor
{
    public override ValueTask&amp;lt;InterceptionResult&amp;lt;int&amp;gt;&amp;gt; SavingChangesAsync(
        DbContextEventData eventData,
        InterceptionResult&amp;lt;int&amp;gt; result,
        CancellationToken cancellationToken = default)
    {
        if (eventData.Context is null)
        {
            return base.SavingChangesAsync(eventData, result, cancellationToken);
        }

        IEnumerable&amp;lt;EntityEntry&amp;lt;ISoftDeletable&amp;gt;&amp;gt; entries =
            eventData.Context.ChangeTracker.Entries&amp;lt;ISoftDeletable&amp;gt;()
                .Where(e =&amp;gt; e.State == EntityState.Deleted);

        foreach (EntityEntry&amp;lt;ISoftDeletable&amp;gt; softDeletable in entries)
        {
            softDeletable.State = EntityState.Modified;
            softDeletable.Entity.IsDeleted = true;
            softDeletable.Entity.DeletedOnUtc = DateTime.UtcNow;
        }

        return base.SavingChangesAsync(eventData, result, cancellationToken);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Configure Application Context.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Configure EF Core to use the soft delete interceptor and global query filters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ApplicationDbContext: DbContext
{
    public ApplicationDbContext(DbContextOptions&amp;lt;ApplicationDbContext&amp;gt; options)
        : base(options)
    {
    }

    public DbSet&amp;lt;User&amp;gt; Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // HasQueryFilter is used to filter soft-deleted data automatically.
        modelBuilder.Entity&amp;lt;User&amp;gt;().HasQueryFilter(r =&amp;gt; !r.IsDeleted);

        modelBuilder.Entity&amp;lt;User&amp;gt;()
        .HasIndex(r=&amp;gt; r.IsDeleted)
        .HasFilter("IsDeleted=0");

        // This HasFilter method accepts the SQL filter for records that will be 
            included in the index.
        // You can also create a filtered index using SQL:
         /*
           Create index IX_Users_IsDeleted on User(IsDeleted) where IsDelete =0;
         */
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Register SoftDeleteIntercepter with dependency injection.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;services.AddSingleton&amp;lt;SoftDeleteInterceptor&amp;gt;();
services.AddDbContext&amp;lt;ApplicationDbContext&amp;gt;(
    sp, options)=&amp;gt;options
        .UseSqlServer(connectionString)
        .AddInterceptor(
               sp.GetRequiredService&amp;lt;SoftDeleteInterceptor&amp;gt;()));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Example Entity.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create an example entity Review implementing the soft delete marker interface.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class User: ISoftDeletable
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime? DeletedOnUtc { get; set; }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Benefits:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Flexibility in managing data.&lt;/li&gt;
&lt;li&gt;Simplified queries with automatic exclusion of soft-deleted records.&lt;/li&gt;
&lt;li&gt;Improved performance with filtered indexes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Soft delete ensures data integrity and flexibility in managing records without compromising performance.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>efcore</category>
      <category>softdelete</category>
      <category>softdeletewithefcore</category>
      <category>softdeleteindotnetcore</category>
    </item>
    <item>
      <title>Prototype Design Pattern in C#</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Sat, 24 Feb 2024 13:37:30 +0000</pubDate>
      <link>https://dev.to/rohitchdy/prototype-design-pattern-in-c-338d</link>
      <guid>https://dev.to/rohitchdy/prototype-design-pattern-in-c-338d</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwu6clq9xxqq7merkh351.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwu6clq9xxqq7merkh351.png" alt="Prototype Design Pattern" width="760" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
The Prototype design pattern is a creation design pattern that specifies creating new objects by copying an existing object, thus avoiding the need to create new classes. This pattern allows us to clone existing objects, creating new instances with the same data. Any changes made to the cloned object do not affect the original object. It’s especially handy when the cost of creating an object is more expensive or complex than copying an existing one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example to Understand Prototype Design Pattern&lt;/strong&gt;&lt;br&gt;
Let’s illustrate this with a simple example. Suppose we have an Employee class with properties like Name and Department. When we copy one employee object to another using the assignment operator (=), both objects share the same memory address. However, we want to create a new object without affecting the original. Here’s how you can achieve that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;

namespace PrototypeDesignPattern
{
    class Employee
    {
        public string Name { get; set; }
        public string Department { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of Employee
            var emp1 = new Employee { Name = "John", Department = "HR" };

            // Create another employee instance by assigning the existing one
            var emp2 = emp1;

            // Change the Name property of emp2
            emp2.Name = "Alice";

            // Both emp1 and emp2 share the same memory
            Console.WriteLine($"Employee 1: {emp1.Name}, {emp1.Department}");
            Console.WriteLine($"Employee 2: {emp2.Name}, {emp2.Department}");
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, modifying emp2 also affects emp1 because they share the same memory. However, the Prototype Design Pattern allows us to create a new object without this shared reference.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to Use Prototype Design Pattern?&lt;/strong&gt;&lt;br&gt;
The Prototype Design Pattern is particularly useful in scenarios where:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Object creation is costly in terms of resources and time.&lt;/li&gt;
&lt;li&gt;You have an existing object similar to the one needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Real-Time Example of Prototype Design Pattern&lt;/strong&gt;&lt;br&gt;
In real-world scenarios, the Prototype Design Pattern is frequently used in game development. It allows instantiating multiple instances of game entities without the overhead of constructing each one from scratch.&lt;/p&gt;

&lt;p&gt;Remember, the Prototype Design Pattern provides a way to create new or cloned objects from existing ones, making it a powerful tool for efficient object creation.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>designpatterns</category>
      <category>prototypedesignpattern</category>
    </item>
    <item>
      <title>Factory Method Design Pattern in C#</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Sat, 24 Feb 2024 13:19:05 +0000</pubDate>
      <link>https://dev.to/rohitchdy/factory-method-design-pattern-in-c-39f1</link>
      <guid>https://dev.to/rohitchdy/factory-method-design-pattern-in-c-39f1</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwqblrgvazycj7e6hhj0n.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwqblrgvazycj7e6hhj0n.jpg" alt="Factory Method Design Pattern" width="310" height="163"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Factory Method Design Pattern is a creational design pattern that allows us to create objects without exposing the creation logic to the client. It provides a way to create objects based on input parameters and returns them using a common interface.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Time Example&lt;/strong&gt;&lt;br&gt;
Suppose we’re building an application to display Credit Card Details. We have three credit card classes: MoneyBack, Titanium, and Platinum, all of which are subclasses of the CreditCard superclass (or super interface). Each credit card class implements methods like GetCardType, GetCreditLimit, and GetAnnualCharge.&lt;/p&gt;

&lt;p&gt;Our task is to ask the user to select a credit card type. Based on their choice, we need to display relevant information about the selected credit card.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example Without Using the Factory Pattern&lt;/strong&gt;&lt;br&gt;
Let’s first see how we might approach this without using the Factory Design Pattern:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Without Factory Pattern
class Program
{
    static void Main()
    {
        // User selects a credit card type (e.g., "MoneyBack")
        string userChoice = GetUserInput();

        // Create an instance based on user choice
        CreditCard card;
        if (userChoice == "MoneyBack")
            card = new MoneyBack();
        else if (userChoice == "Titanium")
            card = new Titanium();
        else if (userChoice == "Platinum")
            card = new Platinum();
        else
            throw new ArgumentException("Invalid choice");

        // Display credit card details
        Console.WriteLine($"Card Type: {card.GetCardType()}");
        Console.WriteLine($"Credit Limit: {card.GetCreditLimit()}");
        Console.WriteLine($"Annual Charge: {card.GetAnnualCharge()}");
    }

    // Other methods...
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problems Without Factory Pattern&lt;/strong&gt;&lt;br&gt;
Tight Coupling: The client code is tightly coupled to specific credit card classes.&lt;br&gt;
Maintenance Challenges: Adding new credit card types requires modifying the client code.&lt;br&gt;
Testing Complexity: Unit testing becomes difficult due to direct dependencies on concrete classes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementing the Factory Design Pattern&lt;/strong&gt;&lt;br&gt;
Now let’s use the Factory Design Pattern to address these issues:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// With Factory Pattern
class Program
{
    static void Main()
    {
        // User selects a credit card type (e.g., "MoneyBack")
        string userChoice = GetUserInput();

        // Create a credit card factory
        CreditCardFactory factory = new CreditCardFactory();

        // Get the appropriate credit card object
        CreditCard card = factory.CreateCreditCard(userChoice);

        // Display credit card details
        Console.WriteLine($"Card Type: {card.GetCardType()}");
        Console.WriteLine($"Credit Limit: {card.GetCreditLimit()}");
        Console.WriteLine($"Annual Charge: {card.GetAnnualCharge()}");
    }

    // Other methods...
}

// Factory class
class CreditCardFactory
{
    public CreditCard CreateCreditCard(string type)
    {
        switch (type)
        {
            case "MoneyBack":
                return new MoneyBack();
            case "Titanium":
                return new Titanium();
            case "Platinum":
                return new Platinum();
            default:
                throw new ArgumentException("Invalid choice");
        }
    }
}

// Credit card superclass
interface CreditCard
{
    string GetCardType();
    decimal GetCreditLimit();
    decimal GetAnnualCharge();
}

// Concrete credit card classes
class MoneyBack : CreditCard { /* Implementation */ }
class Titanium : CreditCard { /* Implementation */ }
class Platinum : CreditCard { /* Implementation */ }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;br&gt;
The Factory Design Pattern provides flexibility, separation of concerns, and better maintainability. It allows us to create objects dynamically based on input parameters, without exposing the creation logic to the client. Choose the Factory Pattern when you need to create objects with varying behavior or when you want to promote loose coupling between client code and concrete classes&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>designpatterns</category>
      <category>factorydesignpattern</category>
    </item>
    <item>
      <title>Repository Pattern Vs Entity Framework</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Sat, 24 Feb 2024 11:06:12 +0000</pubDate>
      <link>https://dev.to/rohitchdy/repository-pattern-vs-entity-framework-55ga</link>
      <guid>https://dev.to/rohitchdy/repository-pattern-vs-entity-framework-55ga</guid>
      <description>&lt;p&gt;The "Repository Pattern Vs Entity Framework" is indeed a topic of debate among software developers, and there isn't a definitive answer that applies universally to all scenarios. Different developers and teams may have different preferences and experiences that influence their perspective on this matter.&lt;/p&gt;

&lt;p&gt;The choice between the Repository Pattern and Entity Framework often depends on various factors, including the project's requirements, complexity, team expertise, existing infrastructure, and personal preferences.&lt;/p&gt;

&lt;p&gt;Some developers prefer the Repository Pattern because it provides clear separation between the application's business logic and the database access layer, making it easier to test, maintain and switch between different data sources. It also allows for more flexibility and customization, as developer have full control over the repository implementations.&lt;/p&gt;

&lt;p&gt;Lets see with and sample C# code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// User model representing a user entity in the application
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// UserRepository interface defining the contract for interacting with user data
public interface IUserRepository
{
    User GetById(int userId);
    User GetByEmail(string email);
    void Save(User user);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Concrete implementation of the UserRepository interface using a relational database
public class DatabaseUserRepository : IUserRepository
{
    public User GetById(int userId)
    {
        // Database query to fetch user by id
        // ...
    }

    public User GetByEmail(string email)
    {
        // Database query to fetch user by email
        // ...
    }

    public void Save(User user)
    {
        // Database query to save the user
        // ...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Concrete implementation of the UserRepository interface using an external API
public class ExternalAPIUserRepository : IUserRepository
{
    public User GetById(int userId)
    {
        // API call to fetch user by id
        // ...
    }

    public User GetByEmail(string email)
    {
        // API call to fetch user by email
        // ...
    }

    public void Save(User user)
    {
        // API call to save the user
        // ...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Service layer or business logic layer using the UserRepository interface
public class UserService
{
    private readonly IUserRepository userRepository;

    public UserService(IUserRepository userRepository)
    {
        this.userRepository = userRepository;
    }

    public void CreateUser(string name, string email)
    {
        // Create a new user instance
        var user = new User { Name = name, Email = email };

        // Save the user using the repository
        userRepository.Save(user);
    }

    public User GetUserById(int userId)
    {
        // Fetch the user by id using the repository
        return userRepository.GetById(userId);
    }

    public User GetUserByEmail(string email)
    {
        // Fetch the user by email using the repository
        return userRepository.GetByEmail(email);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above code we can see that, the business logic layer is represented by the "&lt;strong&gt;UserService&lt;/strong&gt;" class. It contains the method such as "&lt;strong&gt;CreateUser&lt;/strong&gt;", "&lt;strong&gt;GetUserById&lt;/strong&gt;" and "&lt;strong&gt;GetUserByEmail&lt;/strong&gt;" that encapsulate the application's specific logic for creating users and retriving users based on different criteria.&lt;/p&gt;

&lt;p&gt;The data access layer is seperated into the repository interfaces "&lt;strong&gt;IUserRepositoty&lt;/strong&gt;" and their concrete implementations "&lt;strong&gt;DatabaseUserRepositoty&lt;/strong&gt;" and "&lt;strong&gt;ExternalAPIUserRepository&lt;/strong&gt;". These classes handle the actual interaction with the underling datasources, such as a relational database or an external API.&lt;/p&gt;

&lt;p&gt;Now let's discuss how this code structure makes it easier to test, maintain and switch between different data sources.&lt;/p&gt;

&lt;p&gt;Lets write a test.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[TestFixture]
public class UserServiceTests
{
    [Test]
    public void CreateUser_Should_Save_User_Using_Repository()
    {
        // Arrange
        Mock&amp;lt;IUserRepository&amp;gt; userRepositoryMock = new Mock&amp;lt;IUserRepository&amp;gt;();
        UserService userService = new UserService(userRepositoryMock.Object);
        string name = "Rohit Chaudhary";
        string email = "rohit@chaudhary.com";

        // Act
        userService.CreateUser(name, email);

        // Assert
        userRepositoryMock.Verify(repo =&amp;gt; repo.Save(It.Is&amp;lt;User&amp;gt;(user =&amp;gt; user.Name == name &amp;amp;&amp;amp; user.Email == email)), Times.Once);
    }

    // Similar tests for other methods of UserService
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the business logic &lt;strong&gt;UserService&lt;/strong&gt; depends on abstractions &lt;strong&gt;IUserRepository&lt;/strong&gt; interface instead of concrete implementations. This allows for easier testing, as you can create mock implementations of the repositoty interface to isolate the business logic from the actual data storage.&lt;/p&gt;

&lt;p&gt;Now suppose we want to switch from using a database repository to an API repository. We can simply create a new concrete implementation of the &lt;strong&gt;IUserRepository&lt;/strong&gt; interface for the API repository, inject it into the &lt;strong&gt;UserService&lt;/strong&gt; class, and business logic remains the same.&lt;br&gt;
Here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Concrete implementation of the UserRepository interface using an API
public class APIUserRepository : IUserRepository
{
    public User GetById(int userId)
    {
        // API call to fetch user by id
        // ...
    }

    public User GetByEmail(string email)
    {
        // API call to fetch user by email
        // ...
    }

    public void Save(User user)
    {
        // API call to save the user
        // ...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Switching to API repository
IUserRepository userRepository = new APIUserRepository();
UserService userService = new UserService(userRepository);

// Now, the UserService can seamlessly work with the API repository without any changes to its methods.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From above explanation we can conclude that, it gives the flexibility to adopt to changing requirements and incorporate different data sources based on our needs.&lt;/p&gt;

&lt;p&gt;By utilizing the Repository Pattern, the above provided code structure enhances testability, maintainability, and flexibility in the following ways:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The business logic is decoupled from the data access layer, enabling easier testing and isolation of the business logic.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Changes in the data access layer can be made without affecting the business logic, leading easier maintenance.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Switching between different data sources becomes simpler by creating new concrete implementation of repository interfaces, allowing for seamless integration with different data storage technologies or APIs.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While the Repository Pattern offers clear benefits in terms of flexibility and separation of concerns, it's also worth considering the advantages of using Entity Framework (EF) as an alternative approach to data access.&lt;/p&gt;

&lt;p&gt;Entity Framework is an Object-Relational Mapping (ORM) framework provided by Microsoft, which simplifies the interaction between the application and the database by allowing developers to work with database entities as .NET objects directly. &lt;br&gt;
Here are some reasons why you might choose Entity Framework over the Repository Pattern:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Rapid Development: Entity Framework allows developers to quickly scaffold database models from existing databases or code-first approaches, reducing the amount of boilerplate code needed for data access.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;LINQ Support: Entity Framework provides robust support for Language Integrated Query (LINQ), allowing developers to write queries using familiar C# syntax, which can lead to more concise and readable code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Automatic Change Tracking: Entity Framework automatically tracks changes to entities, making it easier to manage updates and ensure data consistency without manually writing CRUD operations.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimized Queries: Entity Framework generates optimized SQL queries based on LINQ expressions, helping to improve performance and reduce the risk of SQL injection attacks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Integration with Other Microsoft Technologies: Entity Framework integrates seamlessly with other Microsoft technologies such as ASP.NET Core, making it a natural choice for developers working in the Microsoft ecosystem.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Maturity and Community Support: Entity Framework has been around for many years and has a large community of users, which means there are plenty of resources, tutorials, and third-party libraries available to support development efforts.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here's how the UserService class might look if implemented using Entity Framework:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class UserService
{
    private readonly DbContext _dbContext;

    public UserService(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public void CreateUser(string name, string email)
    {
        var user = new User { Name = name, Email = email };
        _dbContext.Set&amp;lt;User&amp;gt;().Add(user);
        _dbContext.SaveChanges();
    }

    public User GetUserById(int userId)
    {
        return _dbContext.Set&amp;lt;User&amp;gt;().Find(userId);
    }

    public User GetUserByEmail(string email)
    {
        return _dbContext.Set&amp;lt;User&amp;gt;().FirstOrDefault(u =&amp;gt; u.Email == email);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In conclusion, while the Repository Pattern offers advantages in terms of flexibility and testability, Entity Framework provides a more streamlined approach to data access, particularly for developers working in the Microsoft ecosystem or those looking for rapid development and integration with other Microsoft technologies. Ultimately, the choice between the Repository Pattern and Entity Framework depends on the specific requirements and constraints of the project.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Builder Design Pattern in C#</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Sat, 24 Feb 2024 10:52:35 +0000</pubDate>
      <link>https://dev.to/rohitchdy/builder-design-pattern-in-c-4215</link>
      <guid>https://dev.to/rohitchdy/builder-design-pattern-in-c-4215</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj1nxr39ccweguzegr4cp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj1nxr39ccweguzegr4cp.png" alt="Builder Design Pattern in C#" width="301" height="167"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
The Builder Design Pattern builds a complex object using many simple objects and a step-by-step approach. The goal is to create a generic process for constructing the complex object, which can be used to create different representations of the same object. This pattern is especially handy when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You need to create an object with many optional and required fields.&lt;/li&gt;
&lt;li&gt;The object’s construction process is complex.&lt;/li&gt;
&lt;li&gt;Multiple representations of the object are possible.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Real-Life Analogy&lt;/strong&gt;&lt;br&gt;
Imagine building a laptop. A laptop is a complex object composed of various smaller components like LCD displays, USB ports, hard drives, batteries, keyboards, and more. To construct a laptop, we follow a generic process:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Plug in the memory.&lt;/li&gt;
&lt;li&gt;Plug in the hard drive.&lt;/li&gt;
&lt;li&gt;Plug in the battery.&lt;/li&gt;
&lt;li&gt;Plug in the keyboard.&lt;/li&gt;
&lt;li&gt;Cover the laptop with a plastic case.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Using this process, we can create different types of laptops—some with 14-inch screens, others with 17-inch screens, varying RAM sizes, and so on. The Builder Design Pattern allows us to assemble these small components into a cohesive whole, following the same generic process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation in C#&lt;/strong&gt;&lt;br&gt;
In C#, you can use the Builder Design Pattern to create objects with many optional components or configurations. Here’s how it works:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Define a Builder class responsible for constructing the complex object step by step.&lt;/li&gt;
&lt;li&gt;The Builder class has methods for adding components (e.g., memory, hard drive, battery).&lt;/li&gt;
&lt;li&gt;A Director class orchestrates the construction process by invoking the Builder methods.&lt;/li&gt;
&lt;li&gt;The final complex object is retrieved from the Builder.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Here’s a simplified example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;

// Product class (complex object)
class Laptop
{
    public int MemorySize { get; set; }
    public string HardDriveType { get; set; }
    // Other properties...

    public void DisplayInfo()
    {
        Console.WriteLine($"Laptop Info: Memory: {MemorySize}GB, Hard Drive: {HardDriveType}");
        // Display other properties...
    }
}

// Builder interface
interface ILaptopBuilder
{
    void AddMemory(int size);
    void AddHardDrive(string type);
    // Other methods for adding components...
    Laptop GetLaptop();
}

// Concrete builder
class LaptopBuilder : ILaptopBuilder
{
    private Laptop _laptop = new Laptop();

    public void AddMemory(int size)
    {
        _laptop.MemorySize = size;
    }

    public void AddHardDrive(string type)
    {
        _laptop.HardDriveType = type;
    }

    // Other component methods...

    public Laptop GetLaptop()
    {
        return _laptop;
    }
}

// Director
class LaptopManufacturer
{
    public Laptop ConstructLaptop(ILaptopBuilder builder)
    {
        builder.AddMemory(8); // Example: Add 8GB RAM
        builder.AddHardDrive("SSD"); // Example: Add SSD
        // Other component additions...
        return builder.GetLaptop();
    }
}

class Program
{
    static void Main()
    {
        var builder = new LaptopBuilder();
        var manufacturer = new LaptopManufacturer();
        var myLaptop = manufacturer.ConstructLaptop(builder);

        // Display laptop info
        myLaptop.DisplayInfo();
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember that the Builder Design Pattern allows you to create different representations of the same complex object using a consistent construction process. It’s a powerful tool when dealing with intricate object creation.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>designpatterns</category>
      <category>bulderdesignpattern</category>
    </item>
    <item>
      <title>Abstract Factory Pattern in C#</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Sat, 24 Feb 2024 08:08:12 +0000</pubDate>
      <link>https://dev.to/rohitchdy/abstract-factory-pattern-in-c-44f6</link>
      <guid>https://dev.to/rohitchdy/abstract-factory-pattern-in-c-44f6</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh8j9tg1aojd36o4n1kep.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh8j9tg1aojd36o4n1kep.jpg" alt="Example of Abstract Factory Design Pattern Implementation" width="287" height="175"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
The Abstract Factory pattern is a creational design pattern that provides a way to create families of related or dependent objects without specifying their concrete classes. 1 It is useful when you want to decouple the creation of objects from their usage and when you want to have multiple variants of the same family of objects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;br&gt;
Let’s say you want to create a simulation of different types of vehicles, such as cars, trucks, and motorcycles. You want to have different families of vehicles, such as family vehicles, sports vehicles, and luxury vehicles. Each family of vehicles has its concrete implementation of the car, truck, and motorcycle interfaces.&lt;/p&gt;

&lt;p&gt;To implement the Abstract Factory pattern, you need to define the following components:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An abstract product interface for each type of object, such as a Car, Truck, and Motorcycle.&lt;/li&gt;
&lt;li&gt;A concrete product class for each variant of each type of object, such as Mustang, PickupTruck, and SportBike for the family vehicles family.&lt;/li&gt;
&lt;li&gt;An abstract factory interface that declares methods for creating each type of object, such as VehicleFactory.&lt;/li&gt;
&lt;li&gt;A concrete factory class for each family of objects that implements the abstract factory interface and returns the appropriate concrete products, such as FamilyVehicleFactory.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following code shows the implementation of these components in C#:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Abstract product interfaces
public interface Car
{
    void Drive();
}

public interface Truck
{
    void Drive();
}

public interface Motorcycle
{
    void Drive();
}

// Concrete product classes
public class Mustang : Car
{
    public void Drive()
    {
        Console.WriteLine("Driving a Mustang");
    }
}

public class PickupTruck : Truck
{
    public void Drive()
    {
        Console.WriteLine("Driving a Pickup Truck");
    }
}

public class SportBike : Motorcycle
{
    public void Drive()
    {
        Console.WriteLine("Riding a Sport Bike");
    }
}

// Abstract factory interface
public interface VehicleFactory
{
    Car CreateCar();
    Truck CreateTruck();
    Motorcycle CreateMotorcycle();
}

// Concrete factory classes
public class FamilyVehicleFactory : VehicleFactory
{
    public Car CreateCar()
    {
        return new Mustang();
    }

    public Truck CreateTruck()
    {
        return new PickupTruck();
    }

    public Motorcycle CreateMotorcycle()
    {
        return new SportBike();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use the Abstract Factory pattern, you need to create a client class that takes an abstract factory as a parameter and uses its methods to create and use the objects. The client class does not know which concrete products it receives from the factory, as it only uses the abstract product interfaces. This way, you can change the factory at runtime and get different variants of the same family of objects.&lt;/p&gt;

&lt;p&gt;The following code shows an example of a client class in C#:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Client
{
    private VehicleFactory _vehicleFactory;

    public Client(VehicleFactory vehicleFactory)
    {
        _vehicleFactory = vehicleFactory;
    }

    public void CreateVehicles()
    {
        Car car = _vehicleFactory.CreateCar();
        Truck truck = _vehicleFactory.CreateTruck();
        Motorcycle motorcycle = _vehicleFactory.CreateMotorcycle();

        car.Drive();
        truck.Drive();
        motorcycle.Drive();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To test the Abstract Factory pattern, you can create different concrete factories and pass them to the client class. The following code shows an example of how to do this in C#:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Program
{
    static void Main(string[] args)
    {
        // Create a family vehicle factory
        VehicleFactory familyVehicleFactory = new FamilyVehicleFactory();
        // Create a client with the family vehicle factory
        Client client = new Client(familyVehicleFactory);
        // Create and use the family vehicles
        client.CreateVehicles();

        // Output:
        // Driving a Mustang
        // Driving a Pickup Truck
        // Riding a Sport Bike

        // Create another concrete factory here and pass it to the client to get different variants of the same family of objects
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Benefits and Drawbacks&lt;/strong&gt;&lt;br&gt;
The Abstract Factory pattern has the following benefits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It promotes loose coupling by hiding the details of object creation from the client.&lt;/li&gt;
&lt;li&gt;It supports the open/closed principle by allowing new variants of objects to be added without changing the existing code.&lt;/li&gt;
&lt;li&gt;It supports the single responsibility principle by separating the creation of objects from their usage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Abstract Factory pattern has the following drawbacks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It may introduce unnecessary complexity and extra work in the initial writing of code.&lt;/li&gt;
&lt;li&gt;It may result in a large number of classes and interfaces, which can make the code harder to understand and maintain.&lt;/li&gt;
&lt;li&gt;It may require changes in the abstract factory interface and all its subclasses if new types of objects are added to the family.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>csharp</category>
      <category>aspnet</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Delegate in C#</title>
      <dc:creator>Rohit Cdy</dc:creator>
      <pubDate>Mon, 18 Dec 2023 18:40:22 +0000</pubDate>
      <link>https://dev.to/rohitchdy/why-to-use-delegate-in-c-with-example-3fad</link>
      <guid>https://dev.to/rohitchdy/why-to-use-delegate-in-c-with-example-3fad</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2yewmo27mq9v6q0ctbur.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2yewmo27mq9v6q0ctbur.jpg" alt="Delegate Example and Usages" width="287" height="175"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a Delegate?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A delegate in C# is a type that represents references to methods with a specific parameter list and return type.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When you create an instance of a delegate, you can associate it with any method that has a compatible signature (matching parameters and return type).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Delegates allow you to pass methods as arguments to other methods.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code Example&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;
using System.Collections.Generic;

public class Program
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    // Define a delegate to represent filtering methods
    public delegate bool FilterDelegate(Person p);

    public static void Main()
    {
        // Create some Person objects
        Person p1 = new Person() { Name = "Rohit", Age = 26 };
        Person p2 = new Person() { Name = "Lal", Age = 40 };
        Person p3 = new Person() { Name = "Prashant", Age = 65 };

        // Populate a list with Person objects
        List&amp;lt;Person&amp;gt; people = new List&amp;lt;Person&amp;gt;() { p1, p2, p3 };

        // Display people based on different filters
        DisplayPeople("Children", people, IsChild);
        DisplayPeople("Adults", people, IsAdult);
        DisplayPeople("Seniors", people, IsSenior);

        Console.Read();
    }

    // Display people based on a specified filter
    static void DisplayPeople(string title, List&amp;lt;Person&amp;gt; people, FilterDelegate filter)
    {
        Console.WriteLine(title + ":");
        foreach (Person p in people)
        {
            if (filter(p))
            {
                Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
            }
        }
        Console.WriteLine();
    }

    // Filter methods
    static bool IsChild(Person p) =&amp;gt; p.Age &amp;lt; 18;
    static bool IsAdult(Person p) =&amp;gt; p.Age &amp;gt;= 18 &amp;amp;&amp;amp; p.Age &amp;lt; 65;
    static bool IsSenior(Person p) =&amp;gt; p.Age &amp;gt;= 65;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key Concepts Explained&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Delegate Declaration:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We define a FilterDelegate to represent filtering methods that take a Person object and return a boolean value.&lt;/li&gt;
&lt;li&gt;This delegate allows us to dynamically choose different filters for our list of people.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Method Definitions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We have three filter methods: IsChild, IsAdult, and IsSenior.&lt;/li&gt;
&lt;li&gt;These methods determine whether a person falls into the child, adult, or senior category based on their age.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Displaying People:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The DisplayPeople method takes a title, a list of people, and a filter delegate.&lt;/li&gt;
&lt;li&gt;It iterates through the list and displays relevant information based on the specified filter.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Children:
Rohit, 26 years old

Adults:
Rohit, 26 years old
Lal, 40 years old

Seniors:
Prashant, 65 years old
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>csharp</category>
      <category>delegates</category>
    </item>
  </channel>
</rss>
