<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Techies Diary]]></title><description><![CDATA[C# / Delphi Developer | JavaScript enthusiastic]]></description><link>https://thoughtcopy.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 13 Oct 2026 09:58:39 GMT</lastBuildDate><atom:link href="https://thoughtcopy.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Azure Front Door with Azure App Service: A Practical Guide]]></title><description><![CDATA[Introduction
Modern cloud applications require:

Low latency

High availability

Global routing

SSL termination

DDoS protection

Web Application Firewall (WAF)


Azure Front Door (AFD) is Microsoft']]></description><link>https://thoughtcopy.com/azure-front-door-with-azure-app-service-a-practical-guide</link><guid isPermaLink="true">https://thoughtcopy.com/azure-front-door-with-azure-app-service-a-practical-guide</guid><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Tue, 18 Aug 2026 08:50:34 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Modern cloud applications require:</p>
<ul>
<li><p>Low latency</p>
</li>
<li><p>High availability</p>
</li>
<li><p>Global routing</p>
</li>
<li><p>SSL termination</p>
</li>
<li><p>DDoS protection</p>
</li>
<li><p>Web Application Firewall (WAF)</p>
</li>
</ul>
<p>Azure Front Door (AFD) is Microsoft's global application delivery service that routes user requests through Microsoft's edge network to the most appropriate backend service.</p>
<p>A typical architecture looks like:</p>
<pre><code class="language-text">Users
   │
   ▼
Azure Front Door
   │
   ▼
Azure App Service
   │
   ▼
Database / APIs
</code></pre>
<h3>Benefits of Azure Front Door</h3>
<ul>
<li><p>Global load balancing</p>
</li>
<li><p>SSL offloading</p>
</li>
<li><p>Improved performance</p>
</li>
<li><p>Web Application Firewall integration</p>
</li>
<li><p>Origin health monitoring</p>
</li>
<li><p>Custom domain support</p>
</li>
<li><p>Path-based routing</p>
</li>
<li><p>Centralized ingress point for distributed applications</p>
</li>
</ul>
<hr />
<h1>Azure Front Door Fundamentals</h1>
<p>Azure Front Door is a Layer-7 reverse proxy capable of routing HTTP and HTTPS traffic.</p>
<h2>Request Flow</h2>
<pre><code class="language-text">Browser / Client
       │
       ▼
Azure Front Door Endpoint
       │
       ▼
Route Matching
       │
       ▼
Origin Group
       │
       ▼
Origin (App Service)
</code></pre>
<h2>Core Components</h2>
<h3>Endpoint</h3>
<p>The public-facing DNS endpoint.</p>
<p>Example:</p>
<pre><code class="language-text">mydiary-cud7d3eahthmcre9.z02.azurefd.net
</code></pre>
<hr />
<h3>Route</h3>
<p>Determines how incoming requests are matched and forwarded.</p>
<p>Examples:</p>
<pre><code class="language-text">/*
</code></pre>
<pre><code class="language-text">/api/*
</code></pre>
<hr />
<h3>Origin Group</h3>
<p>A collection of backend services.</p>
<p>Example:</p>
<pre><code class="language-text">default-origin-group
</code></pre>
<p>Origin groups provide:</p>
<ul>
<li><p>Failover capability</p>
</li>
<li><p>Health monitoring</p>
</li>
<li><p>Traffic distribution</p>
</li>
</ul>
<hr />
<h3>Origin</h3>
<p>The actual backend service.</p>
<p>Example:</p>
<pre><code class="language-text">slazmydiary01.azurewebsites.net
</code></pre>
<hr />
<h1>Configuring Azure Front Door with App Service</h1>
<h2>Step 1: Deploy App Service</h2>
<p>Deploy your ASP.NET Core API.</p>
<p>Example:</p>
<pre><code class="language-text">https://myapp.azurewebsites.net
</code></pre>
<p>Validate that endpoints work directly:</p>
<pre><code class="language-text">GET /api/health
GET /api/expense
POST /api/auth/login
</code></pre>
<hr />
<h2>Step 2: Create Azure Front Door</h2>
<p>Create an Azure Front Door Standard or Premium profile.</p>
<p>Recommended for production:</p>
<pre><code class="language-text">Azure Front Door Standard
</code></pre>
<hr />
<h2>Step 3: Create an Origin Group</h2>
<p>Example:</p>
<pre><code class="language-text">app-origin-group
</code></pre>
<p>Recommended Health Probe Settings:</p>
<pre><code class="language-text">Protocol: HTTPS
Path: /health
Interval: 30 seconds
</code></pre>
<hr />
<h2>Step 4: Add App Service as Origin</h2>
<p>Example configuration:</p>
<pre><code class="language-text">Origin Type: App Service
Host Name: myapp.azurewebsites.net
HTTPS Port: 443
Origin Enabled: Yes
</code></pre>
<hr />
<h2>Step 5: Configure Route</h2>
<p>Recommended route configuration:</p>
<pre><code class="language-text">Pattern to Match: /*
Origin Group: app-origin-group
Origin Path: Empty
Forwarding Protocol: Match Incoming Request
</code></pre>
<hr />
<h2>Step 6: Enable HTTPS Redirection</h2>
<p>Enable:</p>
<pre><code class="language-text">Redirect all traffic to use HTTPS
</code></pre>
<p>This ensures:</p>
<ul>
<li><p>Secure communication</p>
</li>
<li><p>Better security compliance</p>
</li>
<li><p>Prevention of accidental HTTP access</p>
</li>
</ul>
<hr />
<h1>Advanced Azure Front Door Features</h1>
<h2>Custom Domains</h2>
<p>Instead of:</p>
<pre><code class="language-text">myapp.azurefd.net
</code></pre>
<p>Use:</p>
<pre><code class="language-text">api.contoso.com
</code></pre>
<p>Benefits:</p>
<ul>
<li><p>Branding</p>
</li>
<li><p>Easier management</p>
</li>
<li><p>Better user experience</p>
</li>
</ul>
<hr />
<h2>Web Application Firewall (WAF)</h2>
<p>Protect applications from:</p>
<ul>
<li><p>SQL Injection</p>
</li>
<li><p>Cross-Site Scripting (XSS)</p>
</li>
<li><p>Malicious Bots</p>
</li>
<li><p>OWASP Top 10 attacks</p>
</li>
</ul>
<p>Architecture:</p>
<pre><code class="language-text">Internet
    │
    ▼
Azure Front Door + WAF
    │
    ▼
App Service
</code></pre>
<hr />
<h2>Path-Based Routing</h2>
<p>Useful for microservices.</p>
<p>Example:</p>
<pre><code class="language-text">/api/users/*      → User Service
/api/orders/*     → Order Service
/api/payments/*   → Payment Service
</code></pre>
<hr />
<h2>Health Probes</h2>
<p>Azure Front Door continuously checks backend health.</p>
<p>Example:</p>
<pre><code class="language-text">GET /health
</code></pre>
<p>Benefits:</p>
<ul>
<li><p>Automatic failover</p>
</li>
<li><p>Faster recovery</p>
</li>
<li><p>Improved reliability</p>
</li>
</ul>
<hr />
<h2>Caching</h2>
<p>Ideal for:</p>
<pre><code class="language-text">Images
CSS
JavaScript
Static Content
</code></pre>
<p>Avoid caching:</p>
<pre><code class="language-text">JWT-secured APIs
Authenticated endpoints
User-specific data
</code></pre>
<hr />
<h2>Private Link Integration</h2>
<p>Available in Azure Front Door Premium.</p>
<p>Architecture:</p>
<pre><code class="language-text">Internet
    │
    ▼
Azure Front Door
    │
    ▼
Private Link
    │
    ▼
App Service
</code></pre>
<p>Benefits:</p>
<ul>
<li><p>Backend not publicly exposed</p>
</li>
<li><p>Improved security posture</p>
</li>
</ul>
<hr />
<h1>Security Best Practices</h1>
<h2>Restrict Direct Backend Access</h2>
<p>Validate requests originate from Front Door.</p>
<p>Example:</p>
<pre><code class="language-csharp">var fdid = Request.Headers["X-Azure-FDID"];
</code></pre>
<p>Useful headers:</p>
<pre><code class="language-http">X-Azure-FDID
X-Forwarded-Host
X-Azure-ClientIP
</code></pre>
<hr />
<h2>Enforce HTTPS Everywhere</h2>
<p>Always use:</p>
<pre><code class="language-text">https://
</code></pre>
<p>Avoid:</p>
<pre><code class="language-text">http://
</code></pre>
<p>for production APIs.</p>
<hr />
<h2>Secure APIs Using JWT</h2>
<p>Example:</p>
<pre><code class="language-csharp">[Authorize]
[HttpGet("expense")]
public async Task&lt;IActionResult&gt; GetExpenses()
{
    ...
}
</code></pre>
<hr />
<h2>Enable Application Insights</h2>
<p>Monitor:</p>
<ul>
<li><p>Failures</p>
</li>
<li><p>Dependency calls</p>
</li>
<li><p>Exceptions</p>
</li>
<li><p>Performance</p>
</li>
</ul>
<hr />
<h1>Troubleshooting Guide</h1>
<h2>Scenario 1: 503 or 504 Errors</h2>
<p>Symptoms:</p>
<pre><code class="language-html">504 Gateway Timeout
</code></pre>
<h3>Check Origin Health</h3>
<pre><code class="language-text">Azure Front Door
    └─ Origin Group
          └─ Health Status
</code></pre>
<hr />
<h3>Test Origin Directly</h3>
<p>Test:</p>
<pre><code class="language-text">https://myapp.azurewebsites.net/api/expense
</code></pre>
<p>If origin fails:</p>
<pre><code class="language-text">Application issue
</code></pre>
<p>If origin succeeds:</p>
<pre><code class="language-text">Front Door configuration issue
</code></pre>
<hr />
<h2>Scenario 2: Route Misconfiguration</h2>
<p>Example:</p>
<pre><code class="language-text">Pattern = /api/auth/*
</code></pre>
<p>Works:</p>
<pre><code class="language-text">/api/auth/login
</code></pre>
<p>Fails:</p>
<pre><code class="language-text">/api/expense
</code></pre>
<p>Recommended:</p>
<pre><code class="language-text">Pattern = /*
</code></pre>
<hr />
<h2>Scenario 3: Authentication Failures (401)</h2>
<p>Symptoms:</p>
<pre><code class="language-http">401 Unauthorized
</code></pre>
<p>Investigate:</p>
<pre><code class="language-csharp">OnAuthenticationFailed
OnTokenValidated
OnChallenge
</code></pre>
<p>Enable detailed logging.</p>
<hr />
<h2>Scenario 4: Verify Request Came Through Front Door</h2>
<p>Check headers:</p>
<pre><code class="language-http">X-Azure-FDID
</code></pre>
<p>Example:</p>
<pre><code class="language-text">X-Azure-FDID: fbadd70b-8340-48a6-a0c2-78830a17bdcf
</code></pre>
<p>Additional useful headers:</p>
<pre><code class="language-http">X-Forwarded-Host
X-Original-URL
X-Azure-ClientIP
</code></pre>
<p>Example:</p>
<pre><code class="language-text">X-Forwarded-Host: myapp.azurefd.net
X-Original-URL: /api/expense
</code></pre>
<hr />
<h2>Scenario 5: Authorization Header Issues</h2>
<p>Verify:</p>
<pre><code class="language-csharp">Request.Headers["Authorization"]
</code></pre>
<p>Expected:</p>
<pre><code class="language-text">Authorization: Bearer eyJ...
</code></pre>
<p>Missing authorization header typically causes:</p>
<pre><code class="language-http">401 Unauthorized
</code></pre>
<hr />
<h2>Scenario 6: HTTP to HTTPS Redirect and JWT Authentication</h2>
<h3>Real-World Case Study</h3>
<p>A Front Door route was configured with:</p>
<pre><code class="language-text">Redirect all traffic to HTTPS = Enabled
</code></pre>
<p>Request:</p>
<pre><code class="language-text">http://myapp.azurefd.net/api/expense
</code></pre>
<p>Flow:</p>
<pre><code class="language-text">Client
   │
   ▼
HTTP Request + JWT
   │
   ▼
301 Redirect
   │
   ▼
HTTPS Request
</code></pre>
<p>Some HTTP clients may drop the Authorization header after following the redirect.</p>
<p>Result:</p>
<pre><code class="language-http">401 Unauthorized
</code></pre>
<p>while the application itself remains healthy.</p>
<h3>Symptoms</h3>
<p>Observed behavior:</p>
<pre><code class="language-text">myapp.azurefd.net/api/expense
</code></pre>
<p>Failed</p>
<p>while</p>
<pre><code class="language-text">https://myapp.azurefd.net/api/expense
</code></pre>
<p>Worked successfully.</p>
<h3>Root Cause</h3>
<p>The request was initially sent over HTTP and redirected to HTTPS.</p>
<p>The Authorization header was not preserved during the redirect flow.</p>
<h3>Resolution</h3>
<p>Always invoke APIs directly using HTTPS:</p>
<pre><code class="language-text">https://myapp.azurefd.net/api/expense
</code></pre>
<p>Avoid:</p>
<pre><code class="language-text">http://myapp.azurefd.net/api/expense
</code></pre>
<hr />
<h1>Useful Diagnostic Headers</h1>
<table>
<thead>
<tr>
<th>Header</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>X-Azure-FDID</td>
<td>Identifies Azure Front Door request</td>
</tr>
<tr>
<td>X-Forwarded-Host</td>
<td>Original requested host</td>
</tr>
<tr>
<td>X-Azure-ClientIP</td>
<td>Client IP address</td>
</tr>
<tr>
<td>X-Original-URL</td>
<td>Original request path</td>
</tr>
<tr>
<td>Authorization</td>
<td>JWT token passed to backend</td>
</tr>
</tbody></table>
<hr />
<h1>Application Insights Checklist</h1>
<p>When troubleshooting:</p>
<p>✅ Check Request Failures</p>
<p>✅ Check Exceptions</p>
<p>✅ Verify Response Codes</p>
<p>✅ Compare Front Door vs Direct Origin Requests</p>
<p>✅ Validate Authorization Header</p>
<p>✅ Review Authentication Events</p>
<p>✅ Inspect Dependency Calls</p>
<hr />
<h1>Key Takeaways</h1>
<ul>
<li><p>Azure Front Door provides global routing, security, and performance improvements.</p>
</li>
<li><p>A simple route configuration (<code>/*</code>) is sufficient for many App Service applications.</p>
</li>
<li><p>Always validate both Front Door and direct App Service endpoints during troubleshooting.</p>
</li>
<li><p>Application Insights should be the first place to inspect failures.</p>
</li>
<li><p>Use <code>X-Azure-FDID</code> to confirm requests originate from Azure Front Door.</p>
</li>
<li><p>Most authentication issues are caused by missing or invalid Authorization headers.</p>
</li>
<li><p>HTTP-to-HTTPS redirects can lead to JWT authentication failures when clients do not preserve Authorization headers.</p>
</li>
<li><p>Always use HTTPS URLs directly when testing secured APIs.</p>
</li>
<li><p>Understanding request flow through Front Door dramatically simplifies troubleshooting.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Comprehensive Guide to Understanding CORS]]></title><description><![CDATA[This document details why Cross-Origin Resource Sharing (CORS) acts as a browser-level sandbox and demonstrates how data flows between clients and servers during CORS restrictions.

1. Why Postman Wor]]></description><link>https://thoughtcopy.com/comprehensive-guide-to-understanding-cors</link><guid isPermaLink="true">https://thoughtcopy.com/comprehensive-guide-to-understanding-cors</guid><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Tue, 18 Aug 2026 08:47:47 GMT</pubDate><content:encoded><![CDATA[<p>This document details why Cross-Origin Resource Sharing (CORS) acts as a browser-level sandbox and demonstrates how data flows between clients and servers during CORS restrictions.</p>
<hr />
<h2>1. Why Postman Works vs. Why Browsers Block Requests</h2>
<p>The fundamental difference lies in <strong>where</strong> the security check happens. CORS is not a server-side firewall; it is a <strong>browser-enforced security contract</strong>.</p>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Web Browser (Chrome, Safari, Firefox)</th>
<th>Postman Client / Backend Server</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Enforces CORS?</strong></td>
<td><strong>Yes</strong></td>
<td><strong>No</strong></td>
</tr>
<tr>
<td><strong>Sandbox Environment?</strong></td>
<td>Yes (Isolates origins to protect user sessions)</td>
<td>No (Direct terminal/application environment)</td>
</tr>
<tr>
<td><strong>Sends</strong> <code>Origin</code> <strong>Header?</strong></td>
<td>Automatically attached by the browser engine</td>
<td>None (Unless manually configured by user)</td>
</tr>
<tr>
<td><strong>Action on Mismatch</strong></td>
<td>Blocks code from reading the response</td>
<td>Delivers full payload directly to interface</td>
</tr>
</tbody></table>
<hr />
<h2>2. Request-Response Cycle for Simple Requests (e.g., GET)</h2>
<p>For simple requests, <strong>the server always processes your data</strong>. The browser blocks the incoming response <em>after</em> it leaves the server if headers are missing.</p>
<pre><code class="language-text">+-------------------+           1. GET Request           +-------------------+

|    WEB BROWSER    | ---------------------------------&gt; |    API SERVER     |
| (domain-a.com)    |                                    |  (://domain-b.com) |
+-------------------+                                    +-------------------+
          ^                                                        |

          |                                                        | 2. Processes logic
          |                                                        |    Saves to database
          |                                                        |    Generates response
          |               3. Response Payload                      v
          +------------------------------------------------- [ Sends Data ]
          |
  [ Browser Check ]
  Does Response Header contain: 
  'Access-Control-Allow-Origin: domain-a.com'?
          |
          +---&gt; NO  ==&gt; [ CORS Error ] Response blocked from JavaScript.
          |
          +---&gt; YES ==&gt; Data successfully passed to frontend app.
</code></pre>
<h3>Critical Side Effect</h3>
<p>Because the server executes the action <strong>before</strong> the browser evaluates the security header, data modifications (like database updates) <strong>will still occur</strong> on the backend. Only the client application is prevented from reading the confirmation or result.</p>
<hr />
<h2>3. Request-Response Cycle for Complex Requests (The Preflight Check)</h2>
<p>For non-simple requests (like sending JSON payloads via <code>POST</code>, <code>PUT</code>, or <code>DELETE</code>), the browser performs a safety preflight handshake using the HTTP <code>OPTIONS</code> method <strong>before</strong> executing your actual logic.</p>
<h3>Scenario A: Failed Preflight (Server Denies Cross-Origin Access)</h3>
<pre><code class="language-text">+-------------------+          1. OPTIONS Request         +-------------------+

|    WEB BROWSER    | ---------------------------------&gt; |    API SERVER     |
| (domain-a.com)    |     "Are you open to domain-a?"    |  (://domain-b.com) |
+-------------------+                                    +-------------------+
          ^                                                        |

          |                                                        | 2. Evaluates Origin
          |               3. Refusal Response                      v
          +------------------------------------------------- [ Sends 400/403 ]
          |
  [ Browser Check ]
  Preflight Refused!
          |
          +---&gt; [ CRITICAL STOP ] 
                The browser cancels the workflow.
                The actual POST/PUT request is NEVER sent.
                Server data remains completely untouched.
</code></pre>
<h3>Scenario B: Successful Preflight &amp; Actual Request Lifecycle</h3>
<pre><code class="language-text">+-------------------+          1. OPTIONS Request         +-------------------+

|    WEB BROWSER    | ---------------------------------&gt; |    API SERVER     |
| (domain-a.com)    |     "Are you open to domain-a?"    |  (://domain-b.com) |
+-------------------+                                    +-------------------+
          ^                                                        |
          |               2. Access Allowed Response               v
          +------------------------------------------------- [ Sends 200 OK ]
          |                (Access-Control-Allow-Origin)
  [ Browser Check ]
  Preflight Passed!
          |
          |                    3. Actual Request                   +-------------------+
          +----------------- (POST / PUT / DELETE) --------------&gt; |    API SERVER     |

          |                                                        |  Processes logic  |
          |                                                        |  Modifies data    |
          |                                                        +-------------------+

          |                                                                  |
          |                    4. Actual Response                            |
          +------------------------------------------------------------------+
</code></pre>
<hr />
<h2>4. Summary of Key Takeaways</h2>
<ol>
<li><p><strong>Postman succeeds</strong> because it acts as a direct backend client; it does not implement or respect browser origin restrictions.</p>
</li>
<li><p><strong>Servers always process simple cross-origin requests</strong>, even if the browser throws a CORS error right afterward.</p>
</li>
<li><p><strong>Preflight checks protect your infrastructure</strong> by catching illegal cross-origin configurations before state-changing mutations (<code>POST</code>/<code>PUT</code>/<code>DELETE</code>) hit your core business logic.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[ASP.NET Core Configuration Guide]]></title><description><![CDATA[ASP.NET Core Configuration Guide
Overview
ASP.NET Core uses a layered configuration system where later sources override earlier ones for the same key.

Configuration Priority Order



Priority
Source
]]></description><link>https://thoughtcopy.com/asp-net-core-configuration-guide</link><guid isPermaLink="true">https://thoughtcopy.com/asp-net-core-configuration-guide</guid><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Wed, 17 Jun 2026 06:55:00 GMT</pubDate><content:encoded><![CDATA[<h1>ASP.NET Core Configuration Guide</h1>
<h2>Overview</h2>
<p>ASP.NET Core uses a <strong>layered configuration system</strong> where later sources override earlier ones for the same key.</p>
<hr />
<h2>Configuration Priority Order</h2>
<table>
<thead>
<tr>
<th>Priority</th>
<th>Source</th>
<th>When Loaded</th>
</tr>
</thead>
<tbody><tr>
<td>1 (lowest)</td>
<td><code>appsettings.json</code></td>
<td>Always</td>
</tr>
<tr>
<td>2</td>
<td><code>appsettings.{Environment}.json</code></td>
<td>Always</td>
</tr>
<tr>
<td>3</td>
<td>User Secrets</td>
<td>Development only</td>
</tr>
<tr>
<td>4</td>
<td>Environment variables</td>
<td>Always</td>
</tr>
<tr>
<td>5</td>
<td>Command-line arguments</td>
<td>Always</td>
</tr>
<tr>
<td>6 (highest)</td>
<td>Azure Key Vault (if registered)</td>
<td>When explicitly added in code</td>
</tr>
</tbody></table>
<blockquote>
<p><strong>Rule</strong>: Later sources override earlier ones for the same key.</p>
</blockquote>
<hr />
<h2>Environment Detection</h2>
<p>ASP.NET Core determines the current environment from the <code>ASPNETCORE_ENVIRONMENT</code> variable.</p>
<p>Common values:</p>
<ul>
<li><p><code>Development</code></p>
</li>
<li><p><code>Staging</code></p>
</li>
<li><p><code>Production</code></p>
</li>
</ul>
<p>This is typically set in <code>launchSettings.json</code> for local development:</p>
<pre><code class="language-json">{
    "profiles": {
        "Dev": {
            "commandName": "Project",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "applicationUrl": "http://localhost:5056"
        },
        "Production": {
            "commandName": "Project",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Production"
            },
            "applicationUrl": "http://localhost:5055"
        }
    }
}
</code></pre>
<h3>Checking environment in code</h3>
<pre><code class="language-csharp">// During host building 
if (builder.Environment.IsDevelopment()) 
{ 
  // development-only setup 
}
// After app is built 
if (app.Environment.IsProduction()) 
{ 
   // production-only setup 
}
</code></pre>
<hr />
<h2>1. appsettings.json Files</h2>
<h3>Base configuration (always loaded)</h3>
<h3>appsettings.json</h3>
<pre><code class="language-json">{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*"
}
</code></pre>
<h3>Environment-specific overrides</h3>
<h3>appsettings.Development.json</h3>
<pre><code class="language-json">{
    "Logging": {
        "LogLevel": {
            "Default": "Debug"
        }
    },
    "ConnectionStrings": {
        "MyDiaryDb": "Server=127.0.0.1;Port=5432;Database=MyDiaryDb_Dev;UserId=postgres;Password=12345;"
    }
}
</code></pre>
<h3>appsettings.Production.json</h3>
<pre><code class="language-json">{
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        }
    }
}
</code></pre>
<h3>How it merges</h3>
<p>When running in Development:</p>
<p>appsettings.json → LogLevel: Default = "Information" appsettings.Development.json → LogLevel:Default = "Debug" ← wins</p>
<p>The environment-specific file <strong>overrides</strong> matching keys, but non-overlapping keys from <code>appsettings.json</code> are still available.</p>
<hr />
<h2>2. User Secrets</h2>
<h3>What are they?</h3>
<p>A <strong>development-only</strong> mechanism for storing sensitive config values (passwords, API keys) <strong>outside</strong> the project directory so they are never committed to source control.</p>
<h3>Where are they stored?</h3>
<table>
<thead>
<tr>
<th>OS</th>
<th>Path</th>
</tr>
</thead>
<tbody><tr>
<td>Windows</td>
<td><code>%APPDATA%\Microsoft\UserSecrets\&lt;UserSecretsId&gt;\secrets.json</code></td>
</tr>
<tr>
<td>Linux/Mac</td>
<td><code>~/.microsoft/usersecrets/&lt;UserSecretsId&gt;/secrets.json</code></td>
</tr>
</tbody></table>
<h3>Setup</h3>
<h4>1. Initialize (one-time per project)</h4>
<pre><code class="language-powershell">dotnet user-secrets init
</code></pre>
<p>This adds a <code>&lt;UserSecretsId&gt;</code> to your <code>.csproj</code>:</p>
<pre><code class="language-xml">&lt;PropertyGroup&gt;
	&lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
	&lt;UserSecretsId&gt;a1b2c3d4-e5f6-7890-abcd-ef1234567890&lt;/UserSecretsId&gt;
&lt;/PropertyGroup&gt;
</code></pre>
<h4>2. Set secrets</h4>
<blockquote>
<p>dotnet user-secrets set "ConnectionStrings:MyDiaryDb" "Server=127.0.0.1;Port=5432;Database=MyDiaryDb_Dev;User Id=postgres;Password=SecretPassword;"</p>
</blockquote>
<h4>3. List secrets</h4>
<pre><code class="language-powershell">dotnet user-secrets list
</code></pre>
<h4>4. Remove a secret</h4>
<pre><code class="language-powershell">dotnet user-secrets remove "ConnectionStrings:MyDiaryDb"
</code></pre>
<h4>5. Clear all secrets</h4>
<pre><code class="language-powershell">dotnet user-secrets clear
</code></pre>
<h3>How they are loaded</h3>
<p>You do <strong>not</strong> need to register them manually. <code>WebApplication.CreateBuilder(args)</code> automatically loads User Secrets when <code>ASPNETCORE_ENVIRONMENT=Development</code>:</p>
<blockquote>
<p>This happens internally — you don't write this yourself:</p>
</blockquote>
<pre><code class="language-csharp">if (builder.Environment.IsDevelopment()) 
{ 
  builder.Configuration.AddUserSecrets(); 
}
</code></pre>
<h3>Priority</h3>
<p>User Secrets override <code>appsettings.Development.json</code> for the same key:</p>
<blockquote>
<p>appsettings.json → ConnectionStrings:MyDiaryDb = (not set) appsettings.Development.json → ConnectionStrings:MyDiaryDb = "local-dev-string" User Secrets → ConnectionStrings:MyDiaryDb = "secret-string" ← wins</p>
</blockquote>
<h3>Key characteristics</h3>
<table>
<thead>
<tr>
<th>Question</th>
<th>Answer</th>
</tr>
</thead>
<tbody><tr>
<td>In source control?</td>
<td>No</td>
</tr>
<tr>
<td>Works in Production?</td>
<td>No, Development only</td>
</tr>
<tr>
<td>Overrides appsettings.Development.json?</td>
<td>Yes</td>
</tr>
<tr>
<td>Needs manual registration?</td>
<td>No, automatic in Development</td>
</tr>
<tr>
<td>Shared across team?</td>
<td>No, per-developer</td>
</tr>
</tbody></table>
<h3>When to use</h3>
<ul>
<li><p>Local database passwords</p>
</li>
<li><p>API keys for third-party services during development</p>
</li>
<li><p>Any secret you don't want in Git</p>
</li>
</ul>
<hr />
<h2>3. Environment Variables</h2>
<h3>How they work</h3>
<p>Environment variables override all file-based config. Use <code>__</code> (double underscore) as a section separator:</p>
<h4>Linux/Mac</h4>
<pre><code class="language-powershell">export ConnectionStrings\_\_MyDiaryDb="Server=prod-server;..."
</code></pre>
<h4>Windows (PowerShell)</h4>
<pre><code class="language-powershell">$env:ConnectionStrings\_\_MyDiaryDb = "Server=prod-server;..."
</code></pre>
<h3>In code</h3>
<pre><code class="language-csharp">// Read normally — the framework resolves the source automatically var connectionString = builder.Configuration.GetConnectionString("MyDiaryDb");
</code></pre>
<h3>Priority</h3>
<p>Environment variables override User Secrets and appsettings files:</p>
<blockquote>
<p>appsettings.Development.json → ConnectionStrings:MyDiaryDb = "dev-string" User Secrets → ConnectionStrings:MyDiaryDb = "secret-string" Environment Variable → ConnectionStrings:MyDiaryDb = "env-string" ← wins</p>
</blockquote>
<h3>Common use cases</h3>
<ul>
<li><p>CI/CD pipelines</p>
</li>
<li><p>Docker containers</p>
</li>
<li><p>Azure App Service (Application Settings)</p>
</li>
</ul>
<hr />
<h2>4. Azure Key Vault</h2>
<h3>What it does</h3>
<p>Stores secrets centrally in Azure. Your app fetches them at startup and they become part of the configuration system.</p>
<h3>Setup</h3>
<h4>Install package</h4>
<pre><code class="language-powershell">dotnet add package Azure.Identity 
dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
</code></pre>
<h4>Register in Program.cs (conditionally)</h4>
<pre><code class="language-csharp">using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
// Only connect to Key Vault in non-Development environments 
if (!builder.Environment.IsDevelopment()) 
{ 
  var keyVaultUrl = new Uri("https://your-vault-name.vault.azure.net/"); 
  builder.Configuration.AddAzureKeyVault(keyVaultUrl, new DefaultAzureCredential()); 
}
// Connection string is resolved from whatever source is available 
builder.Services.AddDbContext&lt;DataContext&gt;(options =&gt; { 
  options.UseNpgsql(builder.Configuration.GetConnectionString("MyDiaryDb")); 
});
</code></pre>
<h3>Secret naming in Key Vault</h3>
<p>Use <code>--</code> as separator (Key Vault doesn't allow <code>:</code>):</p>
<table>
<thead>
<tr>
<th>Key Vault Secret Name</th>
<th>Maps to Configuration Key</th>
</tr>
</thead>
<tbody><tr>
<td><code>ConnectionStrings--MyDiaryDb</code></td>
<td><code>ConnectionStrings:MyDiaryDb</code></td>
</tr>
<tr>
<td><code>Jwt--Key</code></td>
<td><code>Jwt:Key</code></td>
</tr>
<tr>
<td><code>Jwt--Issuer</code></td>
<td><code>Jwt:Issuer</code></td>
</tr>
</tbody></table>
<h3>Priority</h3>
<p>Key Vault is the <strong>highest priority</strong> when registered (added last):</p>
<blockquote>
<p>appsettings.json → ConnectionStrings:MyDiaryDb = (not set) appsettings.Production.json → ConnectionStrings:MyDiaryDb = (not set) Environment Variables → ConnectionStrings:MyDiaryDb = "env-string" Azure Key Vault → ConnectionStrings:MyDiaryDb = "vault-string" ← wins</p>
</blockquote>
<h3>Authentication methods (DefaultAzureCredential)</h3>
<p><code>DefaultAzureCredential</code> tries these in order:</p>
<ol>
<li><p>Environment variables (<code>AZURE_CLIENT_ID</code>, <code>AZURE_TENANT_ID</code>, <code>AZURE_CLIENT_SECRET</code>)</p>
</li>
<li><p>Managed Identity (Azure App Service, VM, Container Apps)</p>
</li>
<li><p>Visual Studio credentials</p>
</li>
<li><p>Azure CLI (<code>az login</code>)</p>
</li>
<li><p>Azure PowerShell</p>
</li>
</ol>
<h3>Why wrap in environment check</h3>
<pre><code class="language-csharp">// BAD — tries to connect to Azure even in Development 
var keyVaultUrl = new Uri("https://your-vault.vault.azure.net/"); 
builder.Configuration.AddAzureKeyVault(keyVaultUrl, new DefaultAzureCredential());

// GOOD — only connects in Production 
if (!builder.Environment.IsDevelopment()) 
{ 
  var keyVaultUrl = new Uri("https://your-vault.vault.azure.net/"); 
  builder.Configuration.AddAzureKeyVault(keyVaultUrl, new DefaultAzureCredential()); 
}
</code></pre>
<p>Without the check, <code>AddAzureKeyVault</code> attempts to authenticate to Azure <strong>immediately</strong> at startup. If credentials are not available locally, the app crashes or hangs before it ever reads your local config files.</p>
<hr />
<h2>5. Command-Line Arguments</h2>
<p>Highest priority among built-in sources (before Key Vault):</p>
<blockquote>
<p>dotnet run --ConnectionStrings:MyDiaryDb="Server=override;..."</p>
</blockquote>
<p>Useful for one-off overrides during testing.</p>
<hr />
<h2>Complete Example: Program.cs</h2>
<pre><code class="language-csharp">using Azure.Identity; using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Configuration is already loaded in this order: 
  // 1. appsettings.json 
  // 2. appsettings.{Environment}.json 
  // 3. User Secrets (Development only, automatic) 
  // 4. Environment variables 
  // 5. Command-line args
  // 6. Azure Key Vault (Production only, manual) 
  if (!builder.Environment.IsDevelopment()) 
  { 
    var keyVaultUrl = new Uri("https://your-vault.vault.azure.net/"); 
    builder.Configuration.AddAzureKeyVault(keyVaultUrl, new DefaultAzureCredential()); 
  }
// This resolves from whichever source has the highest priority 
  var connectionString = builder.Configuration.GetConnectionString("MyDiaryDb");
  builder.Services.AddDbContext&lt;DataContext&gt;(options =&gt; { options.UseNpgsql(connectionString); });
  var app = builder.Build(); app.Run();
</code></pre>
<hr />
<h2>Summary: Which source to use when</h2>
<table>
<thead>
<tr>
<th>Environment</th>
<th>Recommended secret source</th>
</tr>
</thead>
<tbody><tr>
<td>Local Development</td>
<td>User Secrets</td>
</tr>
<tr>
<td>CI/CD Pipeline</td>
<td>Environment variables</td>
</tr>
<tr>
<td>Azure App Service</td>
<td>Azure Key Vault or App Settings</td>
</tr>
<tr>
<td>Docker/Container</td>
<td>Environment variables</td>
</tr>
</tbody></table>
<hr />
<h2>Quick Reference: Common Commands</h2>
<h5>Initialize user secrets</h5>
<blockquote>
<p>dotnet user-secrets init</p>
</blockquote>
<h5>Set a secret</h5>
<blockquote>
<p>dotnet user-secrets set "ConnectionStrings:MyDiaryDb" "your-connection-string"</p>
</blockquote>
<h5>List all secrets</h5>
<blockquote>
<p>dotnet user-secrets list</p>
</blockquote>
<h5>Clear all secrets</h5>
<blockquote>
<p>dotnet user-secrets clear</p>
</blockquote>
<h5>Azure CLI login (for local Key Vault access)</h5>
<blockquote>
<p>az login</p>
</blockquote>
<hr />
<h2>Common Mistakes</h2>
<h3>1. Key Vault without environment check</h3>
<pre><code class="language-csharp">// Crashes locally if no Azure credentials 
  builder.Configuration.AddAzureKeyVault(keyVaultUrl, new DefaultAzureCredential());
</code></pre>
<h3>2. Secrets in appsettings.json committed to Git</h3>
<pre><code class="language-csharp">// DON'T — this goes into source control 
{
    "ConnectionStrings": {
        "MyDiaryDb": "Server=prod;Password=secret123;"
    }
}
</code></pre>
<h3>3. Using Production profile for local development</h3>
<pre><code class="language-csharp">// Ensure your local profile uses Development 
{
    "Dev": {
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    }
}
</code></pre>
<h3>4. Assuming User Secrets work in Production</h3>
<p>They don't. User Secrets are <strong>Development-only</strong> by design.</p>
<hr />
<h2>References</h2>
<ul>
<li><p><a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/">ASP.NET Core Configuration</a></p>
</li>
<li><p><a href="https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets">Safe storage of secrets in Development</a></p>
</li>
<li><p><a href="https://learn.microsoft.com/en-us/aspnet/core/security/key-vault-configuration">Azure Key Vault configuration provider</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to Modernize Legacy Delphi Applications with a Hybrid Approach]]></title><description><![CDATA[Legacy Delphi applications often struggle with outdated UI/UX, performance issues, and monolithic architectures that make refactoring difficult. However, a full rewrite is not always feasible due to time, cost, and the risk of disrupting critical bus...]]></description><link>https://thoughtcopy.com/how-to-modernize-legacy-delphi-applications-with-a-hybrid-approach</link><guid isPermaLink="true">https://thoughtcopy.com/how-to-modernize-legacy-delphi-applications-with-a-hybrid-approach</guid><category><![CDATA[Delphi]]></category><category><![CDATA[legacy-systems]]></category><category><![CDATA[DelphiFMX]]></category><category><![CDATA[delphi developer]]></category><category><![CDATA[Delphi Development Companies]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Mon, 10 Mar 2025 09:41:53 GMT</pubDate><content:encoded><![CDATA[<p>Legacy Delphi applications often struggle with outdated UI/UX, performance issues, and monolithic architectures that make refactoring difficult. However, a full rewrite is not always feasible due to time, cost, and the risk of disrupting critical business functions. A <strong>hybrid modernization approach</strong>, which integrates modern web technologies while retaining core Delphi logic, offers a balanced solution.</p>
<p><strong>Why Hybrid Modernization?</strong></p>
<p>A hybrid approach allows developers to:</p>
<ul>
<li><p><strong>Enhance UI/UX</strong> by embedding modern web components inside Delphi applications.</p>
</li>
<li><p><strong>Improve maintainability</strong> by gradually transitioning to modular architecture.</p>
</li>
<li><p><strong>Extend cross-platform capabilities</strong> without abandoning existing Delphi logic.</p>
</li>
<li><p><strong>Reduce risk and cost</strong> by modernizing in phases instead of a complete rewrite.</p>
</li>
<li><p><strong>Leverage modern security practices</strong> while maintaining compatibility with legacy systems.</p>
</li>
<li><p><strong>Enable cloud or mobile access</strong> by introducing web-based components that extend Delphi functionalities.</p>
</li>
</ul>
<p>I’ve created a video demonstration of the hybrid modernization approach. You can watch it to have a visual feel of hybrid modernization approach.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=kFS2uKGSyAM">https://www.youtube.com/watch?v=kFS2uKGSyAM</a></div>
<p> </p>
<p><strong>Key Components of the Hybrid Approach</strong></p>
<p><strong>1. Embedding Web UI in Delphi Using CEF4Delphi / TEdgeBrowser</strong></p>
<p>To modernize the front end, developers can use the <strong>Chromium Embedded Framework (CEF4Delphi)</strong> to render web-based UI inside the Delphi application:</p>
<ul>
<li><p><strong>Why CEF4Delphi?</strong> It allows embedding Chromium-based browsers within a Delphi form, enabling seamless rendering of modern web applications.</p>
</li>
<li><p><strong>Implementation Steps:</strong></p>
<ol>
<li><p>Install CEF4Delphi and integrate it with the Delphi project.</p>
</li>
<li><p>Load a local or remote React / Angular/ Blazor based web application inside a Delphi form.</p>
</li>
<li><p>Use <strong>JavaScript-to-Delphi Interop</strong> to allow the web UI to trigger Delphi business logic.</p>
</li>
<li><p>Implement message passing to handle data exchange between Delphi and the web UI.</p>
</li>
</ol>
</li>
<li><p><strong>Example Use Case:</strong> Migrating a legacy order management form to a React-based interface while keeping backend logic in Delphi.</p>
</li>
</ul>
<p><strong>2. Exposing Delphi Business Logic via APIs</strong></p>
<p>Instead of tightly coupling the frontend with Delphi logic, expose business functionalities as APIs:</p>
<ul>
<li><p><strong>Why Use APIs?</strong> APIs help in decoupling the UI from business logic, making it easier to switch or upgrade components.</p>
</li>
<li><p><strong>Options for API Development:</strong></p>
<ul>
<li><p><strong>Delphi RAD Server (EMS):</strong> Provides built-in REST API capabilities for Delphi applications.</p>
</li>
<li><p><strong>DelphiMVCFramework:</strong> DelphiMVCFramework (or DMVCFramework) is a powerful and popular framework for building RESTful APIs and web applications using Delphi. It follows the <code>Model-View-Controller (MVC) pattern</code>, providing a structured and scalable approach to developing modern applications.</p>
</li>
<li><p><a target="_blank" href="http://ASP.NET"><strong>ASP.NET</strong></a> <strong>Core Web API:</strong> If the team is comfortable with .NET, it provides a robust alternative.</p>
</li>
<li><p><strong>Node.js or Python Flask/Django:</strong> If real-time communication or data analytics are required.</p>
</li>
</ul>
</li>
<li><p><strong>Implementation Steps:</strong></p>
</li>
<li><ol>
<li><p>Identify business logic functions that need exposure via APIs.</p>
<ol start="2">
<li><p>Develop RESTful services in Delphi RAD Server or <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core.</p>
</li>
<li><p>Secure APIs using JWT, OAuth, or API keys.</p>
</li>
<li><p>Consume these APIs in the React/Angular frontend.</p>
</li>
</ol>
</li>
</ol>
</li>
<li><p><strong>Example Use Case:</strong> Exposing customer data retrieval functions via REST API to a modern web dashboard.</p>
</li>
</ul>
<p><strong>3. Using Web Technologies for New Features</strong></p>
<p>Instead of upgrading the entire UI at once, migrate modules that benefit most from web technologies:</p>
<ul>
<li><p><strong>Modern Dashboards &amp; Reports:</strong> Use web-based data visualization tools like <strong>Chart.js, Recharts, or Power BI Embedded</strong>.</p>
</li>
<li><p><strong>Forms &amp; Data Entry:</strong> Replace complex Delphi forms with responsive <strong>React/Angular-based</strong> input interfaces.</p>
</li>
<li><p><strong>Authentication &amp; User Management:</strong> Implement <strong>OAuth/JWT authentication</strong> via a web-based authentication provider.</p>
</li>
<li><p><strong>Cloud Integrations:</strong> Utilize <strong>Azure Functions, AWS Lambda, or Firebase</strong> for scalable backend processes.</p>
</li>
</ul>
<p><strong>4. Gradual Migration Strategy</strong></p>
<p>The modernization process should be phased to ensure smooth transition:</p>
<ol>
<li><p><strong>Assess the legacy application</strong> to identify outdated UI components and tightly coupled logic.</p>
</li>
<li><p><strong>Prioritize modernization</strong> based on business impact and technical feasibility.</p>
</li>
<li><p><strong>Embed web components</strong> using CEF4Delphi while maintaining core Delphi workflows.</p>
</li>
<li><p><strong>Expose business logic as APIs</strong> to allow seamless data exchange.</p>
</li>
<li><p><strong>Migrate more functionalities incrementally</strong>, reducing dependency on Delphi’s VCL UI.</p>
</li>
</ol>
<p><strong>Challenges and Considerations</strong></p>
<p>While the hybrid approach offers many benefits, there are challenges to be aware of:</p>
<ul>
<li><p><strong>Performance Overhead:</strong> Running web UI inside Delphi may introduce additional resource usage.</p>
</li>
<li><p><strong>Data Synchronization:</strong> Ensuring smooth communication between the Delphi backend and web frontend.</p>
</li>
<li><p><strong>Security Concerns:</strong> Protecting API endpoints and securing inter-process communication.</p>
</li>
<li><p><strong>Long-Term Maintainability:</strong> Planning for gradual migration while avoiding technical debt.</p>
</li>
</ul>
<p><strong>Benefits of the Hybrid Approach</strong></p>
<p>✅ <strong>Lower Risk</strong> – Retain core Delphi logic while upgrading the UI.</p>
<p>✅ <strong>Better User Experience</strong> – Web UI provides modern design and responsiveness. ✅ <strong>Incremental Improvements</strong> – Avoid major disruptions by modernizing step by step.</p>
<p>✅ <strong>Cross-Platform Capabilities</strong> – Web-based UI works on multiple operating systems.</p>
<p>✅ <strong>Future-Proofing</strong> – Set the foundation for a fully modernized system in the long run.</p>
<p>✅ <strong>Enhanced Security</strong> – Implement modern authentication and secure APIs.</p>
<p>✅ <strong>Scalability</strong> – Web components can be extended to mobile and cloud environments.</p>
<p>The hybrid modernization approach provides a practical, phased way to improve legacy Delphi applications without the challenges of a complete rewrite. By embedding modern web UI and exposing business logic via <strong>REST APIs</strong>, organizations can enhance their applications while ensuring long-term maintainability.</p>
]]></content:encoded></item><item><title><![CDATA[Working with EF Core pipeline]]></title><description><![CDATA[Entity Framework Core (EF Core) is a powerful and flexible object-relational mapping (ORM) framework for .NET applications, enabling developers to work with relational databases using strongly-typed .NET objects. It simplifies data access by abstract...]]></description><link>https://thoughtcopy.com/working-with-ef-core-pipeline</link><guid isPermaLink="true">https://thoughtcopy.com/working-with-ef-core-pipeline</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[ASP.NET]]></category><category><![CDATA[aspnet developers]]></category><category><![CDATA[Aspnetcore]]></category><category><![CDATA[entity framework]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Tue, 07 May 2024 06:15:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715062283745/7bffd766-e275-420f-95df-f1c41e2fa8b1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Entity Framework Core (EF Core) is a powerful and flexible object-relational mapping (ORM) framework for .NET applications, enabling developers to work with relational databases using strongly-typed .NET objects. It simplifies data access by abstracting the database interactions, allowing developers to focus more on the application's business logic.</p>
<p>One of the key features of EF Core is its extensibility through the EF Core pipeline. The pipeline represents the sequence of operations that occur when EF Core interacts with the database. Developers can tap into this pipeline to customize or extend the behavior of EF Core to suit their application's specific requirements.</p>
<p>Tapping into the EF Core pipeline allows developers to:</p>
<ul>
<li><p>Intercept database operations: By intercepting operations such as query execution, saving changes, or database schema creation, developers can add custom logic, logging, or validation.</p>
</li>
<li><p>Customize query generation: EF Core generates SQL queries based on LINQ expressions or raw SQL statements. Developers can customize this process to optimize queries or handle specific database features.</p>
</li>
<li><p>Implement change tracking: EF Core tracks changes made to entities and detects when to insert, update, or delete records in the database. Developers can customize change tracking behavior for performance or business logic reasons.</p>
</li>
</ul>
<p>There are 3 most common ways to deal with EF Core pipeline:</p>
<ul>
<li><p>Override the <code>SaveChanges</code> method.</p>
</li>
<li><p>Using the saving and tracking event handlers</p>
</li>
<li><p>Interceptors</p>
</li>
</ul>
<p>In the next sections of this article, we will delve into code examples and techniques for tapping into the EF Core pipeline, showcasing the flexibility and power it provides to developers working with database interactions in their .NET applications.</p>
<h3 id="heading-override-the-savechanges-method">Override the <code>SaveChanges</code> method</h3>
<p><code>SaveChanges</code> method saves the changes made to entities to the database. It prepares the SQL queries to insert, update or delete the records. EF Core allows to override this method in <code>DBContext</code> class.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">int</span> <span class="hljs-title">SaveChanges</span>(<span class="hljs-params"></span>)</span> {
    <span class="hljs-keyword">var</span> result = <span class="hljs-keyword">base</span>.SaveChanges();
    <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>Developer could perform various operations in this overridden method. Some examples of such operations are:</p>
<ul>
<li><p>adding additional logging before or after saving the changes.</p>
</li>
<li><p>Modifying the entities in change tracker before saving the data. (updating the shadow properties)</p>
</li>
</ul>
<h3 id="heading-saving-and-tracking-event-handlers">Saving and tracking event handlers</h3>
<p>EF Core provides below events which could be used to perform operations before, after or during EF Core operations:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Event Name</td><td>Description</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td>SavingChanges</td><td>Fired at the beginning of a call to <code>SaveChanges</code></td><td><code>SavingChanges += DataContext_SavingChanges;</code></td></tr>
<tr>
<td>SavedChanges</td><td>Fired at the end of a call to <code>SaveChanges</code></td><td><code>SavedChanges += DataContext_SavedChanges;</code></td></tr>
<tr>
<td>SaveChangesFailed</td><td>Fired when <code>SaveChanges</code> fails with an exception</td><td><code>SaveChangesFailed += DataContext_SaveChangesFailed;</code></td></tr>
<tr>
<td>ChangeTracker.StateChanged</td><td>When entity moves from one tracked state to another</td><td><code>ChangeTracker.StateChanged += ChangeTracker_StateChanged;</code></td></tr>
<tr>
<td>ChangeTracker.StateChanging</td><td>When entity is moving from one state to another</td><td><code>ChangeTracker.StateChanging += ChangeTracker_StateChanging;</code></td></tr>
</tbody>
</table>
</div><h3 id="heading-using-interceptor-to-work-with-ef-core-pipeline">Using Interceptor to work with EF Core pipeline</h3>
<p>Interceptors allows to intercept the EF Core operations; developer could modify or suppress the intercepted operation.</p>
<blockquote>
<p>Interceptors are different from logging and diagnostic as they allow modification or suppression of operation.</p>
</blockquote>
<p>There are three types of interceptors provided by EF Core:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Interceptor</td><td>Database operations intercepted</td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor">IDbCommandInterceptor</a></td><td>Creating commands</td></tr>
<tr>
<td>Executing commands</td><td></td></tr>
<tr>
<td>Command failures</td><td></td></tr>
<tr>
<td>Disposing the command's DbDataReader</td><td></td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbconnectioninterceptor">IDbConnectionInterceptor</a></td><td>Opening and closing connections</td></tr>
<tr>
<td>Connection failures</td><td></td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbtransactioninterceptor">IDbTransactionInterceptor</a></td><td>Creating transactions</td></tr>
<tr>
<td>Using existing transactions</td><td></td></tr>
<tr>
<td>Committing transactions</td><td></td></tr>
<tr>
<td>Rolling back transactions</td><td></td></tr>
<tr>
<td>Creating and using savepoints</td><td></td></tr>
<tr>
<td>Transaction failures</td></tr>
</tbody>
</table>
</div><p>Table source: <a target="_blank" href="https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors">Interceptors - EF Core | Microsoft Learn</a></p>
<p>That's it for now, in this article we have learnt about tapping into EF Core pipeline where developer could perform additional operations before or after execution of operation. Let me know your feedback in comments.</p>
]]></content:encoded></item><item><title><![CDATA[Options pattern in ASP.NET Core:  Advance scenario]]></title><description><![CDATA[In this article we are going to cover some advance scenarios where Options pattern is very useful.
We have covered the basic understanding of Options pattern into Options pattern in ASP.NET Core: Introduction article. Please go through it if not fami...]]></description><link>https://thoughtcopy.com/options-pattern-in-aspnet-core-advance-scenario</link><guid isPermaLink="true">https://thoughtcopy.com/options-pattern-in-aspnet-core-advance-scenario</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[ASP.NET]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[dotnetcore]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[learning]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Sat, 27 Apr 2024 12:54:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714222208500/f71a87ec-a0e9-4ad4-87a7-9c69b3856a10.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we are going to cover some advance scenarios where Options pattern is very useful.</p>
<p>We have covered the basic understanding of Options pattern into <a target="_blank" href="https://thoughtcopy.com/options-pattern-in-aspnet-core-introduction">Options pattern in ASP.NET Core: Introduction</a> article. Please go through it if not familiar with it.</p>
<p>We will cover below scenarios which are handled using Options pattern:</p>
<ul>
<li><p>Validation of configuration settings using data annotation.</p>
</li>
<li><p>Validation of configuration settings using custom validation logic.</p>
</li>
<li><p>Validation of configuration settings during application startup.</p>
</li>
<li><p>Handling command line arguments or environment variables using options pattern.</p>
</li>
<li><p>Monitoring the changes of configuration settings.</p>
</li>
</ul>
<p>Let's dive directly into code to understand all how Options pattern is used to handle all these scenarios.</p>
<p>GitHub repo link for the code sample <a target="_blank" href="https://github.com/dkj468/OptionsPatternDemo">https://github.com/dkj468/OptionsPatternDemo</a></p>
<h3 id="heading-validation-of-configuration-settings-using-data-annotation">Validation of configuration settings using data annotation</h3>
<p>Options pattern allows to bind the <code>DataAnnotations</code> rules to class which represents the section of application settings. This is powerful mechanism to validate for non empty, range and many more things.</p>
<p>consider the <code>FileOptions</code> class from our first article :</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FileOptions</span> {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> Key = <span class="hljs-string">"file"</span>;

        [<span class="hljs-meta">Required(AllowEmptyStrings =false)</span>]
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> MaxSize { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> FileType { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> CanModify { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        [<span class="hljs-meta">Range(minimum:2, maximum:6)</span>]
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> MaxFileCount { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    }
</code></pre>
<p>We have applied some validation rules to class properties which represents the configuration setting.</p>
<p>Now we need to modify <code>Program.cs</code> file to validate these data annotations.</p>
<pre><code class="lang-csharp">builder.Services
       .AddOptions&lt;FileOptions&gt;().Bind(builder.Configuration.GetSection(<span class="hljs-string">"file"</span>))
       .ValidateDataAnnotations();  <span class="hljs-comment">// validate the annotations</span>
</code></pre>
<p>With above code changes, application is ready to validate annotation rule when user tries to access the configuration settings via Options pattern.</p>
<p>if you just remove the <code>MaxSize</code> property from <code>appsettings.json</code> file and try to access this inside controller then <code>Microsoft.Extensions.Options.OptionsValidationException</code> exception will be thrown with proper message.</p>
<p><code>Microsoft.Extensions.Options.OptionsValidationException: DataAnnotation validation failed for 'FileOptions' members: 'MaxSize' with the error: 'The MaxSize field is required.'.</code></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You could provide custom error message while defining the annotation rules.</div>
</div>

<pre><code class="lang-csharp"> [<span class="hljs-meta">Required(AllowEmptyStrings =false, ErrorMessage =<span class="hljs-meta-string">"MaxSize cannot be empty"</span>)</span>]
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> MaxSize { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
</code></pre>
<h3 id="heading-custom-validation">Custom validation</h3>
<p>You could write custom validation logic to validate configuration settings value.</p>
<pre><code class="lang-csharp">builder.Services
       .AddOptions&lt;FileOptions&gt;().Bind(builder.Configuration.GetSection(<span class="hljs-string">"file"</span>))
       .Validate(fileOptions =&gt; {
           <span class="hljs-keyword">if</span> (<span class="hljs-keyword">string</span>.IsNullOrEmpty(fileOptions.FileType) {
               <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
           }
           <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
       });
</code></pre>
<h3 id="heading-validate-on-application-startup">Validate on application startup</h3>
<pre><code class="lang-csharp">builder.Services
       .AddOptions&lt;FileOptions&gt;().Bind(builder.Configuration.GetSection(<span class="hljs-string">"file"</span>))
       .ValidateDataAnnotations()
       .ValidateOnStart();
</code></pre>
<p>With .NET 8 , you could combine this with <code>AddOptions</code> method.</p>
<pre><code class="lang-csharp">builder.Services
    .AddOptionsWithValidateOnStart&lt;FileOptions&gt;()
    .Bind(builder.Configuration.GetSection(<span class="hljs-string">"file"</span>));
</code></pre>
<h3 id="heading-handling-command-line-arguments-or-environment-variables">Handling command line arguments or environment variables</h3>
<p>To manage command line arguments or environment variables using options pattern, we somehow need a way to use ASP.NET Core dependency injection mechanism to access the required data.</p>
<p>So far we have used <code>AddOptions</code> method to tell ASP.NET Core to bind the C# class with a specific section of the <code>appsettings.json</code> file. So this method only allows us to bind the configurations which are part of <code>appsettings.json</code> file. We need a way to bind the configuration from other sources like command line, environment variables, database, xml or ini files etc.</p>
<p>To achieve this, we will set options pattern using <code>IConfigurationOptions</code> . This is two step process:</p>
<ul>
<li><p>Create a class which implements <code>IConfigureOptions</code> interface, this class will allow us to access the other configuration sources via dependency injection.</p>
</li>
<li><p>Modify <code>Program.cs</code> to use the class created in above step.</p>
</li>
</ul>
<p>let's see this with code:</p>
<p>First, we will modify the FileOptions class to include two new properties: <code>FileMode</code> and <code>Version</code>.</p>
<p>let's create class with implementation of <code>IConfigureOptions</code></p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FileOptionsSetup</span> : <span class="hljs-title">IConfigureOptions</span>&lt;<span class="hljs-title">FileOptions</span>&gt; {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IConfiguration _config;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">FileOptionsSetup</span>(<span class="hljs-params">IConfiguration config</span>)</span> {
            _config = config;
        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Configure</span>(<span class="hljs-params">FileOptions options</span>)</span> {
            _config.GetSection(<span class="hljs-string">"file"</span>).Bind(options);
            <span class="hljs-comment">// bind the environment variable</span>
            options.filemode = Environment.GetEnvironmentVariable(<span class="hljs-string">"filemode"</span>);
            <span class="hljs-comment">// bind the command line argument</span>
            options.version = _config.GetValue&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"version"</span>); 
        }
    }
</code></pre>
<p>In above code, we first bind the <code>appsettings.json</code> section to <code>FileOptions</code> object and then read the configuration from environment variable and command line respectively.</p>
<p>We could extend above code to include configurations from almost any source</p>
<p>Now let's tell our <code>program.cs</code> to use above class for configurations.</p>
<pre><code class="lang-csharp">builder.Services.ConfigureOptions&lt;FileOptionsSetup&gt;();
</code></pre>
<p>With all above code, our code is now powered to handle configuration from sources other than <code>appsettings.json</code></p>
<h3 id="heading-monitoring-the-changes-in-configuration-settings">Monitoring the changes in configuration settings</h3>
<p>Let's recall how our code uses the <code>IOptions</code> interface for injecting the <code>FileOptions</code> class into controller constructor. There are two more interfaces which could be used to inject the options classes vai dependency injection into ASP.NET Core application.</p>
<p>Let's understand more about these in details :</p>
<p><strong>IOptions</strong></p>
<ul>
<li><p>After running the program, <code>IOptions</code> doesn't monitor for changes into application configurations. It always gives the same value.</p>
</li>
<li><p>This works as singleton and can be injected in any service lifetime.</p>
</li>
</ul>
<p><strong>IOptionsSnapshot</strong></p>
<ul>
<li><p>This is useful in scenario where configuration needs to be read for each request - It works as a scoped service.</p>
</li>
<li><p>This can be injected into a scoped or transient service but not in singleton service.</p>
</li>
<li><p><code>appsettings.json</code> is read for each request.</p>
</li>
</ul>
<p><strong>IOptionsMonitor</strong></p>
<ul>
<li><p>This works as singleton and can be injected in any service lifetime.</p>
</li>
<li><p>this interface has an <code>OnChnage</code> method which is triggered if there are changes in <code>appsettings.json</code></p>
<pre><code class="lang-csharp">          <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">FileController</span>(<span class="hljs-params">IConfiguration config, 
                              IOptionsMonitor&lt;FileOptions&gt; optionsMonitor</span>)</span> {
              _config = config;
              _optionsMonitor = optionsMonitor;
              _fileOptions = _optionsMonitor.CurrentValue; <span class="hljs-comment">// notice here</span>
              _optionsMonitor.OnChange(options =&gt; { <span class="hljs-comment">// onchange method</span>
                  _fileOptions = options;
              });
          }
</code></pre>
</li>
</ul>
<hr />
<p>🚀 Use <code>IOptions&lt;T&gt;</code> when you are not expecting changes in <code>appsettings</code> content.</p>
<p>🚀 Use <code>IOptionsSnapshot&lt;T&gt;</code> when values are expected to change but want it to be consistent during a request.</p>
<p>🚀 Use <code>IOptionsMonitor&lt;T&gt;</code> when real time value is expected.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article we have learned about some advance use cases where options pattern is quite useful. All such scenarios are difficult to manage using <code>IConfiguration</code> method.</p>
<p>Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Options pattern in ASP.NET Core: Introduction]]></title><description><![CDATA[In this article we will learn about Options pattern in ASP.NET Core for dealing with application configurations. The Options pattern uses the C# classes to access and manage the configurations thus providing more flexibility and type safe approach to...]]></description><link>https://thoughtcopy.com/options-pattern-in-aspnet-core-introduction</link><guid isPermaLink="true">https://thoughtcopy.com/options-pattern-in-aspnet-core-introduction</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[C#]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Aspnetcore]]></category><category><![CDATA[aspnet developers]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Fri, 19 Apr 2024 12:26:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713529485190/36ff48ac-48da-4395-abb2-b33b438b163e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we will learn about Options pattern in ASP.NET Core for dealing with application configurations. The Options pattern uses the C# classes to access and manage the configurations thus providing more flexibility and type safe approach to manage application configurations.</p>
<p>if you are already familiar with Options pattern and want to understand about some advance scenario handled by this pattern then please refer another article : <a target="_blank" href="https://thoughtcopy.com/options-pattern-in-aspnet-core-advance-scenario">Options pattern in ASP.NET Core: Advance scenario</a></p>
<p>Application's setting or configuration could come from multiple sources:</p>
<ul>
<li><p>JSON files - <code>appsettings.json</code> or any other JSON file.</p>
</li>
<li><p>Environment variables</p>
</li>
<li><p>Command lines arguments.</p>
</li>
<li><p>Other sources like from DB, from xml file, from INI files etc.</p>
</li>
</ul>
<p>Let's dive into code to solidify the understanding.</p>
<p>GitHub repo link for the code sample: <a target="_blank" href="https://github.com/dkj468/OptionsPatternDemo">dkj468/OptionsPatternDemo (</a><a target="_blank" href="http://github.com">github.com</a><a target="_blank" href="https://github.com/dkj468/OptionsPatternDemo">)</a></p>
<p>Let's assume we have some application configurations defined in <code>appsettings.json</code> file:</p>
<pre><code class="lang-json">  <span class="hljs-string">"file"</span>: {
    <span class="hljs-attr">"maxSize"</span>: <span class="hljs-string">"2Mib"</span>,
    <span class="hljs-attr">"fileType"</span>: <span class="hljs-string">"pdf;jpeg;"</span>,
    <span class="hljs-attr">"canModify"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"maxFileCount"</span>:  <span class="hljs-number">5</span>
  }
</code></pre>
<p>Our aim is to read this configuration data and use it throughout the application. There are multiple ways to read this data from <code>appsettings.json</code> in ASP.NET Core applications. Here, we will start with basic way which is to use <code>IConfiguration</code> interface and then will explore the Options pattern to achieve the same thing.</p>
<h3 id="heading-reading-configuration-data-using-iconfiguration">Reading configuration data using IConfiguration</h3>
<p><code>appsettings.json</code> content can be read easily using <code>IConfiguration</code> interface. We simply need to inject an instance of <code>IConfiguration</code> into controller constructor and all the config values are accessible to use.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FileController</span> : <span class="hljs-title">ControllerBase</span> {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IConfiguration _config;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">FileController</span> (<span class="hljs-params">IConfiguration config</span>)</span> {
            _config = config;
        }
        [<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"config/iconfiguration"</span>)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">GetFileConfig_IConfiguration</span>(<span class="hljs-params"></span>)</span> {
            <span class="hljs-keyword">var</span> fileSize = _config.GetValue&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"file:maxSize"</span>);
            <span class="hljs-keyword">var</span> fileType = _config.GetValue&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"file:fileType"</span>);
            <span class="hljs-keyword">var</span> canModify = _config.GetValue&lt;<span class="hljs-keyword">bool</span>&gt;(<span class="hljs-string">"file:canModify"</span>); 
            <span class="hljs-keyword">var</span> maxFileCount = _config.GetValue&lt;<span class="hljs-keyword">int</span>&gt;(<span class="hljs-string">"file:maxFileCount"</span>);
            <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { fileSize = fileSize, fileType = fileType, canModify = canModify, maxFileCount = maxFileCount });
        } 
    }
</code></pre>
<p>Reading config data using <code>IConfiguration</code> is straightforward and doesn't require any rocket science in ASP.NET Core code. However, this approach has some problems such as:</p>
<ul>
<li><p>Security: <code>IConfiguration</code> has access to whole <code>appsettings.json</code> contents thus exposing the other settings as well.</p>
</li>
<li><p>Code maintainability: configuration key must be named and used properly to avoid mistakes.</p>
</li>
<li><p>No validation: There is no mechanism to validate configurations with <code>IConfiguration</code></p>
</li>
<li><p>No type safety: <code>IConfiguration</code> reads configuration values as string and those strings must be parsed manually to appropriate type.</p>
</li>
<li><p>No default value: There is no mechanism to have a default value for a configuration.</p>
</li>
<li><p>No reload on change: sometimes there are requirements to reload the changed configurations. with <code>IConfiguration</code> this can't be achieved.</p>
</li>
</ul>
<p>As explained above, managing configurations using <code>IConfiguration</code> is straightforward but comes with some limitations. Now let's explore Options pattern to overcome all above shortcomings.</p>
<h3 id="heading-reading-configuration-data-using-options-pattern">Reading Configuration data using Options pattern</h3>
<p>There are 3 steps involved in using Options pattern:</p>
<ul>
<li><p>Defining a C# class which represents a mapping of configuration data.</p>
</li>
<li><p>Binding the C# class with intended section of configuration file and registering it with services container</p>
</li>
<li><p>Injecting the <code>IOptions</code> interface via constructor injection to use it.</p>
</li>
</ul>
<p>Let's see this in action using code.</p>
<p>First, we will create a C# class representing the configuration data.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FileOptions</span> {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> Key = <span class="hljs-string">"file"</span>;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> MaxSize { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> FileType { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> CanModify { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> MaxFileCount { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    }
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">1. Property names must be same as configuration key name. 2. Constant Key is the section name in appsettings.json file. This is optional and you could have your section named as class name i.e. 'fileOptions' instead of 'file'.</div>
</div>

<p>Second, we will bind the <code>FileOptions</code> class with <code>file</code> section of the configuration file and will register it with <code>IServiceCollection</code> inside <code>Program.cs</code> file.</p>
<pre><code class="lang-csharp">builder.Services
    .Configure&lt;FileOptions&gt;(builder.Configuration.GetSection(<span class="hljs-string">"file"</span>));
</code></pre>
<p>There is another way to bind the configuration with Options class which is to use <code>AddOptions</code> extension method.</p>
<pre><code class="lang-csharp">builder.Services
       .AddOptions&lt;FileOptions&gt;().Bind(builder.Configuration.GetSection(<span class="hljs-string">"file"</span>));
</code></pre>
<p>The later returns a <code>OptionsBuilder&lt;T&gt;</code> which allows to chain the configuration for advance scenario like handling custom validations, validations during startup of the application etc. We will discuss it further in upcoming article.</p>
<p>Third and final step, we will use this <code>FileOptions</code> options inside a controller to fetch the configuration data.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FileController</span> : <span class="hljs-title">ControllerBase</span> {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IConfiguration _config;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> FileOptions _fileOptions;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">FileController</span>(<span class="hljs-params">IConfiguration config, IOptions&lt;FileOptions&gt; fileOptions</span>)</span> {
            _config = config;
            _fileOptions = fileOptions.Value;
        }
        [<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"config/iconfiguration"</span>)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">GetFileConfig_IConfiguration</span>(<span class="hljs-params"></span>)</span> {
            <span class="hljs-keyword">var</span> fileSize = _config.GetValue&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"file:maxSize"</span>);
            <span class="hljs-keyword">var</span> fileType = _config.GetValue&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"file:fileType"</span>);
            <span class="hljs-keyword">var</span> canModify = _config.GetValue&lt;<span class="hljs-keyword">bool</span>&gt;(<span class="hljs-string">"file:canModify"</span>);
            <span class="hljs-keyword">var</span> maxFileCount = _config.GetValue&lt;<span class="hljs-keyword">int</span>&gt;(<span class="hljs-string">"file:maxFileCount"</span>);             
            <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { fileSize = fileSize, fileType = fileType, canModify = canModify, maxFileCount = maxFileCount });
        }

        <span class="hljs-comment">// get config data using Options Pattern</span>
        [<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"config/option"</span>)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">GetFileConfig_IOptions</span>(<span class="hljs-params"></span>)</span> {
            <span class="hljs-keyword">var</span> fileSize = _fileOptions.MaxSize;
            <span class="hljs-keyword">var</span> fileType = _fileOptions.FileType;
            <span class="hljs-keyword">var</span> canModify = _fileOptions.CanModify;
            <span class="hljs-keyword">var</span> maxFileCount = _fileOptions.MaxFileCount;
            <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { fileSize = fileSize, fileType = fileType, canModify = canModify, maxFileCount = maxFileCount });
        }
    }
</code></pre>
<p>In above code, we have injected <code>IOptions</code> with type <code>FileOptions</code> . Notice that <code>Value</code> property of <code>IOptions</code> interface returns an instance of <code>FileOptions</code></p>
<p>There are some advance scenarios which could be handled easily with Options pattern for example:</p>
<ul>
<li><p>validation of configuration.</p>
</li>
<li><p>validating the configuration values during application start-up.</p>
</li>
<li><p>handling command line arguments or environment variables using Options pattern.</p>
</li>
<li><p>monitoring for changes into configuration data etc.</p>
</li>
</ul>
<p>This article aimed to explore the fundamental of Options pattern. In upcoming articles, we will explore how to handle above mentioned scenarios using this pattern.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this article we have explored how to read application configuration using basic way i.e. using <code>IConfiguration</code> and later learned about Options pattern to achieve the same thing. On the surface, it seems an overkilling to use this pattern for the simple use case, but Options pattern has helped us achieving below things:</p>
<p>💥 type safety and manageable code: no more hard coded strings into code. Easy to change the configuration key names.</p>
<p>💥 Separation of concerns: Bind only related config and hide other details of configuration settings.</p>
<p>That's it for this article, In next article we will explore some advance use cases solved using Options pattern.</p>
<h3 id="heading-references-and-motivation">References and motivation</h3>
<p>👉 <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/core/extensions/options">Options pattern - .NET | Microsoft Learn</a></p>
<p>👉 <a target="_blank" href="https://codewithmukesh.com/blog/options-pattern-in-aspnet-core/">Options Pattern in</a><a target="_blank" href="http://ASP.NET">ASP.NET</a><a target="_blank" href="https://codewithmukesh.com/blog/options-pattern-in-aspnet-core/">Core – Bind &amp; Validate Configurations from appsettings.json - codewithmukesh</a></p>
<p><a target="_blank" href="https://medium.com/checkout-com-techblog/the-options-pattern-simplified-8e0e03b41a71">👉 The Options Pattern Simplified. Easily use your configuration in your… | by Andre Lopes | Checkout.com-techblog | Medium</a></p>
<p>👉 <a target="_blank" href="https://www.milanjovanovic.tech/blog/how-to-use-the-options-pattern-in-asp-net-core-7">How To Use The Options Pattern In ASP.NET Core 7 (milanjovanovic.tech)</a></p>
]]></content:encoded></item><item><title><![CDATA[HttPContextAccessor in ASP.NET Core]]></title><description><![CDATA[While working with ASP.NET Core web applications, developers often need HttpContext to access the properties associated with request and response.
A HttpContext object encapsulates all such properties for example request path, request method, query s...]]></description><link>https://thoughtcopy.com/httpcontextaccessor-in-aspnet-core</link><guid isPermaLink="true">https://thoughtcopy.com/httpcontextaccessor-in-aspnet-core</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[C#]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Mon, 15 Jan 2024 18:17:50 GMT</pubDate><content:encoded><![CDATA[<p>While working with ASP.NET Core web applications, developers often need <code>HttpContext</code> to access the properties associated with request and response.</p>
<p>A <code>HttpContext</code> object encapsulates all such properties for example request path, request method, query string parameters, response status and code, response content type, etc.</p>
<h3 id="heading-why-httpcontextaccessor">Why HttPContextAccessor?</h3>
<p>Accessing <code>HttpContext</code> inside framework-level APIs like controllers, middlewares, Razor pages, and Razor views are fairly simple where an <code>HttpContext</code> object is exposed and can be used directly.</p>
<p>A real-world application consists of more than framework-level APIs and builds with various components. For example, consider an N-Layer architecture application or a <a target="_blank" href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">clean architecture</a> application where an application has more than one library that interacts with each other.</p>
<p>Here comes <code>HttPContextAccessor</code> into picture which helps to access <code>HttpContext</code> inside non-framework constructs. We will understand this with an example below.</p>
<p>for this article, we will take an example of an ASP.NET Core web API application that is built using 3 layers.</p>
<p>below is the project structure for this application :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1705337281603/5c0268cc-1ab6-4081-8510-07a9ba51dd15.png" alt /></p>
<ul>
<li><p>DemoWebApi - Web API project</p>
</li>
<li><p>DataAccess - responsible for data access i.e. database connection</p>
</li>
<li><p>Application - application's business logic layer</p>
</li>
</ul>
<p>Now consider a requirement where we need to access the current <code>HttpContext</code> inside the Application layer or Data Access layer. This could be anything like accessing the current logged-in user or user claims etc.</p>
<p>In such a scenario, <code>HttpContext</code> is not directly accessible or cannot be injected as a dependency. So we utilize the <code>HttPContextAccessor</code> to achieve the above-mentioned objective.</p>
<h3 id="heading-how-to-use-httpcontextaccessor">How to use HttPContextAccessor?</h3>
<p>To understand the use of <code>HttPContextAccessor</code> , we are going to create a sample application that has 3 layers as demonstrated above. We have a requirement where we need to log the request path. for demonstration purposes, we would access the <code>HttpContext</code> request's path inside the <code>Application</code> project and will log it inside the <code>DataAccess</code> project.</p>
<p>The code for this demo can be found in the <a target="_blank" href="https://github.com/dkj468/HttpContextAccesorDemo">HttpContextAccessorDemo</a> Github repo.</p>
<ul>
<li><p>Add dependency to inject <code>HttpContextAccessor</code> in <code>Program.cs</code> file.</p>
<pre><code class="lang-csharp">  builder.Services.AddHttpContextAccessor();
</code></pre>
</li>
<li><p>Create a service that needs the <code>HttpContextAccessor</code></p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IRequestPathAccessor</span> {
      <span class="hljs-function"><span class="hljs-keyword">string</span> <span class="hljs-title">GetRequestPath</span>(<span class="hljs-params"></span>)</span>;
  }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">RequestPathAccessor</span> : <span class="hljs-title">IRequestPathAccessor</span> {
      <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IHttpContextAccessor _httpContextAccessor;
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RequestPathAccessor</span>(<span class="hljs-params">IHttpContextAccessor httpContextAccessor</span>)</span>{
          _httpContextAccessor = httpContextAccessor;
      }
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetRequestPath</span>(<span class="hljs-params"></span>)</span>{
          <span class="hljs-keyword">return</span> _httpContextAccessor.HttpContext.Request.Path;
      }
  }
</code></pre>
</li>
<li><p>Finally, inject RequestPathAccessor as a service into the dependency container to be used inside some other project. (Inside Program.cs file)</p>
<pre><code class="lang-csharp">  builder.Services.AddHttpContextAccessor();
  builder.Services.AddScoped&lt;IRequestPathAccessor, RequestPathAccessor&gt;();
</code></pre>
</li>
<li><p>Service to log the request path (DataAccess project)</p>
<pre><code class="lang-csharp">      <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IRepoService</span> {
          <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">LogRequestPath</span>(<span class="hljs-params"></span>)</span>;
      }

      <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">RepoService</span> : <span class="hljs-title">IRepoService</span>{
          <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IRequestPathAccessor _userAccessor;
          <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RepoService</span>(<span class="hljs-params">DataContext context,  IRequestPathAccessor userAccessor</span>)</span>{
              _userAccessor = userAccessor;
          }
          <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogRequestPath</span>(<span class="hljs-params"></span>)</span>{
              <span class="hljs-comment">// get path </span>
              <span class="hljs-keyword">var</span> path = _userAccessor.GetRequestPath();
              Console.WriteLine(path);
          }
      }
</code></pre>
<p>  In this way, <code>HttPContextAccessor</code> could be used to access the current context.</p>
<p>  Thanks</p>
</li>
</ul>
<h3 id="heading-resources">Resources</h3>
<ul>
<li><a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-8.0">Access HttpContext in ASP.NET Core | Microsoft Learn</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[EF Core Query interceptor]]></title><description><![CDATA[Query interceptor in EF core allows developer to intercept the query before or after the execution. This provides the ability of interception, modification, or suppression of the query execution.
How to use Query Interceptor into code
EF core exposes...]]></description><link>https://thoughtcopy.com/ef-core-query-interceptor</link><guid isPermaLink="true">https://thoughtcopy.com/ef-core-query-interceptor</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[entity framework]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Sun, 14 Jan 2024 00:23:51 GMT</pubDate><content:encoded><![CDATA[<p>Query interceptor in EF core allows developer to intercept the query before or after the execution. This provides the ability of interception, modification, or suppression of the query execution.</p>
<h3 id="heading-how-to-use-query-interceptor-into-code">How to use Query Interceptor into code</h3>
<p>EF core exposes <code>DbCommandInterceptor</code>  base class, this base class is abstract class and has overridable methods which could be hooked into a class which is inherited <code>DbCommandInterceptor</code> class. Since Entity framework internally uses <a target="_blank">ADO.NET</a> for database operations,  <code>DbCommandInterceptor</code> class provides lifecycle methods for a query.</p>
<h3 id="heading-code-example">Code example</h3>
<p><strong>Create a class that inherits</strong> <code>DbCommandInterceptor</code></p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QueryInterceptor</span> :<span class="hljs-title">DbCommandInterceptor</span> {
}
</code></pre>
<p><strong>Override the lifecycle method which you are interested in</strong></p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QueryInterceptor</span> :<span class="hljs-title">DbCommandInterceptor</span> {
    <span class="hljs-comment">// runs before a query is executed</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> InterceptionResult&lt;DbDataReader&gt; <span class="hljs-title">ReaderExecuting</span>(<span class="hljs-params">DbCommand command,CommandEventData eventData, InterceptionResult&lt;DbDataReader&gt; result</span>)</span>{
        Console.WriteLine(<span class="hljs-string">$"Before Query execution. Query : <span class="hljs-subst">{command.CommandText}</span>"</span>);
        <span class="hljs-keyword">return</span> result;
    }
    <span class="hljs-comment">// runs after a query is excuted</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> DbDataReader <span class="hljs-title">ReaderExecuted</span>(<span class="hljs-params">DbCommand command, CommandExecutedEventData eventData, DbDataReader result</span>)</span> {
        Console.WriteLine(<span class="hljs-string">$"After Query execution. Query : <span class="hljs-subst">{command.CommandText}</span>"</span>);
        <span class="hljs-keyword">return</span> result;
    }        
}
</code></pre>
<p><code>DbCommandInterceptor</code> provides async version of these methods to support asynchronous operations</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QueryInterceptor</span> :<span class="hljs-title">DbCommandInterceptor</span> {
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> ValueTask&lt;InterceptionResult&lt;DbDataReader&gt;&gt; ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult&lt;DbDataReader&gt; result, CancellationToken cancellationToken = <span class="hljs-keyword">default</span>){
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">base</span>.ReaderExecutingAsync(command, eventData, result, cancellationToken);
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> ValueTask&lt;DbDataReader&gt; <span class="hljs-title">ReaderExecutedAsync</span>(<span class="hljs-params">DbCommand command, CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = <span class="hljs-keyword">default</span></span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">base</span>.ReaderExecutedAsync(command, eventData, result, cancellationToken);
    }
}
</code></pre>
<p><strong>Register the interceptor with DbContext:</strong></p>
<p>An interceptor could be added to context using two ways :</p>
<ul>
<li><p>register while adding DbContext to services</p>
<pre><code class="lang-csharp">  services.AddDbContext&lt;ExampleContext&gt;(opt =&gt; 
    opt.UseNpgsql(cfg.GetConnectionString(<span class="hljs-string">"DefaultConnectionString"</span>))
       .AddInterceptors (<span class="hljs-keyword">new</span> QueryInterceptor()));
</code></pre>
</li>
</ul>
<ul>
<li><p>register inside <code>OnConfiguring</code> method of DbContext class</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ExampleContext</span> : <span class="hljs-title">DbContext</span>{
      <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnConfiguring</span>(<span class="hljs-params">DbContextOptionsBuilder optionsBuilder</span>)</span>{
          <span class="hljs-keyword">base</span>.OnConfiguring(optionsBuilder);
          optionsBuilder.AddInterceptors(<span class="hljs-keyword">new</span> QueryInterceptor())
      }
  }
</code></pre>
</li>
</ul>
<h3 id="heading-list-of-lifecycle-methods-available">List of lifecycle methods available</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Method Name</td><td><strong>Description</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.commandcanceled?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-commandcanceled(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandendeventdata)">CommandCanceled</a> , <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.commandcanceledasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-commandcanceledasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandendeventdata-system-threading-cancellationtoken)">CommandCanceledAsync</a></td><td>called when a command is cancelled.</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.commandcreated?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-commandcreated(microsoft-entityframeworkcore-diagnostics-commandendeventdata-system-data-common-dbcommand)">CommandCreated</a></td><td>After command creation but before execution.</td></tr>
<tr>
<td>[CommandCreating](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.commandcreating?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-commandcreating(microsoft-entityframeworkcore-diagnostics-commandcorrelatedeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult((system-data-common-dbcommand))))</td><td>Before a command is created</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.commandfailed?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-commandfailed(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commanderroreventdata)">CommandFailed</a>, <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.commandfailedasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-commandfailedasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commanderroreventdata-system-threading-cancellationtoken)">CommandFailedAsync</a></td><td>Called when execution of a command has failed with an exception.</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.commandinitialized?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-commandinitialized(microsoft-entityframeworkcore-diagnostics-commandendeventdata-system-data-common-dbcommand)">CommandInitialized</a></td><td>Called after EF has initialized <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.commandtext#system-data-common-dbcommand-commandtext">CommandText</a> and other command configuration.</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.datareaderclosing?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-datareaderclosing(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-datareaderclosingeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult)">DataReaderClosing</a>, <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.datareaderclosingasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-datareaderclosingasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-datareaderclosingeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult)">DataReaderClosingAsync</a></td><td>Called just before EF intends to call <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbdatareader.close#system-data-common-dbdatareader-close">Close()</a>.</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.datareaderdisposing?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-datareaderdisposing(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-datareaderdisposingeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult)">DataReaderDisposing</a></td><td>Called when execution of a <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbdatareader">DbDataReader</a> is about to be disposed.</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.nonqueryexecuted?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-nonqueryexecuted(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandexecutedeventdata-system-int32)">NonQueryExecuted</a>, <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.nonqueryexecutedasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-nonqueryexecutedasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandexecutedeventdata-system-int32-system-threading-cancellationtoken)">NonQueryExecutedAsync</a></td><td>Called immediately after EF calls <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executenonquery#system-data-common-dbcommand-executenonquery">ExecuteNonQuery()</a>.</td></tr>
<tr>
<td>[NonQueryExecuting](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.nonqueryexecuting?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-nonqueryexecuting(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult((system-int32)))), [NonQueryExecutingAsync](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.nonqueryexecutingasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-nonqueryexecutingasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult((system-int32))-system-threading-cancellationtoken))</td><td>Called just before EF intends to call <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executenonquery#system-data-common-dbcommand-executenonquery">ExecuteNonQuery()</a>.</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.readerexecuted?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-readerexecuted(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandexecutedeventdata-system-data-common-dbdatareader)">ReaderExecuted</a>, <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.readerexecutedasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-readerexecutedasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandexecutedeventdata-system-data-common-dbdatareader-system-threading-cancellationtoken)">ReaderExecutedAsync</a></td><td>Called immediately after EF calls <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executereader#system-data-common-dbcommand-executereader">ExecuteReader()</a>.</td></tr>
<tr>
<td>[ReaderExecuting](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.readerexecuting?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-readerexecuting(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult((system-data-common-dbdatareader)))), [ReaderExecutingAsync](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.readerexecutingasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-readerexecutingasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult((system-data-common-dbdatareader))-system-threading-cancellationtoken))</td><td>Called just before EF intends to call <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executereader#system-data-common-dbcommand-executereader">ExecuteReader()</a>.</td></tr>
<tr>
<td><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.scalarexecuted?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-scalarexecuted(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandexecutedeventdata-system-object)">ScalarExecuted</a>, <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.scalarexecutedasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-scalarexecutedasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandexecutedeventdata-system-object-system-threading-cancellationtoken)">ScalarExecutedAsync</a></td><td>Called immediately after EF calls <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executescalar#system-data-common-dbcommand-executescalar">ExecuteScalar()</a>.</td></tr>
<tr>
<td>[ScalarExecuting](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.scalarexecuting?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-scalarexecuting(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult((system-object)))), [ScalarExecutingAsync](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.idbcommandinterceptor.scalarexecutingasync?view=efcore-7.0#microsoft-entityframeworkcore-diagnostics-idbcommandinterceptor-scalarexecutingasync(system-data-common-dbcommand-microsoft-entityframeworkcore-diagnostics-commandeventdata-microsoft-entityframeworkcore-diagnostics-interceptionresult((system-object))-system-threading-cancellationtoken))</td><td>Called just before EF intends to call <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executescalar#system-data-common-dbcommand-executescalar">ExecuteScalar()</a>.</td></tr>
</tbody>
</table>
</div><h3 id="heading-resources">Resources</h3>
<ul>
<li><p><a target="_blank" href="https://lizzy-gallagher.github.io/query-interception-entity-framework/">Query interception in Entity Framework Core - What’s keeping Lizzy busy? (lizzy-gallagher.github.io)</a></p>
</li>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors">Interceptors - EF Core | Microsoft Learn</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[C# - Value Types Versus Reference Types]]></title><description><![CDATA[C# types can be divided mainly into two categories: value types and reference types. In this article, we would be having a closer look at these two types.
Value Types

Most of the c# built-in types such as numeric types, char types and boolean types ...]]></description><link>https://thoughtcopy.com/c-value-types-versus-reference-types</link><guid isPermaLink="true">https://thoughtcopy.com/c-value-types-versus-reference-types</guid><category><![CDATA[C#]]></category><category><![CDATA[#microsoftstack]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Wed, 19 Jul 2023 05:22:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689743857631/5a5d83b8-731d-4197-bef0-70fe42d638ac.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>C# types can be divided mainly into two categories: <strong>value types</strong> and <strong>reference types</strong>. In this article, we would be having a closer look at these two types.</p>
<h3 id="heading-value-types">Value Types</h3>
<ul>
<li><p>Most of the c# built-in types such as numeric types, char types and boolean types are <em>value types.</em></p>
</li>
<li><p>custom structs and enum types are also <em>value types.</em></p>
</li>
<li><p>content of a value-type variable or constant is simply a value.</p>
</li>
<li><p>The assignment operator always copies the value.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">int</span> a = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">int</span> b = <span class="hljs-number">7</span>;
  b = a;   <span class="hljs-comment">// copies the value of a into b</span>
  Console.WriteLine(<span class="hljs-string">" a = {0}, b = {1}"</span>, a, b);  <span class="hljs-comment">//  a = 10, b = 10</span>
  a = <span class="hljs-number">15</span>;  <span class="hljs-comment">// b won't change</span>
  Console.WriteLine(<span class="hljs-string">" a = {0}, b = {1}"</span>, a, b);  <span class="hljs-comment">//  a = 15, b = 10</span>
</code></pre>
</li>
</ul>
<p><strong>custom value types</strong></p>
<p>custom value types can be created using <code>struct</code> or <code>enum</code> .</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">public</span> <span class="hljs-keyword">struct</span> Point { <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> X; <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Y; }
 Point p1 = <span class="hljs-keyword">new</span> Point();
 p1.X = <span class="hljs-number">7</span>;
 Point p2 = p1; <span class="hljs-comment">// Assignment causes copy</span>
 Console.WriteLine (p1.X); <span class="hljs-comment">// 7</span>
 Console.WriteLine (p2.X); <span class="hljs-comment">// 7</span>

 p1.X = <span class="hljs-number">9</span>; <span class="hljs-comment">// Change p1.X</span>
 Console.WriteLine (p1.X); <span class="hljs-comment">// 9</span>
 Console.WriteLine (p2.X); <span class="hljs-comment">// 7</span>
</code></pre>
<h3 id="heading-reference-types">Reference Types</h3>
<ul>
<li><p>A reference type has two parts: an object and the <code>reference</code> to that object.</p>
</li>
<li><p>content of a reference-type variable or constant is a reference to an object that contains the value.</p>
</li>
<li><p>a class type, an interface type, an array type, a delegate type, or the <code>dynamic</code> type are all <code>reference</code> types.</p>
</li>
</ul>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> { <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> X, Y; }
Point p1 = <span class="hljs-keyword">new</span> Point();
p1.X = <span class="hljs-number">7</span>;
Point p2 = p1; <span class="hljs-comment">// Copies p1 reference</span>
Console.WriteLine (p1.X); <span class="hljs-comment">// 7</span>
Console.WriteLine (p2.X); <span class="hljs-comment">// 7</span>
p1.X = <span class="hljs-number">9</span>; <span class="hljs-comment">// Change p1.X</span>
Console.WriteLine (p1.X); <span class="hljs-comment">// 9</span>
Console.WriteLine (p2.X); <span class="hljs-comment">// 9</span>
</code></pre>
<h3 id="heading-value-types-and-reference-types-and-null">value types and reference types and null</h3>
<ul>
<li><p><code>null</code> can be assigned to reference types without any issue. assigning null to a reference type indicates that the reference points at nothing.</p>
</li>
<li><p>a value type cannot have null [Except <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types">Nullable Value types</a> ]</p>
<h3 id="heading-int-x-null-compile-time-error"><code>int x = null</code> // compile time error</h3>
</li>
</ul>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The fundamental difference between value types and reference types is how they are handled in memory. <code>Value types</code> occupy the memory required to store the field for example 4 bytes for an integer field. However, since the <code>reference type</code> has two parts, it requires separate allocations for reference and object.</div>
</div>

<p>That's it for this article. Thanks for reading it. Please share your thoughts into comment section.</p>
]]></content:encoded></item><item><title><![CDATA[Demystifying Delphi's "Property" Keyword: Simplifying Object-Oriented Programming]]></title><description><![CDATA[Introduction
In the world of programming, Delphi has long been a popular choice for developing Windows applications. Known for its robustness and object-oriented capabilities, Delphi offers developers a wide range of language features to enhance code...]]></description><link>https://thoughtcopy.com/demystifying-delphis-property-keyword-simplifying-object-oriented-programming</link><guid isPermaLink="true">https://thoughtcopy.com/demystifying-delphis-property-keyword-simplifying-object-oriented-programming</guid><category><![CDATA[Delphi]]></category><category><![CDATA[pascal]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Tue, 11 Jul 2023 08:51:55 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-introduction"><strong>Introduction</strong></h3>
<p>In the world of programming, Delphi has long been a popular choice for developing Windows applications. Known for its robustness and object-oriented capabilities, Delphi offers developers a wide range of language features to enhance code readability and maintainability. One such feature is the "property" keyword, which plays a crucial role in encapsulating data and controlling access to class members. In this blog post, we will delve into the intricacies of Delphi's "property" keyword, exploring its purpose, syntax, and benefits.</p>
<h3 id="heading-understanding-encapsulation">Understanding Encapsulation</h3>
<p>Encapsulation is a fundamental principle in object-oriented programming (OOP) that allows data and behavior to be bundled together within a class. It promotes the idea of data hiding and provides controlled access to class members through methods, properties, and events. Delphi's "property" keyword serves as a powerful tool for achieving encapsulation and ensuring proper data management.</p>
<h3 id="heading-syntax-and-usage">Syntax and Usage</h3>
<p>The syntax for defining a property in Delphi is straightforward:</p>
<pre><code class="lang-plaintext">type
  TMyClass = class
  private
    FMyProperty: Integer;
  public
    property MyProperty: Integer read FMyProperty write FMyProperty;
  end;
</code></pre>
<p>Let's break down the components of this code snippet:</p>
<ol>
<li><p>The class declaration begins with the keyword <code>type</code> followed by the class name, in this case, <code>TMyClass</code>.</p>
</li>
<li><p>Within the class, we define a private field, <code>FMyProperty</code>, which will store the actual data associated with the property.</p>
</li>
<li><p>The <code>public</code> section contains the property declaration using the <code>property</code> keyword.</p>
</li>
<li><p>The property identifier, <code>MyProperty</code> in this case, is used to access the property from outside the class.</p>
</li>
<li><p>The <code>read</code> and <code>write</code> specifiers determine the property's accessibility. In this example, the property can be both read and written to.</p>
</li>
<li><p>The <code>FMyProperty</code> identifier after the <code>read</code> and <code>write</code> specifiers refers to the field that stores the property's value.</p>
</li>
</ol>
<h3 id="heading-benefits-and-functionality">Benefits and Functionality</h3>
<ol>
<li><p>Encapsulating Data Access: The property keyword allows you to expose class members while controlling how they are accessed. By defining read and write methods, you can enforce custom logic, perform validation, or trigger events whenever the property is accessed or modified.</p>
</li>
<li><p>Read-Only and Write-Only Properties: The <code>property</code> keyword can be used to define properties that are either read-only or write-only. By omitting the corresponding <code>write</code> or <code>read</code> specifier, you can restrict access to one direction.</p>
</li>
<li><p>Computed Properties: Delphi's properties can be computed dynamically by implementing only the read method. This enables you to derive values based on other properties or perform complex calculations transparently to the user.</p>
</li>
<li><p>Compatibility with Legacy Code: Delphi's properties seamlessly integrate with existing codebases. They can be used to replace direct field access, maintaining backward compatibility while introducing additional functionality.</p>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Delphi's "property" keyword is a powerful tool for achieving encapsulation and controlling access to class members. By using properties, you can expose data in a controlled manner, enforce validation, and trigger custom logic whenever the property is accessed or modified. The flexibility offered by properties simplifies object-oriented programming and improves code maintainability. Understanding and effectively utilizing the "property" keyword empowers Delphi developers to create robust and elegant applications.</p>
]]></content:encoded></item><item><title><![CDATA[A Beginner's Guide to C# Access Modifiers: Learn the Basics]]></title><description><![CDATA[Access modifiers determine the accessibility of a type or type member, indicating which parts of a C# program can access those types and their members. By protecting types and members from unintended access, access modifiers contribute to achieving e...]]></description><link>https://thoughtcopy.com/a-beginners-guide-to-c-access-modifiers-learn-the-basics</link><guid isPermaLink="true">https://thoughtcopy.com/a-beginners-guide-to-c-access-modifiers-learn-the-basics</guid><category><![CDATA[C#]]></category><category><![CDATA[#microsoftstack]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[dotnetcore]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Tue, 11 Jul 2023 07:11:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689059419816/ec261da1-6443-4251-9cc0-f8e144ff3f51.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Access modifiers determine the accessibility of a type or type member, indicating which parts of a C# program can access those types and their members. By protecting types and members from unintended access, access modifiers contribute to achieving encapsulation.</p>
<p>Below is the list of all the access modifiers used in the C# language</p>
<h3 id="heading-public">Public</h3>
<ul>
<li><p>type or members with <code>private</code> access modifiers could be accessed by any code in the same assembly or another assembly referencing it.</p>
</li>
<li><p><code>public</code> is the default access modifier for members of an <code>enum</code> or <code>interface</code>.</p>
</li>
<li><p>accessibility of public members is controlled by the access modifier of the type itself.</p>
<p>  <strong>Code example</strong></p>
<pre><code class="lang-csharp">
  <span class="hljs-keyword">using</span> System;
  <span class="hljs-keyword">namespace</span> <span class="hljs-title">AccessModifierCode</span> {
  <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> {
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> EmpId;
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name;
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Employee</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> empid, <span class="hljs-keyword">string</span> name</span>)</span> {
          EmpId = empid;
          Name = name;
      }
  }
  <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span> {
      <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
          <span class="hljs-comment">// Creating object of the class Employee</span>
          Employee E = <span class="hljs-keyword">new</span> Employee(<span class="hljs-number">1</span>, <span class="hljs-string">"Deepak"</span>);
          Console.WriteLine(<span class="hljs-string">"Emp Id: {0}"</span>, E.EmpId);
          Console.WriteLine(<span class="hljs-string">"Name: {0}"</span>, E.Name);
          Console.WriteLine();
      }
   }
  }
</code></pre>
</li>
</ul>
<h3 id="heading-private">Private</h3>
<ul>
<li><p>members declared with <code>private</code> access modifier are accessible only within the containing type.</p>
</li>
<li><p><code>private</code> access modifier is the most restrictive one.</p>
</li>
<li><p>one can not declare a private class or struct directly inside a namespace.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689039479467/0191882f-b862-479f-a746-fa89d6ca9d9d.png" alt class="image--center mx-auto" /></p>
</li>
<li><p><code>private</code> is the default accessibility for members of a class or struct.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Demo</span> {
     <span class="hljs-keyword">string</span> Name; <span class="hljs-comment">//  private</span>
  }
</code></pre>
<pre><code class="lang-csharp">  <span class="hljs-keyword">using</span> System;
  <span class="hljs-keyword">namespace</span> <span class="hljs-title">AccessModifierCode</span> {
  <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> {
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> EmpId;
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name;
      <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">decimal</span> Salary
      <span class="hljs-keyword">public</span> <span class="hljs-title">Employee</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> empid, <span class="hljs-keyword">string</span> name, <span class="hljs-keyword">decimal</span> salary</span>)</span> {
          EmpId = empid;
          Name = name;
          Salary = salary;
      }
  }
  <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span> {
      <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
          <span class="hljs-comment">// Creating object of the class Employee</span>
          Employee E = <span class="hljs-keyword">new</span> Employee(<span class="hljs-number">1</span>, <span class="hljs-string">"Deepak"</span>, <span class="hljs-number">0</span>);
          Console.WriteLine(<span class="hljs-string">"Emp Id: {0}"</span>, E.EmpId);
          Console.WriteLine(<span class="hljs-string">"Name: {0}"</span>, E.Name);
          Console.WriteLine(<span class="hljs-string">"Salary: {0}"</span>, E.Salary); 
          <span class="hljs-comment">// Error : 'Employee.Salary is inaccessible due to its protection level'</span>
          Console.WriteLine();
      }
   }
  }
</code></pre>
</li>
</ul>
<h3 id="heading-internal">Internal</h3>
<ul>
<li><p>types or members declared with <code>internal</code> modifiers are accessible within the same assembly or friend assembly. Learn more about <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/standard/assembly/friend">Friend assembly</a></p>
</li>
<li><p><code>internal</code> is the default access modifier for class and struct types.</p>
</li>
</ul>
<h3 id="heading-protected">Protected</h3>
<p><code>protected</code> type or members are accessible within the same class or derived class.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span> {
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">int</span> Width { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">int</span> Height { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span> : <span class="hljs-title">Shape</span> {
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Rectangle</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> width, <span class="hljs-keyword">int</span> height</span>)</span> {
        Width = width;
        Height = height;
    }
}
</code></pre>
<h3 id="heading-protected-internal">protected internal</h3>
<ul>
<li>Types or members declared with the <code>protected internal</code> modifier can be accessed only within the same assembly or in a derived class from another assembly.</li>
</ul>
<h3 id="heading-private-protected">private protected</h3>
<ul>
<li>A member that is <code>private protected</code> is accessible only within the containing type, or subclasses that reside in the same assembly (making it less accessible than protected or internal alone).</li>
</ul>
<h2 id="heading-restrictions-on-access-modifiers">Restrictions on Access Modifiers</h2>
<ul>
<li><p>Interfaces declared directly within a namespace can be <code>public</code> or <code>internal</code> and, just like classes and structs, interfaces default to <code>internal</code> access.</p>
</li>
<li><p>Interface members are <code>public</code> by default.</p>
</li>
<li><p>Enumeration members are always <code>public</code>, and no access modifiers can be applied.</p>
</li>
<li><p>Delegates function similarly to classes and structs. When declared directly within a namespace, they have <code>internal</code> access by default, and when nested, they have <code>private</code> access.</p>
</li>
<li><p>Derived classes and derived records can't have greater accessibility than their base types. You can't declare a public class <code>B</code> that derives from an internal class <code>A</code>. If allowed, it would have the effect of making <code>A</code> public, because all <code>protected</code> or <code>internal</code> members of <code>A</code> are accessible from the derived class.</p>
</li>
</ul>
<p>When overriding a base class function, accessibility must be identical to the over‐ ridden function.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">class</span> <span class="hljs-title">BaseClass</span> { 
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Foo</span>(<span class="hljs-params"></span>)</span> {} 
}
<span class="hljs-keyword">class</span> <span class="hljs-title">Subclass1</span> : <span class="hljs-title">BaseClass</span> { 
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Foo</span>(<span class="hljs-params"></span>)</span> {} <span class="hljs-comment">// OK</span>
} 
<span class="hljs-keyword">class</span> <span class="hljs-title">Subclass2</span> : <span class="hljs-title">BaseClass</span> { 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Foo</span>(<span class="hljs-params"></span>)</span> {} <span class="hljs-comment">// Error</span>
}
</code></pre>
<h2 id="heading-summary-table"><strong>Summary table</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Caller's location</td><td><code>public</code></td><td><code>protected internal</code></td><td><code>protected</code></td><td><code>internal</code></td><td><code>private protected</code></td><td><code>private</code></td></tr>
</thead>
<tbody>
<tr>
<td>Within the class</td><td>✔️️</td><td>✔️</td><td>✔️</td><td>✔️</td><td>✔️</td><td>✔️</td></tr>
<tr>
<td>Derived class (same assembly)</td><td>✔️</td><td>✔️</td><td>✔️</td><td>✔️</td><td>✔️</td><td>❌</td></tr>
<tr>
<td>Non-derived class (same assembly)</td><td>✔️</td><td>✔️</td><td>❌</td><td>✔️</td><td>❌</td><td>❌</td></tr>
<tr>
<td>Derived class (different assembly)</td><td>✔️</td><td>✔️</td><td>✔️</td><td>❌</td><td>❌</td><td>❌</td></tr>
<tr>
<td>Non-derived class (different assembly)</td><td>✔️</td><td>❌</td><td>❌</td><td>❌</td><td>❌</td><td>❌</td></tr>
</tbody>
</table>
</div><p>(note: copied from <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers">MS learn</a>)</p>
<p>So, that concludes our discussion on access modifiers. In this article, we covered the six access modifiers in C#: public, private, protected, internal, protected internal, and private protected. We learned about the purpose of each access modifier and their applications.</p>
<p>By employing the appropriate access modifier, we can ensure that our code is secure, user-friendly, and easy to maintain. Ultimately, this allows us to establish a clear and consistent structure for our code.</p>
<p><strong>References and further reading</strong></p>
<ul>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers</a></p>
</li>
<li><p><a target="_blank" href="https://www.amazon.com/C-10-Nutshell-Definitive-Reference/dp/1098121953">C# 10 in a Nutshell: The Definitive Reference</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/614818/in-c-what-is-the-difference-between-public-private-protected-and-having-no">https://stackoverflow.com/questions/614818/in-c-what-is-the-difference-between-public-private-protected-and-having-no</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[C# delegates]]></title><description><![CDATA[What is a delegate?
a delegate is a reference type variable that holds the reference of a method. C# delegates are similar to the C / C++ equivalent of pointers to the method - a delegate holds the address of a method that can be called using the del...]]></description><link>https://thoughtcopy.com/c-delegates</link><guid isPermaLink="true">https://thoughtcopy.com/c-delegates</guid><category><![CDATA[dotnet]]></category><category><![CDATA[dotnetcore]]></category><category><![CDATA[C#]]></category><category><![CDATA[delegate]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Fri, 30 Jun 2023 10:11:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688119614837/53abbaf6-000b-4b6a-89da-db8878858b4f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-a-delegate">What is a delegate?</h3>
<p>a <code>delegate</code> is a reference type variable that holds the reference of a method. C# delegates are similar to the C / C++ equivalent of pointers to the method - a delegate holds the address of a method that can be called using the delegate.</p>
<blockquote>
<p>A delegate is an object that knows how to call a method.</p>
</blockquote>
<h3 id="heading-defining-the-delegate">Defining the delegate</h3>
<p>A <code>delegate type</code> defines the kind of method that <code>delegate instances</code> can call. Specifically, it defines the method’s <code>return type</code> and its <code>parameter types</code>. The following defines a delegate type called Transformer:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">delegate</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Transformer</span> (<span class="hljs-params"><span class="hljs-keyword">int</span> x</span>)</span>;
</code></pre>
<p>above delegate <code>Transformer</code> is compatible with any method with an int return type and a single int parameter. for example</p>
<pre><code class="lang-csharp">    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Square</span> (<span class="hljs-params"><span class="hljs-keyword">int</span> x</span>)</span> { <span class="hljs-keyword">return</span> x * x; }
    <span class="hljs-comment">// OR</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Square</span> (<span class="hljs-params"><span class="hljs-keyword">int</span> x</span>)</span> =&gt; x * x;
</code></pre>
<p>assigning a method to a delegate variable creates a <code>delegate instance</code>. a delegate instance can be invoked in the same way as a method.</p>
<pre><code class="lang-csharp">Transformer t = Square;
<span class="hljs-keyword">int</span> answer = t(<span class="hljs-number">3</span>);  <span class="hljs-comment">// 9</span>
<span class="hljs-comment">//OR </span>
<span class="hljs-keyword">int</span> answer = t.Invoke(<span class="hljs-number">3</span>); <span class="hljs-comment">// 9</span>

<span class="hljs-comment">// t(3) is shorthand for t.Invoke(3)</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">A delegate instance acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method</div>
</div>

<ul>
<li><p>Delegates are used to define callback methods and implement event handling.</p>
</li>
<li><p>Delegates allow methods to be passed as parameters.</p>
</li>
<li><p>Delegates can be chained together; for example, multiple methods can be called on a single event (multicast delegates).</p>
</li>
</ul>
<h3 id="heading-multicast-delegates">Multicast delegates</h3>
<p>all delegates have <code>multicast</code> ability which means a delegate instance can reference more than one method.</p>
<pre><code class="lang-csharp">SomeDelegate d = SomeMethod1;
d += SomeMethod2;
</code></pre>
<ul>
<li><p>multicast delegates are invoked in the order in which they are added.</p>
</li>
<li><p>a method could be removed at runtime from the multicast delegate.</p>
<p>  <code>d -= SomeMethod1;</code></p>
</li>
<li><p>If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be invoked. for most of the scenarios where multicast delegates are used, methods have a void return type.</p>
</li>
</ul>
<h3 id="heading-generic-delegate-types">Generic delegate types</h3>
<p>A delegate type can have generic type parameters and return type :</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">delegate</span> T <span class="hljs-title">Transformer</span>&lt;<span class="hljs-title">T</span>&gt; (<span class="hljs-params">T arg</span>)</span>;
<span class="hljs-keyword">int</span>[] values = { <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span> };
Util.Transform (values, Square); <span class="hljs-comment">// Hook in Square</span>
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">int</span> i <span class="hljs-keyword">in</span> values)
  Console.Write (i + <span class="hljs-string">" "</span>); <span class="hljs-comment">// 1 4 9</span>
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">Square</span> (<span class="hljs-params"><span class="hljs-keyword">int</span> x</span>)</span> =&gt; x * x;
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Util</span> {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Transform</span>&lt;<span class="hljs-title">T</span>&gt; (<span class="hljs-params">T[] values, Transformer&lt;T&gt; t</span>)</span> {
   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; values.Length; i++)
     values[i] = t (values[i]);
 }
}
</code></pre>
<h3 id="heading-the-func-and-action-delegates">The Func and Action Delegates</h3>
<p>both <code>Func</code> and <code>Action</code> delegates are reference types that encapsulate a method.</p>
<p>The <code>Func</code> delegate refers to a method that accepts some parameters and returns a value.</p>
<p>The <code>Action</code> delegate refers to a method that accepts parameters but <em>do not return any value.</em></p>
<p>below is the declaration syntax of a <code>Func</code> delegate :</p>
<p><code>Func&lt;in_param 1, in_param 2, out_Param &gt; name ;</code></p>
<pre><code class="lang-csharp">      <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
         Func&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt; func = Concat;
         <span class="hljs-keyword">string</span> fullName = func(<span class="hljs-string">"Deepak"</span>, <span class="hljs-string">"Jain"</span>);
         Console.WriteLine(fullName);
         Console.ReadLine();
      }
      <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">Concat</span> (<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span> {
         <span class="hljs-keyword">return</span> firstName + lastName;
      }
</code></pre>
<p>Below is an example of <code>Action</code> delegate :</p>
<p><code>Action&lt;in_param&gt; name</code></p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
         Action&lt;<span class="hljs-keyword">string</span>&gt; act = Display;
         act(<span class="hljs-string">"Hello World"</span>); <span class="hljs-comment">// Hello World</span>
         Console.ReadLine();
      }
      <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-title">Display</span> (<span class="hljs-params"><span class="hljs-keyword">string</span> content</span>)</span> {
         console.log(content);
      }
</code></pre>
<p>That's it for this article, please share your feedback in comment section.</p>
<p><strong>references and further reading</strong></p>
<ul>
<li><a target="_blank" href="https://www.amazon.com/C-10-Nutshell-Definitive-Reference/dp/1098121953">C# 10 in a Nutshell: The Definitive Reference</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[C# : Boxing and Unboxing]]></title><description><![CDATA[While working with C# datatypes, developers often needs to convert value types to reference type or vice-versa. The process of converting value type to reference type is termed as boxing and converting a reference type to value type is termed as unbo...]]></description><link>https://thoughtcopy.com/c-boxing-and-unboxing</link><guid isPermaLink="true">https://thoughtcopy.com/c-boxing-and-unboxing</guid><category><![CDATA[C#]]></category><category><![CDATA[learning]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[#microsoftstack]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Thu, 22 Jun 2023 11:29:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687432947826/500c07e9-9ece-4f38-bd39-e0f38fdf2169.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While working with C# datatypes, developers often needs to convert <code>value</code> types to <code>reference</code> type or vice-versa. The process of converting <code>value</code> type to <code>reference</code> type is termed as <strong>boxing</strong> and converting a <code>reference</code> type to <code>value</code> type is termed as <strong>unboxing.</strong></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">A value type variable is immutable data which contains the data, instead of a reference to it. Value types often have short lives. They are typically stored in memory in an area known as the stack. The stack is where data that does not need to exist for long lives. Structs, Int32, DateTime, and Double are examples of value types.</div>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>A reference type variable contains a reference to data stored in memory, also known as the heap</strong>. The heap is most often used for data that has a longer life. You can have more than one variable point to the same referenced data. Objects are an example of a reference type</div>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">In C#, <code>System.Object</code> is parent class of all the types, it means its possible to assign in any value to <code>Object</code> type instance. [Object = an alias of <code>System.Object</code> ]</div>
</div>

<h3 id="heading-boxing">Boxing</h3>
<p>Boxing is the process of converting <code>value</code> type (int, char etc) to <code>reference</code> type (object). Boxing is an implicit conversion where a <code>value</code> type being allocated on the heap rather than the stack.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> i = <span class="hljs-number">10</span>;
<span class="hljs-keyword">object</span> o = i; <span class="hljs-comment">//performs boxing - implicit boxing</span>
<span class="hljs-keyword">object</span> o = (<span class="hljs-keyword">object</span>)i;  <span class="hljs-comment">// explicit boxing</span>
<span class="hljs-keyword">object</span> o = (<span class="hljs-keyword">object</span>)i;  <span class="hljs-comment">// explicit boxing but never required</span>

<span class="hljs-comment">//more practical example</span>
List&lt;<span class="hljs-keyword">object</span>&gt; mixedList = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">object</span>&gt;();

mixedList.Add(<span class="hljs-string">"First Group:"</span>);  <span class="hljs-comment">// boxing - string to object</span>
mixedList.Add(<span class="hljs-number">10</span>);              <span class="hljs-comment">// boxing - int to object</span>
</code></pre>
<h3 id="heading-unboxing">Unboxing</h3>
<p>Unboxing is explicit conversion from Object / reference type to value type. In the unboxing process, the boxed value type is unboxed from the heap and assigned to a value type that is stored on the stack. This process involves below steps</p>
<ul>
<li><p>Checking that object instance being 'unboxed' is a 'boxed' value of given value type.</p>
</li>
<li><p>copying the value from object instance to value-type variable.</p>
</li>
</ul>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span> i = <span class="hljs-number">123</span>;      <span class="hljs-comment">// a value type</span>
<span class="hljs-keyword">object</span> o = i;     <span class="hljs-comment">// boxing</span>
<span class="hljs-keyword">int</span> j = (<span class="hljs-keyword">int</span>)o;   <span class="hljs-comment">// unboxing</span>

<span class="hljs-comment">//more practical example</span>
List&lt;<span class="hljs-keyword">object</span>&gt; mixedList = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">object</span>&gt;();

mixedList.Add(<span class="hljs-string">"First Group:"</span>);  <span class="hljs-comment">// boxing - string to object</span>
mixedList.Add(<span class="hljs-number">10</span>); 
<span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> item <span class="hljs-keyword">in</span> mixedList) {
    <span class="hljs-comment">// mixedList items are of object type,</span>
    <span class="hljs-comment">// while priting, object type will be 'unboxed' to </span>
    <span class="hljs-comment">// corresponding value-type.</span>
    Console.WriteLine(item); 
}
</code></pre>
<blockquote>
<p>For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox <code>null</code> causes a <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception">NullReferenceException</a>. Attempting to unbox a reference to an incompatible value type causes an <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.invalidcastexception">InvalidCastException</a>.</p>
</blockquote>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Boxing and unboxing are expensive process computationally, so they must be used only when necessary.</div>
</div>

<p>That's it for this article. Thanks for reading it and share your thoughts in comment section.</p>
<h3 id="heading-references-and-further-reading">References and further reading</h3>
<ul>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing</a></p>
</li>
<li><p><a target="_blank" href="https://www.pluralsight.com/guides/csharp-passing-reference-vs-value-objective">https://www.pluralsight.com/guides/csharp-passing-reference-vs-value-objective</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[C# Exception Handling]]></title><description><![CDATA[💡
Exception = an unexpected event that occurred during program execution that disrupts the desired flow of the program.


As mentioned above, exceptions disrupt the flow of the program and terminate the program abnormally. It's the developer's respo...]]></description><link>https://thoughtcopy.com/c-exception-handling</link><guid isPermaLink="true">https://thoughtcopy.com/c-exception-handling</guid><category><![CDATA[C#]]></category><category><![CDATA[exceptionhandling]]></category><category><![CDATA[microsoft technology stack]]></category><category><![CDATA[learning]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Wed, 21 Jun 2023 10:14:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687342225948/0facaac0-1d3c-41cd-a6e1-27c7da9e6586.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Exception = an unexpected event that occurred during program execution that disrupts the desired flow of the program.</div>
</div>

<p>As mentioned above, exceptions disrupt the flow of the program and terminate the program abnormally. It's the developer's responsibility to handle exceptions gracefully. If these errors are not handled properly, the program might crash and you may never know the root cause of failure.</p>
<p>Handling or responding to exceptions is called Exception Handling.</p>
<p>In C#, exception handling is achieved using 4 keywords :</p>
<ul>
<li><p><strong>try</strong>: code that might generate exceptions is put inside the <code>try</code> block.</p>
</li>
<li><p><strong>catch:</strong> This block <code>'catches'</code> the exception generated inside <code>try</code> block. The developer could decide what's need done once an exception is generated i.e. logging the stack trace, logging error messages, showing error prompts to the user etc.</p>
</li>
<li><p><strong>finally:</strong> This code block when written will always execute no matter whether an exception is raised or not. This is useful in scenarios where some clean-up code is required for example closing a file.</p>
</li>
<li><p><strong>throw:</strong> <code>throw</code> keyword is used to generate new exceptions in code.</p>
</li>
</ul>
<blockquote>
<p>In C#, exceptions are a type represented by classes derived from class <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.exception?view=net-7.0">Exception</a>.</p>
</blockquote>
<h2 id="heading-exception-classes">Exception classes</h2>
<p>C# .NET includes built-in exception classes for every possible error. The <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.exception?view=net-7.0">Exception</a> class is the base class of all the exception classes.</p>
<p>below is a list of common C# exception classes :</p>
<ul>
<li><p><code>System.NullReferenceException</code> – Very common exception related to calling a method on a null object reference.</p>
</li>
<li><p><code>System.IndexOutOfRangeException</code> – Occurs attempting to access an array element that does not exist.</p>
</li>
<li><p><code>System.IO.IOException</code> – Used around many file I/O type operations.</p>
</li>
<li><p><code>System.NET.WebException</code> – Commonly thrown around any errors performing HTTP calls.</p>
</li>
<li><p><code>System.Data.SqlClient.SqlException</code> – Various types of SQL Server exceptions.</p>
</li>
<li><p><code>System.StackOverflowException</code> – If a method calls itself recursively, you may get this exception.</p>
</li>
<li><p><code>System.OutOfMemoryException</code> – If your app runs out of memory.</p>
</li>
<li><p><code>System.InvalidCastException</code> – If you try to cast an object to a type that it can’t be cast to.</p>
</li>
<li><p><code>System.InvalidOperationException</code> – Common generic exception in a lot of libraries.</p>
</li>
<li><p><code>System.ObjectDisposedException</code> – Trying to use an object that has already been disposed of.</p>
</li>
</ul>
<h2 id="heading-handling-exception">Handling exception</h2>
<pre><code class="lang-csharp"><span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">int</span> num = <span class="hljs-number">0</span>;
    <span class="hljs-comment">// code that may raise an exception </span>
    <span class="hljs-keyword">int</span> divideByZero = <span class="hljs-number">7</span> / num;
}
<span class="hljs-keyword">catch</span> (Exception e){
    <span class="hljs-comment">// 'catching' and 'handling' the exception</span>
    Console.WriteLine(<span class="hljs-string">"Exception has occurred :"</span> + e.Message);
}
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This is a simple example to illustrate exception handling. We could deal with this particular scenario better in practice by checking explicitly for the divisor being zero before operating. <strong>Checking for preventable errors is preferable</strong> to relying on try/catch blocks because exceptions are relatively expensive to handle, taking hundreds of clock cycles or more</div>
</div>

<p>running the above program shows the below output</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687333345771/71ca3259-a3c9-4523-a307-a44ddb867138.png" alt class="image--center mx-auto" /></p>
<p>if finally block is also available then it also gets executed</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">int</span> num = <span class="hljs-number">0</span>;
    <span class="hljs-comment">// code that may raise an exception </span>
    <span class="hljs-keyword">int</span> divideByZero = <span class="hljs-number">7</span> / num;
}
<span class="hljs-keyword">catch</span> (Exception e){
    <span class="hljs-comment">// 'catching' and 'handling' the exception</span>
    Console.WriteLine(<span class="hljs-string">"Exception has occurred :"</span> + e.Message);
}
<span class="hljs-keyword">finally</span> {
    Console.WriteLine(<span class="hljs-string">"Inside finally"</span>);
}
</code></pre>
<h3 id="heading-how-exception-handling-workflow-works">How exception handling workflow works</h3>
<p>When an exception is thrown within a try statement, the CLR performs a test:</p>
<p><em>Does the try statement have any compatible catch blocks?</em></p>
<p>• If so, execution jumps to the compatible catch block, followed by the finally block (if present), and then execution continues normally.</p>
<p>• If not, execution jumps directly to the finally block (if present), then the CLR looks up the call stack for other try blocks; if found, it repeats the test.</p>
<p>If no function in the call stack takes responsibility for the exception, the program terminates.</p>
<h2 id="heading-multiple-catch-blocks">Multiple Catch Blocks</h2>
<p>A program code that is written inside a <code>try</code> block might raise multiple types of exceptions. These multiple types of exceptions could be handled using multiple catch blocks. Remember that a more specialized catch block should come before a generalized one. Otherwise, the compiler will show a compilation error.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
            <span class="hljs-keyword">try</span> {
                <span class="hljs-keyword">byte</span> b = <span class="hljs-keyword">byte</span>.Parse(args[<span class="hljs-number">0</span>]);
                Console.WriteLine(b);
            }
            <span class="hljs-keyword">catch</span> (IndexOutOfRangeException) {
                Console.WriteLine(<span class="hljs-string">"Please provide at least one argument"</span>);
            }
            <span class="hljs-keyword">catch</span> (FormatException) {
                Console.WriteLine(<span class="hljs-string">"That's not a number!"</span>);
            }
            <span class="hljs-keyword">catch</span> (OverflowException) {
                Console.WriteLine(<span class="hljs-string">"You've given me more than a byte!"</span>);
            }
        }
    }
</code></pre>
<h2 id="heading-catching-all-exception-types">Catching all exception types</h2>
<p>a <code>catch</code> block without bracket or having type as <code>Exception</code> can handle all exception types.</p>
<pre><code class="lang-csharp">        <span class="hljs-keyword">try</span>{
            div = <span class="hljs-number">100</span> / x;
            Console.WriteLine(<span class="hljs-string">"Not executed line"</span>);
        }
        <span class="hljs-keyword">catch</span> {
            Console.WriteLine(<span class="hljs-string">"oException"</span>);
        }
</code></pre>
<h2 id="heading-throwing-an-exception">Throwing an Exception</h2>
<p>using <code>throw</code> keyword, an exception could be thrown programmatically.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ProgramLog</span> {
    FileStream logFile = <span class="hljs-literal">null</span>!;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OpenLog</span>(<span class="hljs-params">FileInfo fileName, FileMode mode</span>)</span> { }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">WriteLog</span>(<span class="hljs-params"></span>)</span> {
        <span class="hljs-keyword">if</span> (!logFile.CanWrite) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(<span class="hljs-string">"Logfile cannot be read-only"</span>);
        }
        <span class="hljs-comment">// Else write data to the log and return.</span>
    }
}
</code></pre>
<h1 id="heading-user-defined-exceptions"><strong>User-defined exceptions</strong></h1>
<p>a user-defined exception class can be created by deriving from the <code>Exception</code> class.</p>
<p>When creating your own exceptions, end the class name of the user-defined exception with the word "Exception", and implement the three common constructors, shown below code :</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeListNotFoundException</span> : <span class="hljs-title">Exception</span> {
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">EmployeeListNotFoundException</span>(<span class="hljs-params"></span>)</span> {
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">EmployeeListNotFoundException</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message</span>)
        : <span class="hljs-title">base</span>(<span class="hljs-params">message</span>)</span> {
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">EmployeeListNotFoundException</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message, Exception inner</span>)
        : <span class="hljs-title">base</span>(<span class="hljs-params">message, inner</span>)</span> {
    }
}
</code></pre>
<p>That's it for this article, please share your feedback in the comments.</p>
<h3 id="heading-references-and-further-reading">References and further reading</h3>
<ul>
<li><p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/standard/exceptions/">Handling and throwing exceptions in .NET | Microsoft Learn</a></p>
</li>
<li><p><a target="_blank" href="https://www.amazon.com/C-10-Nutshell-Definitive-Reference/dp/1098121953">C# 10 in a Nutshell: The Definitive Reference</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[C# abstract keyword]]></title><description><![CDATA[In this tutorial, we would learn about abstract keyword in c# programming language.
abstract: This modifier indicates that thing being modified has a missing or incomplete implementation.
This modifier in C# language applies to the following :

Class...]]></description><link>https://thoughtcopy.com/c-abstract-keyword</link><guid isPermaLink="true">https://thoughtcopy.com/c-abstract-keyword</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[microsoft technology stack]]></category><category><![CDATA[learning]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Tue, 20 Jun 2023 01:19:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687223705608/072352c1-a738-435c-acde-cf4150493612.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we would learn about <code>abstract</code> keyword in c# programming language.</p>
<p><code>abstract</code>: This modifier indicates that thing being modified has a missing or incomplete implementation.</p>
<p>This modifier in C# language applies to the following :</p>
<ol>
<li><p>Class</p>
</li>
<li><p>Method</p>
</li>
<li><p>Properties</p>
</li>
<li><p>Indexers</p>
</li>
<li><p>Events</p>
</li>
</ol>
<h3 id="heading-abstract-class"><strong>Abstract class</strong></h3>
<p>A class declared with <code>abstract</code> modifier is an abstract class.</p>
<ul>
<li><p>abstract classes are intended to be a base class of other classes - the developer can not create an Object of an abstract class.</p>
</li>
<li><p>an abstract class can have both abstract methods ( methods with definition) and non-abstract methods (methods without definition).</p>
</li>
<li><p>As an object can not be created for an abstract class, a derived class must be created for an abstract class.</p>
</li>
</ul>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Asset</span> {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">decimal</span> BuyPrice { <span class="hljs-keyword">get</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">decimal</span> SellPrice { <span class="hljs-keyword">get</span>; }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">decimal</span> <span class="hljs-title">CalculateProfit</span>(<span class="hljs-params"></span>)</span>;
    }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Stock</span> : <span class="hljs-title">Asset</span> {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">decimal</span> BuyPrice =&gt; <span class="hljs-number">100</span>;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">decimal</span> SellPrice =&gt; <span class="hljs-number">150</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">decimal</span> <span class="hljs-title">CalculateProfit</span>(<span class="hljs-params"></span>)</span> {
            <span class="hljs-keyword">return</span> (SellPrice - BuyPrice);
        }
    }
</code></pre>
<ul>
<li><p>An abstract class must provide implementation for all interface members</p>
</li>
<li><p>An abstract class that implements an interface might map the interface methods onto abstract methods.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">interface</span> <span class="hljs-title">I</span> {
      <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">M</span>(<span class="hljs-params"></span>)</span>;
  }
  <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">C</span> : <span class="hljs-title">I</span> {
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">M</span>(<span class="hljs-params"></span>)</span>;
  }
</code></pre>
</li>
</ul>
<h3 id="heading-abstract-methods-properties">Abstract methods / Properties</h3>
<ul>
<li><p>abstract method declaration doesn't provide any implementation.</p>
<pre><code class="lang-csharp">  <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Asset</span> {
          <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">decimal</span> <span class="hljs-title">CalculateProfit</span>(<span class="hljs-params"></span>)</span>;
      }
</code></pre>
</li>
<li><p>An abstract method is implicitly a virtual method - base class must provide its implementation.</p>
</li>
<li><p>It is an error to use static or virtual modifiers in an abstract method declaration.</p>
</li>
<li><p>Abstract method declarations are only permitted in abstract classes.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687162488554/0af53a34-7995-432a-b6ec-6e649a7197f6.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax..</p>
</li>
</ul>
<p>That's it for this article. Thanks for reading this, please share your feedback in the comments section below.</p>
]]></content:encoded></item><item><title><![CDATA[C# virtual, override and new keyword]]></title><description><![CDATA[In this article, we would learn about virtual, override and new keyword.
Before moving further to understand about virtual, override and new , it's important to understand how polymorphism is achieved in c#.
What is polymorphism?
The word polymorphis...]]></description><link>https://thoughtcopy.com/c-virtual-override-and-new-keyword</link><guid isPermaLink="true">https://thoughtcopy.com/c-virtual-override-and-new-keyword</guid><category><![CDATA[C#]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Sat, 28 Jan 2023 17:43:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674927557749/dccb92cd-5dba-4b0a-9107-dcf693c58022.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we would learn about <code>virtual</code>, <code>override</code> and <code>new</code> keyword.</p>
<p>Before moving further to understand about <code>virtual</code>, <code>override</code> and <code>new</code> , it's important to understand how <code>polymorphism</code> is achieved in c#.</p>
<h3 id="heading-what-is-polymorphism">What is polymorphism?</h3>
<p>The word polymorphism means having <code>"many forms"</code>. In OOPs terminology, it has two aspects :</p>
<ol>
<li><p>objects of the derived class may be treated as objects of the base class at run time i.e. derived class behavior could be accessed using the base class object.</p>
</li>
<li><p>the base class may define a method that could be overridden by child classes.</p>
</li>
</ol>
<p>in C#, polymorphism is achieved in 3 ways: <mark>method overloading</mark>, <mark>method overriding</mark> and <mark>method hiding</mark></p>
<p>Now let's discuss how <code>virtual</code> , <code>override</code> and <code>new</code> keyword comes into play to implement polymorphism.</p>
<ul>
<li><p>The base class declares a member as <code>virtual</code>. The member could be a method, property or event.</p>
</li>
<li><p>Derived class may <code>override</code> the base class method to provide a new implementation of the base class method into the derived class.</p>
</li>
<li><p>A derived class may hide the base class method using a new keyword.</p>
</li>
</ul>
<p>Enough theory, now we would dive into code to understand these concepts.</p>
<h3 id="heading-method-overriding-example">Method overriding example</h3>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">string</span> AnimalType { <span class="hljs-keyword">get</span> =&gt; <span class="hljs-string">"base"</span>; }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">string</span> <span class="hljs-title">Speak</span>(<span class="hljs-params"></span>)</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-string">"Speaks"</span>;
        }
    }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Horse</span> : <span class="hljs-title">Animal</span> {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> AnimalType { <span class="hljs-keyword">get</span> =&gt; <span class="hljs-string">"Pet"</span>;  }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">Speak</span>(<span class="hljs-params"></span>)</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-string">"Neighs"</span>;
        }
    }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Lion</span>: <span class="hljs-title">Animal</span> {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> AnimalType { <span class="hljs-keyword">get</span> =&gt; <span class="hljs-string">"Wild"</span>; }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">Speak</span>(<span class="hljs-params"></span>)</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-string">"Roars"</span>;
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {        
        Console.WriteLine(<span class="hljs-string">"Start Of the Program"</span>);
        Lion l1 = <span class="hljs-keyword">new</span> Lion();
        Animal a = l1;
        Console.WriteLine(<span class="hljs-string">$"This animal is a <span class="hljs-subst">{a.AnimalType}</span> animal and it <span class="hljs-subst">{a.Speak()}</span>"</span>);

        Horse h1 = <span class="hljs-keyword">new</span> Horse();
        Animal b = h1;
        Console.WriteLine(<span class="hljs-string">$"This animal is a <span class="hljs-subst">{b.AnimalType}</span> animal and it <span class="hljs-subst">{b.Speak()}</span>"</span>);
        Console.ReadKey();
    }
</code></pre>
<p>In the above code block, <em>Animal</em> is base class that has few virtual members. These virtual members are being overridden by derived classes <em>Lion</em> and <em>Horse</em> differently</p>
<h3 id="heading-method-hiding-example">Method hiding example</h3>
<p>derived classes may hide the base class method i.e. derived class could have a method same ( same method name, return type and parameters) as a base class. <code>new</code> keyword is used to hide the base class method</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BaseClass</span> {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span> {
            Console.WriteLine(<span class="hljs-string">"BaseClass.Display"</span>);
        }
    }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Overrider</span> : <span class="hljs-title">BaseClass</span> {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span> { 
            Console.WriteLine(<span class="hljs-string">"Overrider.Display"</span>); 
        }
    }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Hider</span> : <span class="hljs-title">BaseClass</span> {
        <span class="hljs-function"><span class="hljs-keyword">public</span> new <span class="hljs-keyword">void</span> <span class="hljs-title">Display</span>(<span class="hljs-params"></span>)</span> { 
            Console.WriteLine(<span class="hljs-string">"Hider.Foo"</span>); 
        }
    }
</code></pre>
<p>The difference in the output of the above two classes would be as :</p>
<pre><code class="lang-csharp">  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
        Console.WriteLine(<span class="hljs-string">"Start Of the Program"</span>);
        Overrider over = <span class="hljs-keyword">new</span> Overrider();
        BaseClass b1 = over;
        over.Display(); <span class="hljs-comment">// Overrider.Foo</span>
        b1.Display(); <span class="hljs-comment">// Overrider.Foo</span>
        Hider h = <span class="hljs-keyword">new</span> Hider();
        BaseClass b2 = h;
        h.Display(); <span class="hljs-comment">// Hider.Foo</span>
        b2.Display(); <span class="hljs-comment">// BaseClass.Foo</span>

        Console.ReadKey();
 }
</code></pre>
<blockquote>
<p>NOTE: base class method could be hidden even without using the new keyword. new keyword just suppresses the compiler warning which generates without using new.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674925492570/a2c52bba-b93f-4d44-a051-4a06e31006b4.png" alt class="image--center mx-auto" /></p>
</blockquote>
<h3 id="heading-prevent-derived-class-from-overriding-virtual-method">Prevent derived class from overriding virtual method</h3>
<p>A method declared as <code>virtual</code> in the base class will be available for an override at each level of the inheritance chain.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">A</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoSomething</span>(<span class="hljs-params"></span>)</span> { }
    }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">B</span> : <span class="hljs-title">A</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoSomethingElse</span>(<span class="hljs-params"></span>)</span> {}
    }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">C</span> : <span class="hljs-title">B</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoSomething</span>(<span class="hljs-params"></span>)</span> { }
    }

<span class="hljs-comment">// class B decides not to override base class method still this method is available in class C to override.</span>
</code></pre>
<p>Now if this user wants no further availability of <code>DoSomething</code> method in classes inherited by <code>class C</code> then it could be acheived using <code>sealed</code> keyword.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674926774761/933d41a6-5e3d-4109-ae50-d19aeb9111af.png" alt /></p>
<p>That's it for this article. Thanks for reading this, please share your feedback in the comments section below.</p>
]]></content:encoded></item><item><title><![CDATA[C# static keyword]]></title><description><![CDATA[In this tutorial, we would learn about static keyword in c# programming language.
static : something which belongs to the type itself, not with an instance of the type.
The modifier in C# language applies to the following :

Variable

Methods

Class
...]]></description><link>https://thoughtcopy.com/c-static-keyword</link><guid isPermaLink="true">https://thoughtcopy.com/c-static-keyword</guid><category><![CDATA[C#]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Thu, 26 Jan 2023 08:00:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674719785056/0f249637-1ded-4486-b0bf-71fdcf3f0e8d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we would learn about <code>static</code> keyword in c# programming language.</p>
<p><code>static</code> : something which belongs to the type itself, not with an instance of the type.</p>
<p>The modifier in C# language applies to the following :</p>
<ol>
<li><p>Variable</p>
</li>
<li><p>Methods</p>
</li>
<li><p>Class</p>
</li>
<li><p>Constructor</p>
</li>
</ol>
<p>Now we would look at examples of each</p>
<h3 id="heading-static-variable"><strong>static variable</strong></h3>
<ul>
<li><p>static variables are accessed with the name of the class.</p>
</li>
<li><p>Only a single copy of the variable is created and shared among all the instances of the class.</p>
</li>
<li><p>static variable can't be accessed with the instance.</p>
</li>
<li><p><code>var</code> can not be used to declare a static variable, one must specify the type of variable after the static keyword.</p>
</li>
</ul>
<pre><code class="lang-csharp">   <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span>{
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> EmpCount = <span class="hljs-number">0</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddEmployee</span>(<span class="hljs-params"></span>)</span>{
            EmpCount++;
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>{
        Console.WriteLine(<span class="hljs-string">"Start Of the Program"</span>);
        Employee emp1 = <span class="hljs-keyword">new</span> Employee();
        emp1.AddEmployee();
        Console.WriteLine(Employee.EmpCount); <span class="hljs-comment">// output 1</span>

        Employee emp2 = <span class="hljs-keyword">new</span> Employee();
        emp2.AddEmployee();
        Console.WriteLine(Employee.EmpCount); <span class="hljs-comment">// output 2</span>
        Console.WriteLine(emp2.EmpCount); <span class="hljs-comment">// compilation error</span>
        Console.ReadKey();
    }
</code></pre>
<h3 id="heading-static-method"><strong>static method</strong></h3>
<ul>
<li><p>Similar to static variables, static methods are also accessed with the name of the class.</p>
</li>
<li><p>static methods could use both static and non-static class members.</p>
</li>
<li><p>static members are directly accessed inside the static method without a class name, and non-static members are accessed using instances.</p>
</li>
</ul>
<pre><code class="lang-csharp">        <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> FirstName;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> LastName;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Employee</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> firstName, <span class="hljs-keyword">string</span> lastName</span>)</span> {
            FirstName = firstName;
            LastName = lastName;
        }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> FullName { 
                <span class="hljs-keyword">get</span>{
                    <span class="hljs-keyword">return</span> (<span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">this</span>.FirstName}</span> <span class="hljs-subst">{<span class="hljs-keyword">this</span>.LastName}</span>"</span>);
                } 
        }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> EmpCount = <span class="hljs-number">0</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddEmployee</span>(<span class="hljs-params">Employee emp</span>)</span> {
            EmpCount++;
            Console.WriteLine(emp.FullName);
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
        Console.WriteLine(<span class="hljs-string">"Start Of the Program"</span>);
        Employee emp1 = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Smith"</span>);
        Employee.AddEmployee(emp1); <span class="hljs-comment">// "John Smith" : instance specific data</span>
        Console.WriteLine(Employee.EmpCount); <span class="hljs-comment">// 1: static data</span>
        Employee emp2 = <span class="hljs-keyword">new</span> Employee(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Bold"</span>); <span class="hljs-comment">// "John Bold" : instance specific data</span>
        Employee.AddEmployee(emp2);
        Console.WriteLine(Employee.EmpCount); <span class="hljs-comment">// 2: static data</span>
        Console.ReadKey();
    }
</code></pre>
<h3 id="heading-static-constructor"><strong>static constructor</strong></h3>
<ul>
<li><p>a static constructor is used to initialize static data or to perform an action that needs to be performed only once.</p>
</li>
<li><p>A class can have only one static constructor.</p>
</li>
<li><p>No parameter, No access modifier, No inheritance or overloading</p>
</li>
<li><p>static methods could use both static and non-static class members.</p>
</li>
<li><p>a static constructor is called automatically by the CLR. The user has no control over when a static constructor is executed in the program. static constructor runs before the instance constructor.</p>
</li>
<li><p>a static constructor is called only for a single time during program execution.</p>
</li>
</ul>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Organization</span> {        
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-title">Organization</span>(<span class="hljs-params"></span>)</span> {
            Console.WriteLine(<span class="hljs-string">"Static constrctor called"</span>);
        } 
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Organization</span>(<span class="hljs-params"></span>)</span> {
            Console.WriteLine(<span class="hljs-string">"Instance constructor called"</span>);
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
        Console.WriteLine(<span class="hljs-string">"Start Of the Program"</span>);        
        Organization org1 = <span class="hljs-keyword">new</span> Organization();
        Console.ReadKey();
    }
** Output **
Start Of the Program
Static constrctor called
Instance constructor called
</code></pre>
<h3 id="heading-static-class"><strong>static class</strong></h3>
<ul>
<li><p>static class can only contain static data members, static methods and static constructor. <code>[Error if there are non-static fields, the non-static method in static class]</code></p>
</li>
<li><p>Instances can not be created for a static class. <code>[Error if user tries to create an instance of static class]</code></p>
</li>
<li><p>static classes are sealed, they can't be inherited.</p>
</li>
<li><p>static members can be accessed directly without using the class name inside the static class.</p>
</li>
</ul>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Organization</span> {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> FounderName = <span class="hljs-string">"James Clark"</span>;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> DateTime StartDate = <span class="hljs-keyword">new</span> DateTime(<span class="hljs-number">1990</span>, <span class="hljs-number">01</span>, <span class="hljs-number">01</span>);

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> Introduction;
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-title">Organization</span>(<span class="hljs-params"></span>)</span> {
            Introduction = <span class="hljs-string">$"This organization was founded by <span class="hljs-subst">{FounderName}</span> in <span class="hljs-subst">{StartDate.Year}</span>"</span>;
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span> {
        Console.WriteLine(<span class="hljs-string">"Start Of the Program"</span>);
        Console.WriteLine(Organization.Introduction);
    }
** Output **
Start Of the Program
This organization was founded <span class="hljs-keyword">by</span> James Clark <span class="hljs-keyword">in</span> <span class="hljs-number">1990.</span>
</code></pre>
<hr />
<p>In this post, we have learned about static keyword in c#. Please share your feedback and suggestios to improve this.</p>
]]></content:encoded></item><item><title><![CDATA[Filters in ASP.NET Core]]></title><description><![CDATA[In ASP.NET core world , a user request is routed to appropriate controller and then action method to be executed. In some cases, user may need to run some code before or after during execution pipeline.
Filters allows some code to run before and afte...]]></description><link>https://thoughtcopy.com/net-core-filters</link><guid isPermaLink="true">https://thoughtcopy.com/net-core-filters</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[C#]]></category><category><![CDATA[ASP.NET]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Mon, 31 Jan 2022 04:28:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1641313026544/CDjQgGnOW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In ASP.NET core world , a user request is routed to appropriate controller and then action method to be executed. In some cases, user may need to run some code before or after during execution pipeline.</p>
<p>Filters allows some code to run before and after specific stage in request processing pipeline. ASP.NET core has provided some built in filters , user could also create custom filters as well. Filters can also avoid duplicate code, for example exception filter can consolidate the error handling.</p>
<blockquote>
<p>Built in filters are used for authorization, response caching, short circuiting the request processing pipeline.</p>
<p>Custom filters can be used for error handling, caching, configurations and logging purposes.</p>
<p>Filter pipeline runs after ASP.NET Core selects the action to be executed.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641295837759/oVdjoMi7i.png" alt="image.png" /></p>
<h2 id="heading-filter-types">Filter types</h2>
<h3 id="heading-authorization-filter">Authorization Filter</h3>
<p>Authorization filter is executed at the beginning of the request processing pipeline. This filter is used to determine whether user is authorized for request, and if not request pipeline can be short circuited.</p>
<pre><code>    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthorizationFilter</span> : <span class="hljs-type">Attribute</span>, <span class="hljs-type">IAuthorizationFilter {</span></span>
        <span class="hljs-keyword">public</span> void OnAuthorization(AuthorizationFilterContext context) {
            context.HttpContext.Response.WriteAsync(<span class="hljs-string">"  OnAuthorization  ==&gt; "</span>);
        }
    }
</code></pre><h3 id="heading-resource-filter">Resource Filter</h3>
<p>Resource filter is executed just after Authorization filter. This filter can be used to implement response caching, short circuiting the pipeline.</p>
<p><strong>OnResourceExecuting </strong>runs code before the model binding.
<strong>OnResourceExecuted</strong> runs after rest of the pipeline is executed.</p>
<pre><code>    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResourceFilter</span> :</span> Attribute, IResourceFilter  {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnResourceExecuted</span><span class="hljs-params">(ResourceExecutedContext context)</span>  </span>{
            context.HttpContext.Response.WriteAsync(<span class="hljs-string">"  OnResourceExecuted  ==&gt;  "</span>);
        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnResourceExecuting</span><span class="hljs-params">(ResourceExecutingContext context)</span> </span>{
            context.HttpContext.Response.WriteAsync(<span class="hljs-string">"  OnResourceExecuting  ==&gt;  "</span>);
        }
    }
</code></pre><h3 id="heading-action-filter">Action Filter</h3>
<p>Action filter is executed before and after the execution of action method inside controller. A custom action filter can be used to execute some reusable code block before or after execution of controller action.
Action filter can modify the arguments passed into action method or can modify the result returned from action method.</p>
<pre><code>    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ActionFilter</span> :</span> Attribute, IActionFilter {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnActionExecuted</span><span class="hljs-params">(ActionExecutedContext context)</span> </span>{
            context.HttpContext.Response.WriteAsync(<span class="hljs-string">"  OnActionExecuted  ==&gt;  "</span>);
        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnActionExecuting</span><span class="hljs-params">(ActionExecutingContext context)</span> </span>{
            context.HttpContext.Response.WriteAsync(<span class="hljs-string">"  OnActionExecuting  ==&gt;  "</span>);
        }
    }
</code></pre><h3 id="heading-exception-filter">Exception Filter</h3>
<p>Exception filter can be used to handle exception during request processing pipeline. Using this filter, exceptions can be handled globally. </p>
<pre><code>    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExceptionFilter</span> :</span> Attribute, IExceptionFilter  {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnException</span><span class="hljs-params">(ExceptionContext context)</span>  </span>{
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }
    }
</code></pre><h3 id="heading-result-filter">Result Filter</h3>
<p>This filter runs immediately before and after the execution of action result. This runs after completion of the action method.</p>
<pre><code>   <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResultFilter</span> :</span> Attribute, IResultFilter {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnResultExecuted</span><span class="hljs-params">(ResultExecutedContext context)</span> </span>{
            context.HttpContext.Response.WriteAsync(<span class="hljs-string">"  OnResultExecuted  ==&gt;  "</span>);
        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnResultExecuting</span><span class="hljs-params">(ResultExecutingContext context)</span> </span>{
            context.HttpContext.Response.WriteAsync(<span class="hljs-string">"  OnResultExecuting  ==&gt;  "</span>); 
        }
    }
</code></pre><h3 id="heading-filter-scope">Filter Scope</h3>
<p>A filter can be added to the pipeline at three levels </p>
<ul>
<li>Controller level</li>
</ul>
<p>using an attribute, Filter can be added to pipeline</p>
<pre><code>    [<span class="hljs-meta">AuthorizationFilter</span>]
    [<span class="hljs-meta">ResourceFilter</span>]
    [<span class="hljs-meta">ActionFilter</span>]
    [<span class="hljs-meta">ResultFilter</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">HomeController</span> : <span class="hljs-title">Controller</span> {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;HomeController&gt; _logger;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">HomeController</span>(<span class="hljs-params">ILogger&lt;HomeController&gt; logger</span>)</span> {
            _logger = logger;
        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> IActionResult <span class="hljs-title">Index</span>(<span class="hljs-params"></span>)</span> {
            HttpContext.Response.WriteAsync(<span class="hljs-string">"  Inside Action ==&gt;"</span>);
            <span class="hljs-keyword">return</span> View();
        }
   }
</code></pre><ul>
<li>Action Level
Using an Attribute at action level</li>
</ul>
<pre><code>        [ActionFilter]
        <span class="hljs-built_in">public</span> IActionResult <span class="hljs-keyword">Index</span>()  {
            HttpContext.Response.WriteAsync("  Inside Action ==&gt;");
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">View</span>();
        }
</code></pre><ul>
<li>Globally - For all controllers, Actions</li>
</ul>
<pre><code>        <span class="hljs-keyword">public</span> void ConfigureServices(IServiceCollection services) {
            services.AddControllersWithViews(option <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
                option.Filters.Add&lt;ResourceFilter<span class="hljs-operator">&gt;</span>();
            });
        }
</code></pre>]]></content:encoded></item><item><title><![CDATA[ASP.NET Core Middleware]]></title><description><![CDATA[An ASP.NET Core application's workflow consist of accepting request and serving response to client. With this workflow, an application has different features / functionality like authentication, error handling or logging etc. ASP.NET Core has provide...]]></description><link>https://thoughtcopy.com/net-core-middleware</link><guid isPermaLink="true">https://thoughtcopy.com/net-core-middleware</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[ASP.NET]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Deepak Kumar Jain]]></dc:creator><pubDate>Wed, 19 Jan 2022 08:09:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1642579741275/q1ok6CrUG.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>An ASP.NET Core application's workflow consist of accepting request and serving response to client. With this workflow, an application has different features / functionality like authentication, error handling or logging etc. ASP.NET Core has provided concept of middleware to implement application's features. A middleware is nothing but a C# class which is placed inside ASP.NET Core's request processing pipeline.</p>
<p>A middleware can perform below tasks :</p>
<ul>
<li>Decide whether to pass the HTTP request to the next middleware in request processing pipeline.</li>
<li>Can modify the request / response before / after passing it to next middleware in pipeline.</li>
</ul>
<h3 id="heading-configuring-the-middleware">Configuring the middleware</h3>
<p>Middleware components are configured in Configure method of Startup.cs file. ASP.NET Core has provided some built-in middleware. Middleware can also be added via Nuget package manager or custom middleware can be added.</p>
<p>Below is the Startup.cs file's Configure method. All the middleware shown in this file are built-in middleware</p>
<pre><code><span class="hljs-keyword">public</span> void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    <span class="hljs-keyword">if</span> (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    <span class="hljs-keyword">else</span>
    {
        app.UseExceptionHandler(<span class="hljs-string">"/Home/Error"</span>);
        <span class="hljs-comment">// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.</span>
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
    {
        endpoints.MapControllerRoute(
            name: <span class="hljs-string">"default"</span>,
            pattern: <span class="hljs-string">"{controller=Home}/{action=Index}/{id?}"</span>);
    });
}
</code></pre><h3 id="heading-middleware-ordering">Middleware ordering</h3>
<p>Middleware components are executed in the order they are added to the pipeline and care should be taken to add the middleware in the right order otherwise the application may not function as expected. This ordering is critical for security, performance, and functionality.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1642578918109/dq7IYJ8Hj.png" alt="image.png" /></p>
<h3 id="heading-adding-inline-middleware-using-appuse-and-apprun-method">Adding inline middleware using app.Use and app.Run method</h3>
<p>Inline middleware can be added using app.use or app.Run method. </p>
<blockquote>
<p>Middleware defined using app.Use may call next middleware component in the pipeline. Middlware defined using app.Run will never call subsequent middleware.</p>
</blockquote>
<pre><code><span class="hljs-keyword">public</span> void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
    {
        await context.Response.WriteAsync(<span class="hljs-string">"Middleware 1 using app.Use()"</span>);
        await next();
    });

    app.Use(async (context, next) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
    {
        await context.Response.WriteAsync(<span class="hljs-string">"Middleware 2 using app.Use()"</span>);
        await next();
    });

    app.Run(async context <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
    {
        await context.Response.WriteAsync(<span class="hljs-string">"Middleware 3 using app.Run()"</span>);
        <span class="hljs-comment">// Short circuiting the pipeline</span>
    });

    <span class="hljs-comment">// This will never be called</span>
    app.Use(async (context, next) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
    {
        await context.Response.WriteAsync(<span class="hljs-string">"Middleware 4 using app.Use()"</span>);
        await next();
    });
}
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1642576561844/EGK64I54U.png" alt="image.png" /></p>
<h3 id="heading-adding-custom-middleware">Adding custom middleware</h3>
<p>below is an example where a middleware is created to log the incoming request's http method</p>
<pre><code><span class="hljs-keyword">public</span> class LogRequestMethodMiddleware
{
    <span class="hljs-keyword">private</span> readonly RequestDelegate _next;
    <span class="hljs-keyword">private</span> readonly ILogger<span class="hljs-operator">&lt;</span>LogRequestMethodMiddleware<span class="hljs-operator">&gt;</span> _logger;
    <span class="hljs-keyword">public</span> LogRequestMethodMiddleware(RequestDelegate next, 
            ILogger<span class="hljs-operator">&lt;</span>LogRequestMethodMiddleware<span class="hljs-operator">&gt;</span> logger)
    {
        _next <span class="hljs-operator">=</span> next;
        _logger <span class="hljs-operator">=</span> logger;
    }

    <span class="hljs-keyword">public</span> async Task InvokeAsync (HttpContext context)
    {
        _logger.LogInformation(context.Request.Method);
        await _next(context);
    }
}
</code></pre><p>Inside Startup.cs file </p>
<pre><code><span class="hljs-keyword">public</span> void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware&lt;LogRequestMethodMiddleware<span class="hljs-operator">&gt;</span>();
    app.Run(async context <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
    {
        await context.Response.WriteAsync(<span class="hljs-string">"\n Adding custom middleware"</span>);
    });
}
</code></pre><h3 id="heading-built-in-middleware">Built-in Middleware</h3>
<p>ASP.NET Core has some built-in middleware for common application scenario :</p>
<ul>
<li>Exception/error handling</li>
<li>HTTPS Redirection Middleware (UseHttpsRedirection) redirects HTTP requests to HTTPS.</li>
<li>Static File Middleware (UseStaticFiles) returns static files and short-circuits further request processing.</li>
<li>Cookie Policy Middleware (UseCookiePolicy) conforms the app to the EU General Data Protection Regulation (GDPR) regulations.</li>
<li>Routing Middleware (UseRouting) to route requests.</li>
<li>Authentication Middleware (UseAuthentication) attempts to authenticate the user before they're allowed access to secure resources.</li>
<li>Authorization Middleware (UseAuthorization) authorizes a user to access secure resources.</li>
<li>Session Middleware (UseSession) establishes and maintains session state. If the app uses session state, call Session Middleware after Cookie Policy Middleware and before MVC Middleware.</li>
<li>Endpoint Routing Middleware (UseEndpoints with MapRazorPages) to add Razor Pages endpoints to the request pipeline.</li>
</ul>
]]></content:encoded></item></channel></rss>