<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alifiyakapasi on Medium]]></title>
        <description><![CDATA[Stories by Alifiyakapasi on Medium]]></description>
        <link>https://medium.com/@alifiyakapasi07?source=rss-c7db647e0e86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2LflSmTKD9bLufSQ</url>
            <title>Stories by Alifiyakapasi on Medium</title>
            <link>https://medium.com/@alifiyakapasi07?source=rss-c7db647e0e86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:32:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alifiyakapasi07/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Production-Ready Logging in .NET Using Serilog and Datadog]]></title>
            <link>https://alifiyakapasi07.medium.com/production-ready-logging-in-net-using-serilog-and-datadog-3c9725753b5c?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c9725753b5c</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-06-24T02:31:01.089Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging is one of the most important aspects of building production-ready applications. While simple text logs may be sufficient during development, modern distributed systems require richer and more searchable logging solutions.</p><p>This is where <strong>structured logging</strong> comes in.</p><p>Structured logging allows applications to emit logs as structured data rather than plain text, making them easier to search, filter, and analyze.</p><p>In this article, we’ll learn how to implement structured logging in ASP.NET Core and send logs to Datadog for centralized monitoring and troubleshooting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*271LEUS_h6HROgBpoi5S2A.png" /></figure><h3>What is Structured Logging?</h3><p>Traditional logs are often written as plain text:</p><pre>User John logged in successfully.</pre><p>While readable, searching for specific users or events becomes difficult.</p><p>Structured logging stores additional metadata:</p><pre>{<br>  &quot;Message&quot;: &quot;User logged in successfully&quot;,<br>  &quot;UserName&quot;: &quot;John&quot;,<br>  &quot;UserId&quot;: 101,<br>  &quot;Timestamp&quot;: &quot;2026-06-23T10:00:00Z&quot;<br>}</pre><p>This makes it possible to:</p><ul><li>Filter logs by user</li><li>Search specific properties</li><li>Build dashboards</li><li>Create alerts</li><li>Correlate events across services</li></ul><h3>Why Use Datadog?</h3><p>Datadog is a cloud-based observability platform that provides:</p><ul><li>Log Management</li><li>Application Performance Monitoring (APM)</li><li>Infrastructure Monitoring</li><li>Dashboards</li><li>Alerting</li><li>Distributed Tracing</li></ul><p>Instead of manually reviewing log files, developers can analyze logs through a centralized platform.</p><blockquote>Prerequisites</blockquote><p>Before starting, ensure you have:</p><ul><li>.NET 8 SDK</li><li>ASP.NET Core Web API project</li><li>Datadog account</li><li>Datadog Agent installed locally</li></ul><h4>Create a Sample ASP.NET Core Project</h4><p>Create a new Web API project:</p><pre>dotnet new webapi -n DatadogLoggingDemo</pre><p>Navigate to the project:</p><pre>cd DatadogLoggingDemo</pre><h3>Install Serilog Packages</h3><p>Serilog is one of the most popular structured logging libraries for .NET.</p><blockquote>Install packages:</blockquote><pre>dotnet add package Serilog.AspNetCore</pre><pre>dotnet add package Serilog.Sinks.Console</pre><pre>dotnet add package Serilog.Formatting.Compact</pre><blockquote>Configure Serilog</blockquote><p>Inside Program.cs:</p><pre>using Serilog;<br><br>Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();<br><br>builder.Host.UseSerilog();</pre><p>Now all logs will flow through Serilog.</p><h4>Writing Structured Logs</h4><p>Instead of string concatenation:</p><pre>logger.LogInformation($&quot;User {userName} logged in&quot;);</pre><p>Use structured properties:</p><pre>logger.LogInformation(&quot;User {UserName} logged in&quot;, userName);</pre><p>Benefits:</p><ul><li>Searchable properties</li><li>Better performance</li><li>Cleaner logs</li></ul><h4>Logging Multiple Properties</h4><pre>logger.LogInformation(<br>    &quot;Order created for customer {CustomerId} with amount {Amount}&quot;,<br>    customerId,<br>    amount);</pre><p>Datadog can index these properties automatically.</p><blockquote>Example Endpoint</blockquote><pre>app.MapGet(&quot;/orders&quot;,<br>(<br>    ILogger&lt;Program&gt; logger) =&gt;<br>{<br>    int customerId = 101;<br>    decimal amount = 2500;<br><br>    logger.LogInformation(<br>            &quot;Order created for customer {CustomerId} with amount {Amount}&quot;,<br>            customerId,<br>            amount);<br>    <br>    return Results.Ok();<br>});</pre><h4>Enable JSON Logging</h4><p>Structured logs are typically stored as JSON.</p><p>Update Serilog configuration:</p><pre>Log.Logger =<br>    new LoggerConfiguration()<br>    .WriteTo.Console(<br>        new Serilog.Formatting.Compact<br>        .RenderedCompactJsonFormatter())<br>    .CreateLogger();</pre><p>Example output:</p><pre>{<br>  &quot;@t&quot;:&quot;2026-06-23T09:15:00Z&quot;,<br>  &quot;@m&quot;:&quot;Order created for customer 101&quot;,<br>  &quot;CustomerId&quot;:101,<br>  &quot;Amount&quot;:2500<br>}</pre><h3>Installing Datadog Agent</h3><p>Download and install the Datadog Agent on your machine.</p><p>Configure:</p><pre>logs_enabled: true</pre><p>Enable log collection:</p><pre>logs:<br>  - type: file<br>    path: &quot;C:\\logs\\*.log&quot;<br>    service: aspnetcore-api<br>    source: csharp</pre><p>Restart the Datadog Agent after making changes.</p><h4>Configure Application Log Files</h4><p>Add file logging:</p><pre>Log.Logger =<br>    new LoggerConfiguration()<br>    .WriteTo.File(<br>        &quot;logs/app.log&quot;,<br>        rollingInterval:<br>            RollingInterval.Day)<br>    .CreateLogger();</pre><p>Datadog Agent will automatically collect logs from this location.</p><h4>Enrich Logs with Context</h4><p>Structured logging becomes more powerful when additional metadata is included.</p><pre>Log.Logger =<br>    new LoggerConfiguration()<br>    .Enrich.WithProperty(<br>        &quot;Application&quot;,<br>        &quot;OrderApi&quot;)<br>    .Enrich.WithProperty(<br>        &quot;Environment&quot;,<br>        &quot;Production&quot;)<br>    .WriteTo.Console()<br>    .CreateLogger();</pre><p>These properties appear in every log entry.</p><h4>Logging Exceptions</h4><p>Always include exception details.</p><pre>try<br>{<br>    throw new Exception(<br>        &quot;Payment failed&quot;);<br>}<br>catch (Exception ex)<br>{<br>    logger.LogError(<br>        ex,<br>        &quot;Payment processing failed&quot;);<br>}</pre><p>Datadog automatically extracts stack traces and exception details.</p><h4>Correlation IDs</h4><p>Correlation IDs help track requests across multiple services.</p><pre>logger.LogInformation(<br>    &quot;Request processed with CorrelationId {CorrelationId}&quot;,<br>    correlationId);</pre><p>This becomes extremely useful in microservices architectures.</p><h3>Best Practices</h3><blockquote>Log Structured Data</blockquote><p>Prefer:</p><pre>logger.LogInformation(<br>    &quot;User {UserId} logged in&quot;,<br>    userId);</pre><p>Instead of:</p><pre>logger.LogInformation(<br>    $&quot;User {userId} logged in&quot;);</pre><h4>Avoid Logging Sensitive Information</h4><p>Never log:</p><ul><li>Passwords</li><li>Credit card numbers</li><li>API keys</li><li>Authentication tokens</li></ul><h4>Use Appropriate Log Levels</h4><blockquote>Information</blockquote><pre>logger.LogInformation(&quot;User logged in&quot;);</pre><blockquote>Warning</blockquote><pre>logger.LogWarning(&quot;Payment delayed&quot;);</pre><blockquote>Error</blockquote><pre>logger.LogError(exception,&quot;Payment failed&quot;);</pre><h4>Add Contextual Properties</h4><p>Useful properties include:</p><ul><li>UserId</li><li>RequestId</li><li>CorrelationId</li><li>Environment</li><li>Service Name</li></ul><p>These improve filtering and troubleshooting.</p><h3>Benefits of Structured Logging with Datadog</h3><p>By combining Serilog and Datadog, teams gain:</p><ul><li>Faster troubleshooting</li><li>Better observability</li><li>Centralized log management</li><li>Powerful search capabilities</li><li>Alerting and dashboards</li><li>Easier production monitoring</li></ul><blockquote>Conclusion</blockquote><p>Structured logging is a critical part of modern application development. Instead of relying on plain text logs, structured logging enables powerful searching, filtering, and monitoring capabilities.</p><p>By integrating Serilog with Datadog, ASP.NET Core applications can provide rich observability, making it easier to diagnose issues, monitor application health, and improve overall reliability.</p><p>As applications grow in complexity, structured logging becomes not just a best practice — but a necessity.</p><p><a href="https://medium.com/u/acdb626ac40c">Datadog</a></p><p><strong>Happy Coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c9725753b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core + MongoDB: Building Modern APIs]]></title>
            <link>https://alifiyakapasi07.medium.com/asp-net-core-mongodb-building-modern-apis-fe587301aefd?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe587301aefd</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-06-19T02:31:01.199Z</atom:updated>
            <content:encoded><![CDATA[<p>When building modern applications, choosing the right database is an important decision. While relational databases like SQL Server remain popular, many applications benefit from the flexibility and scalability of NoSQL databases.</p><p>One of the most popular NoSQL databases is <strong>MongoDB</strong>.</p><p>In this article, we’ll learn how to integrate MongoDB with ASP.NET Core, perform CRUD operations, and build a clean, maintainable data access layer using modern .NET 8 practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdTQdoMWo2QYEduLHSTGZw.png" /></figure><h3>What is MongoDB?</h3><p>MongoDB is a document-oriented NoSQL database that stores data in flexible JSON-like documents called BSON (Binary JSON).</p><p>Unlike traditional relational databases:</p><ul><li>No fixed schema is required</li><li>Data is stored as documents</li><li>Horizontal scaling is easier</li><li>Ideal for rapidly evolving applications</li></ul><p>Example MongoDB document:</p><pre>{<br>  &quot;_id&quot;: &quot;665c2f1e2a8d8b2c5f7e1234&quot;,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;age&quot;: 28<br>}</pre><h4>Why Use MongoDB with ASP.NET Core?</h4><p>MongoDB is a great choice when:</p><ul><li>Application requirements change frequently</li><li>Flexible schemas are needed</li><li>Large amounts of data must be stored</li><li>High scalability is required</li><li>JSON-based data models fit naturally</li></ul><p>Common use cases include:</p><ul><li>E-commerce platforms</li><li>Content management systems</li><li>IoT applications</li><li>Event logging systems</li><li>Real-time analytics</li></ul><h4>Prerequisites</h4><p>Before starting, make sure you have:</p><ul><li>.NET 8 SDK installed</li><li>MongoDB Community Edition installed locally</li><li>Visual Studio 2022 or VS Code</li><li>Basic knowledge of ASP.NET Core</li></ul><h4>Install MongoDB Driver</h4><p>Create a new ASP.NET Core Web API project.</p><p>Install MongoDB Driver:</p><pre>dotnet add package MongoDB.Driver</pre><p>This package provides everything needed to communicate with MongoDB.</p><h4>Configure MongoDB Settings</h4><p>Add configuration inside appsettings.json:</p><pre>{<br>  &quot;MongoDbSettings&quot;: {<br>    &quot;ConnectionString&quot;: &quot;mongodb://localhost:27017&quot;,<br>    &quot;DatabaseName&quot;: &quot;StudentDb&quot;,<br>    &quot;CollectionName&quot;: &quot;Students&quot;<br>  }<br>}</pre><blockquote>Create Configuration Class</blockquote><pre>public class MongoDbSettings<br>{<br>    public string ConnectionString { get; set; } = string.Empty;<br>    public string DatabaseName { get; set; } = string.Empty;<br>    public string CollectionName { get; set; } = string.Empty;<br>}</pre><blockquote>Create the Model</blockquote><p>Let’s create a Student entity.</p><pre>using MongoDB.Bson;<br>using MongoDB.Bson.Serialization.Attributes;<br><br>public class Student<br>{<br>    [BsonId]<br>    [BsonRepresentation(BsonType.ObjectId)]<br>    public string Id { get; set; } = string.Empty;<br>    public string Name { get; set; } = string.Empty;<br>    public string Email { get; set; } = string.Empty;<br>    public int Age { get; set; }<br>}</pre><blockquote>Register Configuration</blockquote><p>Inside Program.cs:</p><pre>builder.Services.Configure&lt;MongoDbSettings&gt;(<br>    builder.Configuration.GetSection(<br>        &quot;MongoDbSettings&quot;));</pre><blockquote>Create MongoDB Service</blockquote><p>Create a service responsible for database operations.</p><pre>using Microsoft.Extensions.Options;<br>using MongoDB.Driver;<br><br>public class StudentService<br>{<br>    private readonly IMongoCollection&lt;Student&gt; _students;<br>    <br>public StudentService(<br>        IOptions&lt;MongoDbSettings&gt; settings)<br>    {<br>        var mongoClient =<br>            new MongoClient(<br>                settings.Value.ConnectionString);<br>        var database =<br>            mongoClient.GetDatabase(<br>                settings.Value.DatabaseName);<br>        _students =<br>            database.GetCollection&lt;Student&gt;(<br>                settings.Value.CollectionName);<br>    }<br>}</pre><blockquote>Get All Students</blockquote><p>Add a method:</p><pre>public async Task&lt;List&lt;Student&gt;&gt;<br>    GetAsync()<br>{<br>    return await _students<br>        .Find(_ =&gt; true)<br>        .ToListAsync();<br>}</pre><blockquote>Get Student by Id</blockquote><pre>public async Task&lt;Student?&gt;<br>    GetByIdAsync(string id)<br>{<br>    return await _students<br>        .Find(x =&gt; x.Id == id)<br>        .FirstOrDefaultAsync();<br>}</pre><blockquote>Insert a Student</blockquote><pre>public async Task CreateAsync(<br>    Student student)<br>{<br>    await _students<br>        .InsertOneAsync(student);<br>}</pre><blockquote>Update a Student</blockquote><pre>public async Task UpdateAsync(<br>    string id,<br>    Student updatedStudent)<br>{<br>    await _students.ReplaceOneAsync(<br>        x =&gt; x.Id == id,<br>        updatedStudent);<br>}</pre><blockquote>Delete a Student</blockquote><pre>public async Task DeleteAsync(string id)<br>{<br>    await _students.DeleteOneAsync(<br>        x =&gt; x.Id == id);<br>}</pre><h4>Register Service</h4><p>Program.cs:</p><pre>builder.Services.AddSingleton&lt;<br>    StudentService&gt;();</pre><h4>Create API Endpoints</h4><p>Get all students:</p><pre>app.MapGet(&quot;/students&quot;,<br>async (StudentService service) =&gt;<br>{<br>    return await service.GetAsync();<br>});</pre><blockquote>Create student:</blockquote><pre>app.MapPost(&quot;/students&quot;,<br>async (<br>    Student student,<br>    StudentService service) =&gt;<br>{<br>    await service.CreateAsync(student);<br><br>    return Results.Created(<br>          $&quot;/students/{student.Id}&quot;,<br>        student);<br>});</pre><blockquote>Get student by Id:</blockquote><pre>app.MapGet(&quot;/students/{id}&quot;,<br>async (<br>    string id,<br>    StudentService service) =&gt;<br>{<br>    return await service.GetByIdAsync(id)<br>        is Student student<br>        ? Results.Ok(student)<br>        : Results.NotFound();<br>});</pre><blockquote>Delete student:</blockquote><pre>app.MapDelete(&quot;/students/{id}&quot;,<br>async (<br>    string id,<br>    StudentService service) =&gt;<br>{<br>    await service.DeleteAsync(id);<br><br>    return Results.NoContent();<br>});</pre><h4>Testing with Swagger</h4><p>Run the application:</p><pre>dotnet run</pre><p>Navigate to:</p><pre>https://localhost:5001/swagger</pre><p>You can now:</p><ul><li>Create students</li><li>Retrieve students</li><li>Update students</li><li>Delete students</li></ul><p>directly from Swagger UI.</p><h3>Best Practices</h3><h4>Use Repository Pattern</h4><p>For larger projects:</p><pre>IStudentRepository<br>StudentRepository</pre><p>This improves maintainability and testing.</p><h4>Create Indexes</h4><p>Indexes improve query performance significantly.</p><p>Example:</p><pre>await _students.Indexes.CreateOneAsync(<br>    new CreateIndexModel&lt;Student&gt;(<br>        Builders&lt;Student&gt;.IndexKeys<br>            .Ascending(x =&gt; x.Email)));</pre><h4>Validate Input</h4><p>Always validate incoming requests using:</p><ul><li>Data Annotations</li><li>FluentValidation</li></ul><p>before storing data.</p><h4>Store Connection Strings Securely</h4><p>Avoid storing sensitive values directly in source code.</p><p>Use:</p><ul><li>User Secrets</li><li>Azure Key Vault</li><li>Environment Variables</li></ul><h3>Common Use Cases</h3><p>MongoDB works exceptionally well for:</p><ul><li>Product catalogs</li><li>User profiles</li><li>Event tracking</li><li>Blog systems</li><li>Chat applications</li><li>Audit logs</li><li>Analytics platforms</li></ul><h3>MongoDB vs SQL Server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LVVI3orze2ZNn2_DKHAnw.png" /></figure><blockquote><strong>Conclusion</strong></blockquote><p>MongoDB integrates seamlessly with ASP.NET Core and provides a powerful solution for applications that require flexible data structures and high scalability.</p><p>Using the MongoDB Driver, dependency injection, and a clean service layer, you can quickly build production-ready APIs that perform CRUD operations efficiently.</p><p>Whether you’re building a startup MVP, an analytics platform, or a modern web application, MongoDB is a valuable tool in every .NET developer’s toolkit.</p><p><a href="https://medium.com/u/db5cd12199bd">MongoDB</a>, <a href="https://medium.com/u/5e8a6fdc5b72">Microsoft Edge Developers</a></p><p><strong>Happy Coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe587301aefd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles Every .NET Developer Should Know]]></title>
            <link>https://alifiyakapasi07.medium.com/solid-principles-every-net-developer-should-know-e381de4fa91a?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/e381de4fa91a</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 02:31:00 GMT</pubDate>
            <atom:updated>2026-06-16T02:31:00.809Z</atom:updated>
            <content:encoded><![CDATA[<p>Writing code that works is one thing. Writing code that is maintainable, scalable, and easy to extend is another.</p><p>As applications grow, tightly coupled and poorly designed code becomes difficult to modify and test. This is where the <strong>SOLID Principles</strong> come into play.</p><p>SOLID is a set of five object-oriented design principles introduced by Robert C. Martin (Uncle Bob) that help developers build flexible and maintainable software.</p><p>In this article, we’ll explore each SOLID principle with practical C# examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5MFygh73feOQwH8U2ipdg.png" /></figure><h3>What is SOLID?</h3><p>SOLID is an acronym for:</p><ul><li><strong>S</strong> — Single Responsibility Principle (SRP)</li><li><strong>O</strong> — Open/Closed Principle (OCP)</li><li><strong>L</strong> — Liskov Substitution Principle (LSP)</li><li><strong>I</strong> — Interface Segregation Principle (ISP)</li><li><strong>D</strong> — Dependency Inversion Principle (DIP)</li></ul><p>Let’s examine each one.</p><h3>1. Single Responsibility Principle (SRP)</h3><h4>Definition</h4><blockquote><em>A class should have only one reason to change.</em></blockquote><p>A class should focus on a single responsibility.</p><h4>Bad Example</h4><pre>public class UserService<br>{<br>    public void SaveUser(User user)<br>    {<br>        // Save user to database<br>    }<br>    <br>    public void SendWelcomeEmail(User user)<br>    {<br>            // Send email<br>     }<br>}</pre><p>This class has two responsibilities:</p><ul><li>User management</li><li>Email sending</li></ul><p>If email requirements change, the class changes.</p><h4>Good Example</h4><pre>public class UserService<br>{<br>    public void SaveUser(User user)<br>    {<br>        // Save user<br>    }<br>}</pre><pre>public class EmailService<br>{<br>    public void SendWelcomeEmail(User user)<br>    {<br>        // Send email<br>    }<br>}</pre><p>Now each class has one responsibility.</p><h4>Benefits</h4><ul><li>Easier maintenance</li><li>Better testing</li><li>Improved readability</li></ul><h3>2. Open/Closed Principle (OCP)</h3><h4>Definition</h4><blockquote><em>Software entities should be open for extension but closed for modification.</em></blockquote><p>You should be able to add new functionality without changing existing code.</p><h4>Bad Example</h4><pre>public class DiscountCalculator<br>{<br>    public decimal Calculate(string customerType)<br>    {<br>        if (customerType == &quot;Regular&quot;)<br>            return 10;<br><br>        if (customerType == &quot;Premium&quot;)<br>                    return 20;<br>                return 0;<br>    }<br>}</pre><p>Every new customer type requires modifying existing code.</p><h4>Good Example</h4><pre>public interface IDiscountStrategy<br>{<br>    decimal Calculate();<br>}</pre><pre>public class RegularCustomerDiscount : IDiscountStrategy<br>{<br>    public decimal Calculate() =&gt; 10;<br>}<br><br>public class PremiumCustomerDiscount : IDiscountStrategy<br>{<br>    public decimal Calculate() =&gt; 20;<br>}</pre><h4>Usage:</h4><pre>IDiscountStrategy strategy =  new PremiumCustomerDiscount();<br><br>decimal discount = strategy.Calculate();</pre><p>Adding new discount types requires creating a new class instead of modifying existing ones.</p><h4>Benefits</h4><ul><li>Easier feature additions</li><li>Reduced risk of breaking existing code</li></ul><h3>3. Liskov Substitution Principle (LSP)</h3><h4>Definition</h4><blockquote><em>Derived classes should be replaceable with their base classes without affecting correctness.</em></blockquote><h4>Bad Example</h4><pre>public class Bird<br>{<br>    public virtual void Fly()<br>    {<br>    }<br>}</pre><pre>public class Penguin : Bird<br>{<br>    public override void Fly()<br>    {<br>        throw new NotImplementedException();<br>    }<br>}</pre><p>Penguins cannot fly.</p><p>This breaks expectations.</p><h4>Good Example</h4><pre>public abstract class Bird<br>{<br>}</pre><pre>public interface IFlyable<br>{<br>    void Fly();<br>}<br><br>public class Eagle : Bird, IFlyable<br>{<br>    public void Fly()<br>    {<br>    }<br>}<br><br>public class Penguin : Bird<br>{<br>}</pre><p>Now only birds that can fly implement IFlyable.</p><h4>Benefits</h4><ul><li>Better inheritance hierarchy</li><li>More predictable behavior</li></ul><h3>4. Interface Segregation Principle (ISP)</h3><h4>Definition</h4><blockquote><em>Clients should not be forced to depend on interfaces they do not use.</em></blockquote><h4>Bad Example</h4><pre>public interface IWorker<br>{<br>    void Work();<br><br>    void Eat();<br>}</pre><p>Now every implementation must support both methods.</p><pre>public class Robot : IWorker<br>{<br>    public void Work()<br>    {<br>    }<br><br>    public void Eat()<br>    {<br>        throw new NotImplementedException();<br>    }<br>}</pre><p>A robot doesn’t eat.</p><h4>Good Example</h4><pre>public interface IWorkable<br>{<br>    void Work();<br>}</pre><pre>public interface IEatable<br>{<br>    void Eat();<br>}</pre><p>Implement only what is needed.</p><pre>public class Human : IWorkable, IEatable<br>{<br>    public void Work()<br>    {<br>    }<br><br>    public void Eat()<br>    {<br>    }<br>}</pre><pre>public class Robot : IWorkable<br>{<br>    public void Work()<br>    {<br>    }<br>}</pre><h4>Benefits</h4><ul><li>Cleaner interfaces</li><li>Reduced unnecessary dependencies</li></ul><h3>5. Dependency Inversion Principle (DIP)</h3><h4>Definition</h4><blockquote><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em></blockquote><h4>Bad Example</h4><pre>public class EmailService<br>{<br>    public void Send(string message)<br>    {<br>    }<br>}</pre><pre>public class NotificationService<br>{<br>    private readonly EmailService _emailService =<br>        new EmailService();<br>    <br>    public void Notify(string message)<br>    {<br>        _emailService.Send(message);<br>    }<br>}</pre><p>NotificationService is tightly coupled to EmailService.</p><h4>Good Example</h4><pre>public interface IMessageService<br>{<br>    void Send(string message);<br>}</pre><p>Implementation:</p><pre>public class EmailService : IMessageService<br>{<br>    public void Send(string message)<br>    {<br>    }<br>}</pre><p>Consumer:</p><pre>public class NotificationService<br>{<br>    private readonly IMessageService _messageService;<br><br>    public NotificationService(IMessageService messageService)<br>    {<br>        _messageService = messageService;<br>    }<br>   <br>    public void Notify(string message)<br>    {<br>        _messageService.Send(message);<br>    }<br>}</pre><p>Registration in ASP.NET Core:</p><pre>builder.Services.AddScoped&lt;IMessageService,EmailService&gt;();</pre><h4>Benefits</h4><ul><li>Easier testing</li><li>Better flexibility</li><li>Supports dependency injection</li></ul><h3>Real-World Example in ASP.NET Core</h3><p>Most ASP.NET Core applications naturally follow SOLID principles.</p><p>For example:</p><pre>public interface IUserRepository<br>{<br>    Task&lt;User&gt; GetByIdAsync(int id);<br>}</pre><pre>public class UserRepository: IUserRepository<br>{<br>}<br><br>public class UserService<br>{<br>    private readonly IUserRepository _repository;<br>    <br>    public UserService( IUserRepository repository)<br>    {<br>        _repository = repository;<br>    }<br>}</pre><h4>Benefits:</h4><ul><li>Business logic separated from data access</li><li>Easy unit testing</li><li>Easy replacement of implementations</li></ul><h3>Common Mistakes Developers Make</h3><h4>Overusing Inheritance</h4><p>Prefer composition when possible.</p><h4>Creating Massive Interfaces</h4><p>Keep interfaces small and focused.</p><h4>Tight Coupling</h4><p>Depend on abstractions instead of concrete classes.</p><h4>Ignoring Dependency Injection</h4><p>Modern .NET applications provide built-in dependency injection — use it.</p><h3>Why SOLID Matters</h3><p>Following SOLID principles helps you:</p><ul><li>Write cleaner code</li><li>Improve maintainability</li><li>Reduce technical debt</li><li>Simplify testing</li><li>Scale applications more effectively</li><li>Collaborate better with teams</li></ul><blockquote><strong>Conclusion</strong></blockquote><p>SOLID principles are not just academic concepts — they solve real-world software design problems.</p><p>By applying:</p><ul><li>Single Responsibility Principle</li><li>Open/Closed Principle</li><li>Liskov Substitution Principle</li><li>Interface Segregation Principle</li><li>Dependency Inversion Principle</li></ul><p>you can create applications that are easier to maintain, test, and extend.</p><p>The next time you design a class or service in C#, ask yourself:</p><p><strong>“Am I following SOLID principles?”</strong></p><p>Small improvements today can save countless hours of refactoring tomorrow.</p><p><strong>Happy Coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e381de4fa91a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Email Integration in ASP.NET Core with SendGrid]]></title>
            <link>https://alifiyakapasi07.medium.com/email-integration-in-asp-net-core-with-sendgrid-c43cb213e3a9?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/c43cb213e3a9</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 04:31:02 GMT</pubDate>
            <atom:updated>2026-06-13T10:12:25.957Z</atom:updated>
            <content:encoded><![CDATA[<p>Email functionality is a critical feature in modern applications. Whether you’re sending account verification links, password reset emails, order confirmations, or notifications, having a reliable email delivery service is essential.</p><p>Instead of managing SMTP servers yourself, services like SendGrid make email delivery simple, scalable, and reliable.</p><p>In this article, we’ll learn how to integrate SendGrid into an ASP.NET Core application using modern .NET 8 practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HYuQNTlORvPsAP2Zsfhzw.png" /></figure><h3>Why Use SendGrid?</h3><p>SendGrid is a cloud-based email delivery platform trusted by developers worldwide.</p><p>Some benefits include:</p><ul><li>High email deliverability</li><li>Easy API integration</li><li>Email analytics and tracking</li><li>Template support</li><li>Scalable infrastructure</li><li>Free tier available for testing</li></ul><blockquote>Prerequisites</blockquote><p>Before getting started, ensure you have:</p><ul><li>.NET 8 SDK installed</li><li>Visual Studio 2022 or VS Code</li><li>A SendGrid account</li><li>Basic knowledge of ASP.NET Core</li></ul><h4>Create a SendGrid Account</h4><p>Sign up for a SendGrid account and create an API Key.</p><p>Navigate to:</p><p><strong>Settings → API Keys → Create API Key</strong></p><p>Choose:</p><ul><li>Restricted Access (Recommended)</li><li>Mail Send Permission</li></ul><p>Copy the generated API Key and store it securely.</p><h4>Install the SendGrid Package</h4><p>Using .NET CLI:</p><pre>dotnet add package SendGrid</pre><p>Or Package Manager Console:</p><pre>Install-Package SendGrid</pre><h4>Store Configuration in appsettings.json</h4><p>Add the following configuration:</p><pre>{<br>  &quot;SendGrid&quot;: {<br>    &quot;ApiKey&quot;: &quot;YOUR_API_KEY&quot;,<br>    &quot;FromEmail&quot;: &quot;noreply@yourdomain.com&quot;,<br>    &quot;FromName&quot;: &quot;My Application&quot;<br>  }<br>}</pre><p>Never commit real API keys to source control.</p><p>For production applications, use:</p><ul><li>User Secrets</li><li>Azure Key Vault</li><li>Environment Variables</li></ul><h4>Create a Configuration Model</h4><p>Create a class named SendGridSettings.</p><pre>public class SendGridSettings<br>{<br>    public string ApiKey { get; set; } = string.Empty;<br>    public string FromEmail { get; set; } = string.Empty;<br>    public string FromName { get; set; } = string.Empty;<br>}</pre><h4>Register Configuration</h4><p>Inside Program.cs:</p><pre>builder.Services.Configure&lt;SendGridSettings&gt;(<br>    builder.Configuration.GetSection(&quot;SendGrid&quot;));</pre><h4>Create an Email Service</h4><p>Create an interface:</p><pre>public interface IEmailService<br>{<br>    Task SendEmailAsync(<br>        string toEmail,<br>        string subject,<br>        string htmlContent);<br>}</pre><h4>Implement the Service</h4><p>Create SendGridEmailService.cs.</p><pre>using Microsoft.Extensions.Options;<br>using SendGrid;<br>using SendGrid.Helpers.Mail;<br><br>public class SendGridEmailService : IEmailService<br>{<br>    private readonly SendGridSettings _settings;<br>    public SendGridEmailService(<br>        IOptions&lt;SendGridSettings&gt; settings)<br>    {<br>        _settings = settings.Value;<br>    }<br>    public async Task SendEmailAsync(<br>        string toEmail,<br>        string subject,<br>        string htmlContent)<br>    {<br>        var client = new SendGridClient(_settings.ApiKey);<br><br>        var from = new EmailAddress(_settings.FromEmail, _settings.FromName);<br>        var to = new EmailAddress(toEmail);<br>        var message =<br>            MailHelper.CreateSingleEmail(<br>                from,<br>                to,<br>                subject,<br>                plainTextContent: null,<br>                htmlContent);<br><br>        await client.SendEmailAsync(message);<br>    }<br>}</pre><h4>Register the Service</h4><p>In Program.cs:</p><pre>builder.Services.AddScoped&lt;IEmailService,<br>    SendGridEmailService&gt;();</pre><h4>Create a Test Endpoint</h4><p>Let’s create an endpoint that sends an email.</p><pre>app.MapPost(&quot;/send-email&quot;,<br>async (<br>    IEmailService emailService) =&gt;<br>{<br>    await emailService.SendEmailAsync(<br>        &quot;recipient@example.com&quot;,<br>        &quot;Welcome!&quot;,<br>        &quot;&lt;h2&gt;Hello from ASP.NET Core&lt;/h2&gt;&quot;);<br>  <br>  return Results.Ok(<br>        &quot;Email sent successfully.&quot;);<br>});</pre><p>Run the application and call:</p><pre>POST /send-email</pre><p>If everything is configured correctly, the email should arrive within seconds.</p><blockquote>Sending Dynamic Emails</blockquote><p>Most applications need dynamic content.</p><pre>string customerName = &quot;John&quot;;<br><br>string htmlBody = $&quot;&quot;&quot;<br>&lt;h2&gt;Welcome {customerName}&lt;/h2&gt;<br>&lt;p&gt;Thank you for registering.&lt;/p&gt;<br>&lt;p&gt;We&#39;re excited to have you onboard.&lt;/p&gt;<br>&quot;&quot;&quot;;<br><br>await emailService.SendEmailAsync(<br>    &quot;john@example.com&quot;,<br>    &quot;Welcome to Our Platform&quot;,<br>    htmlBody);</pre><blockquote>Sending Password Reset Emails</blockquote><p>A common use case is password recovery.</p><pre>string resetUrl =<br>    $&quot;https://myapp.com/reset?token={token}&quot;;<br><br>string htmlBody = $&quot;&quot;&quot;<br>&lt;h2&gt;Password Reset Request&lt;/h2&gt;<br>&lt;p&gt;Click the button below to reset your password.&lt;/p&gt;<br>&lt;a href=&quot;{resetUrl}&quot;&gt;<br>Reset Password<br>&lt;/a&gt;<br>&quot;&quot;&quot;;<br><br>await emailService.SendEmailAsync(<br>    user.Email,<br>    &quot;Reset Your Password&quot;,<br>    htmlBody);</pre><blockquote>Using HTML Templates</blockquote><p>Instead of writing HTML directly in code, consider:</p><ul><li>Razor Templates</li><li>SendGrid Dynamic Templates</li><li>HTML Email Files</li></ul><p>Benefits include:</p><ul><li>Cleaner code</li><li>Easier maintenance</li><li>Better separation of concerns</li></ul><p>For larger applications, template-based emails are highly recommended.</p><h4>Error Handling</h4><p>Always wrap email operations in try-catch blocks.</p><pre>try<br>{<br>    await emailService.SendEmailAsync(<br>        toEmail,<br>        subject,<br>        body);<br>}<br>catch (Exception ex)<br>{<br>    logger.LogError(<br>        ex,<br>        &quot;Failed to send email&quot;);<br>}</pre><p>This prevents email failures from crashing your application.</p><h3>Best Practices</h3><blockquote>Keep API Keys Secure</blockquote><p>Never store API keys directly in source code.</p><p>Use:</p><ul><li>Environment Variables</li><li>User Secrets</li><li>Azure Key Vault</li></ul><blockquote>Validate Email Addresses</blockquote><p>Before sending emails, validate user input to reduce delivery failures.</p><blockquote>Use Background Jobs</blockquote><p>Sending emails directly during requests can slow down your application.</p><p>Consider using:</p><ul><li>BackgroundService</li><li>Hangfire</li><li>Azure Queue Storage</li></ul><p>for asynchronous processing.</p><blockquote>Track Delivery Status</blockquote><p>SendGrid provides analytics for:</p><ul><li>Delivered emails</li><li>Open rates</li><li>Click rates</li><li>Bounce reports</li></ul><p>Monitoring these metrics helps improve email reliability.</p><h3>Common Use Cases</h3><p>SendGrid can be used for:</p><ul><li>Account verification</li><li>Password reset emails</li><li>Order confirmations</li><li>Invoice delivery</li><li>Newsletter campaigns</li><li>Event notifications</li><li>Contact forms</li><li>System alerts</li></ul><blockquote>Conclusion</blockquote><p>SendGrid provides a simple and reliable way to send emails from ASP.NET Core applications. With minimal setup, you can build scalable email workflows for account management, notifications, marketing campaigns, and more.</p><p>By combining ASP.NET Core’s dependency injection with SendGrid’s powerful API, you can create maintainable and production-ready email services in just a few steps.</p><p>If your application requires transactional or automated email delivery, SendGrid is an excellent solution worth considering.</p><p><a href="https://medium.com/u/d99855079b79">SendGrid</a> <br><a href="https://medium.com/u/5257579c0e05">SendGrid Labs</a></p><p><strong>Happy Coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c43cb213e3a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate QR Codes in C# Using QRCoder]]></title>
            <link>https://alifiyakapasi07.medium.com/generate-qr-codes-in-c-using-qrcoder-53be1f3594ad?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/53be1f3594ad</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 17:22:38 GMT</pubDate>
            <atom:updated>2026-06-08T17:22:38.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uj1qvvZILzXX3sDLWW5Pdw.png" /><figcaption>Generate QR Codes in C# Using QRCoder</figcaption></figure><p>QR codes are everywhere — from website links and event tickets to digital payments and Wi-Fi sharing. Instead of relying on third-party QR code generators, developers can generate QR codes directly within their .NET applications.</p><p>In this article, we’ll learn how to generate QR codes in C# using the popular <strong>QRCoder</strong> library and follow modern .NET development practices.</p><h3>Why Generate QR Codes Programmatically?</h3><p>Generating QR codes within your application offers several benefits:</p><ul><li>No dependency on external QR code services</li><li>Better control over customization and branding</li><li>Faster generation and processing</li><li>Easier integration with APIs and web applications</li><li>Improved privacy since data remains within your application</li></ul><p>Whether you’re building an ASP.NET Core application, desktop software, or an API, QR codes can be generated with just a few lines of code.</p><h3>Prerequisites</h3><p>Before starting, make sure you have:</p><ul><li>.NET 8 or later installed</li><li>Visual Studio 2022, Visual Studio Code, or JetBrains Rider</li><li>Basic knowledge of C#</li><li>Internet access to install NuGet packages</li></ul><h3>What is QRCoder?</h3><p>QRCoder is a free and open-source .NET library that simplifies QR code generation.</p><p>Some key features include:</p><ul><li>Generate QR codes from text, URLs, emails, and more</li><li>Export QR codes as PNG, SVG, Base64, and byte arrays</li><li>Customize colors and appearance</li><li>Works with ASP.NET Core and modern .NET applications</li></ul><h3>Installing QRCoder</h3><p>Install the package using the .NET CLI:</p><pre>dotnet add package QRCoder</pre><p>Or through the NuGet Package Manager:</p><pre>Install-Package QRCoder</pre><p>After installation, import the namespace:</p><pre>using QRCoder;</pre><h3>Generate Your First QR Code</h3><p>Let’s create a QR code that points to a website URL.</p><pre>using QRCoder;<br><br>string url = &quot;https://www.example.com&quot;;<br>using var qrGenerator = new QRCodeGenerator();<br><br>QRCodeData qrCodeData = qrGenerator.CreateQrCode(<br>        url,QRCodeGenerator.ECCLevel.Q);<br><br>PngByteQRCode qrCode = new PngByteQRCode(qrCodeData);<br><br>byte[] qrCodeBytes = qrCode.GetGraphic(20);<br><br>File.WriteAllBytes(&quot;QRCode.png&quot;, qrCodeBytes);<br><br>Console.WriteLine(&quot;QR Code generated successfully.&quot;);</pre><p>When you run the application, a file named <strong>QRCode.png</strong> will be created in the application’s output directory.</p><h3>Understanding the Code</h3><h3>QRCodeGenerator</h3><p>Creates the QR code structure.</p><pre>using var qrGenerator = new QRCodeGenerator();</pre><h3>CreateQrCode</h3><p>Encodes the content into a QR code.</p><pre>QRCodeData qrCodeData = qrGenerator.CreateQrCode(<br>        url,QRCodeGenerator.ECCLevel.Q);</pre><h3>Error Correction Levels</h3><p>QR codes can still be scanned even if part of the image is damaged.</p><p>- L — Approximately 7% recovery capacity<br>- M — Approximately 15% recovery capacity<br>- Q — Approximately 25% recovery capacity<br>- H — Approximately 30% recovery capacity</p><p>For most applications, <strong>Q</strong> provides a good balance between size and reliability.</p><h3>GetGraphic</h3><p>Creates the PNG image bytes.</p><pre>byte[] qrCodeBytes = qrCode.GetGraphic(20);</pre><p>The value 20 controls the pixel size of each QR module.</p><h3>Generate a QR Code for Plain Text</h3><p>QR codes are not limited to URLs.</p><pre>string text = &quot;Hello from .NET and QRCoder!&quot;;<br><br>using var qrGenerator = new QRCodeGenerator();<br>var qrCodeData =<br>    qrGenerator.CreateQrCode(<br>        text,<br>        QRCodeGenerator.ECCLevel.Q);<br>var qrCode =<br>    new PngByteQRCode(qrCodeData);<br>var bytes =<br>    qrCode.GetGraphic(20);<br>File.WriteAllBytes(&quot;TextQRCode.png&quot;, bytes);</pre><p>Scanning the QR code will display the text content.</p><h3>Generate a Wi-Fi QR Code</h3><p>Wi-Fi QR codes allow users to connect to a network without manually entering credentials.</p><pre>string wifiQr =<br>    &quot;WIFI:T:WPA;S:OfficeWiFi;P:StrongPassword123;;&quot;;<br><br>using var qrGenerator = new QRCodeGenerator();<br>var qrCodeData =<br>    qrGenerator.CreateQrCode(<br>        wifiQr,<br>        QRCodeGenerator.ECCLevel.Q);<br>var qrCode =<br>    new PngByteQRCode(qrCodeData);<br>var bytes =<br>    qrCode.GetGraphic(20);<br>File.WriteAllBytes(&quot;WiFiQRCode.png&quot;, bytes);</pre><p>When scanned, compatible devices will offer to connect automatically.</p><h3>Generate a QR Code in ASP.NET Core</h3><p>One common requirement is generating QR codes dynamically through an API.</p><h3>Minimal API Example</h3><pre>using QRCoder;<br><br>app.MapGet(&quot;/qr&quot;, (string text) =&gt;<br>{<br>    using var qrGenerator =<br>        new QRCodeGenerator();<br>    var qrData =<br>        qrGenerator.CreateQrCode(<br>            text,<br>            QRCodeGenerator.ECCLevel.Q);<br>    var qrCode =<br>        new PngByteQRCode(qrData);<br>    var bytes =<br>        qrCode.GetGraphic(20);<br>    return Results.File(<br>        bytes,<br>        &quot;image/png&quot;);<br>});</pre><p>Request:</p><pre>/qr?text=HelloWorld</pre><p>Response:</p><p>A PNG image containing the generated QR code.</p><h3>Return QR Codes as Base64</h3><p>Sometimes you may want to display a QR code directly in a web page without saving it as a file.</p><pre>string base64QrCode = Convert.ToBase64String(qrCodeBytes);</pre><p>In Razor:</p><pre>&lt;img src=&quot;data:image/png;base64,@Model.QrCode&quot; /&gt;</pre><p>This approach is useful when displaying QR codes in dashboards, invoices, or reports.</p><h3>Common Use Cases</h3><p>QR codes are frequently used for:</p><ul><li>Website links</li><li>Product information</li><li>Event registrations</li><li>Restaurant menus</li><li>Contact sharing (vCard)</li><li>Wi-Fi access</li><li>Digital payments</li><li>Authentication workflows</li><li>Inventory and asset tracking</li></ul><h3>Best Practices</h3><h3>Use Appropriate Error Correction</h3><p>Choose a higher error correction level if the QR code may be partially obstructed or printed in challenging environments.</p><h3>Avoid Excessively Large Content</h3><p>Large amounts of text increase QR code complexity and can reduce scanning reliability.</p><h3>Prefer PNG for Broad Compatibility</h3><p>PNG works consistently across browsers, mobile devices, and document-generation systems.</p><h3>Validate User Input</h3><p>If users provide QR code content, validate it before generating the QR code.</p><h3>Performance Considerations</h3><p>When generating QR codes at scale:</p><ul><li>Reuse application resources where possible</li><li>Cache frequently requested QR codes</li><li>Generate QR codes asynchronously in high-traffic applications</li><li>Consider storing generated files in cloud storage for repeated access</li></ul><h3>Conclusion</h3><p>Generating QR codes in C# has never been easier. With the QRCoder library, you can quickly create QR codes for URLs, text, Wi-Fi credentials, and many other scenarios.</p><p>Because QRCoder works seamlessly with modern .NET applications, it’s an excellent choice for ASP.NET Core APIs, web applications, desktop software, and enterprise solutions.</p><p>If your application needs a simple and reliable QR code generation solution, QRCoder is definitely worth considering.</p><h4>Happy Coding!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53be1f3594ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring SMTP Servers for Email Sending]]></title>
            <link>https://alifiyakapasi07.medium.com/configuring-smtp-servers-for-email-sending-adc77fa66da9?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc77fa66da9</guid>
            <category><![CDATA[smtp]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 01:31:38 GMT</pubDate>
            <atom:updated>2024-09-20T01:31:38.959Z</atom:updated>
            <content:encoded><![CDATA[<p>The System.Net and System.Net.Mail namespaces are the two, in order to send emails using the Simple Mail Transfer Protocol (SMTP), mail namespaces are required in C#. The primary classes used to create and transmit emails are MailMessage and SmtpClient, respectively.</p><p>For secure email transmission, these namespaces offer flexibility in email message configuration, attachment handling, and credential management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PntMvymAyeuhH39E" /></figure><blockquote><strong>1. Why We Send Emails Using MailMessage</strong></blockquote><ul><li><strong>Purpose</strong>: The email itself is represented by the MailMessage class. Key email elements including the sender, recipient(s), subject, message, and attachments can be specified by developers.</li><li><strong>Components</strong>:<br><strong>From</strong>: The sender’s email address.<br><strong>To</strong>, <strong>CC</strong>, and <strong>BCC</strong>: Recipients’ email addresses.<br><strong>Subject</strong>: The email subject line.<br><strong>Body</strong>: The content of the email, which can be plain text or HTML<br><strong>Attachments</strong>: You can attach files to the email.</li><li><strong>Benefits</strong>:<br><strong>Rich Email Composition</strong>: Emails with numerous recipients, attachments, HTML formatting, and embedded resources (such as images) can be created with ease.<br><strong>Customization</strong>: Offers a wide range of choices, including encodings, MIME types for attachments, and priority (high, low, etc.).<br><strong>Segregation of Concerns: </strong>It keeps the generation of messages apart from the SmtpClient’s handling of the message sending process.</li></ul><blockquote><strong>2. Key Classes in System.Net.Mail</strong></blockquote><ul><li><strong>SmtpClient</strong>: In charge of sending the MailMessage-created email to the SMTP server. Important configurations consist of:</li><li><strong>SMTP Server Address</strong>: Configured with the server address (e.g., smtp.gmail.com).</li><li><strong>Port</strong>: The port for SMTP communication (e.g., 587 for Gmail with TLS).</li><li><strong>EnableSsl</strong>: Ensures secure email transmission by enabling SSL/TLS.</li><li><strong>Credentials</strong>: Uses NetworkCredential to specify the sender’s email and password for authentication.</li><li><strong>NetworkCredential</strong>: Used to provide authentication (username and password) when connecting to the SMTP server.</li></ul><blockquote><strong>3. Steps to Send an Email Using System.Net.Mail</strong></blockquote><ol><li>Create an instance of MailMessage.</li><li>Set the From, To, Subject, and Body properties.</li><li>Use HTML formatting or attach files as an optional feature.</li><li>Create an SmtpClient instance.</li><li>Configure SmtpClient with the SMTP server, port, and credentials.</li><li>To send the email, use SmtpClient’s Send() method.</li></ol><blockquote><strong>4. Benefits of Using System.Net.Mail</strong></blockquote><ul><li><strong>Built-in Solution: </strong>Since it is a component of the.NET Framework’s Base Class Library (BCL), no external dependencies are required.</li><li><strong>Customizability: </strong>Total command over the content of emails, with HTML, multiple recipients, and attachments supported.</li><li><strong>Security: </strong>Permits secure authentication using NetworkCredential and SSL/TLS encryption.</li><li><strong>Error Handling: </strong>Offers solutions for possible anomalies such as network problems, timeouts, and failed authentication.</li><li><strong>Scalability: </strong>For larger applications requiring bulk email, it can be used asynchronously or in background operations.</li></ul><p>Configuring the following is necessary in order to send an email in an ASP.NET Core project utilizing MailMessage, SmtpClient, and System.Net.Mail:</p><ol><li>Model: For optional email configuration.</li><li>AppSettings.json: Used to hold SMTP settings and other email setup.</li><li>Program.cs: To set up required services (optional in simple scenarios).</li><li>Controller: An approach to manage logic and email sending.</li></ol><p>Here’s how to configure it:</p><h4>1. Model for Email Configuration (optional)</h4><p>You may make a basic model to store your email configurations.</p><pre>public class SendEmailModel<br>{<br>  public string From { get; set; }<br>  public string SmtpServer { get; set; }<br>  public long Port { get; set; }<br>  public string Username { get; set; }<br>  public string Password { get; set; }<br>}</pre><h4>2. appsettings.json</h4><p>Add your SMTP setup to your appsettings.json file:</p><pre>&quot;EmailConfiguration&quot;: {<br>&quot;SmtpServer&quot;: &quot;smtp.gmail.com&quot;,<br>&quot;Port&quot;: 587,<br>&quot;Username&quot;: &quot;1234556788@gmail.com&quot;,<br>&quot;From&quot;: &quot;1234556788@gmail.com&quot;,<br>&quot;Password&quot;: &quot;strinfklajihrid&quot;<br>}</pre><p>Examples of SMTP server setups for several email providers are provided here:</p><p><strong>SMTP Server Examples</strong></p><p><strong>1. Gmail</strong></p><ul><li><strong>SMTP Server</strong>: smtp.gmail.com</li><li><strong>Port</strong>: 587 (TLS/STARTTLS) or 465 (SSL)</li><li><strong>SSL/TLS</strong>: Yes</li><li><strong>Username</strong>: Your Gmail address</li><li><strong>Password</strong>: Your Gmail password (or an app-specific password if 2FA is enabled)</li></ul><p><strong>2. Yahoo Mail</strong></p><ul><li><strong>SMTP Server</strong>: smtp.mail.yahoo.com</li><li><strong>Port</strong>: 587 (TLS/STARTTLS) or 465 (SSL)</li><li><strong>SSL/TLS</strong>: Yes</li><li><strong>Username</strong>: Your Yahoo email address</li><li><strong>Password</strong>: Your Yahoo email password (or an app-specific password if 2FA is enabled)</li></ul><p><strong>3. Outlook.com (Microsoft)</strong></p><ul><li><strong>SMTP Server</strong>: smtp-mail.outlook.com</li><li><strong>Port</strong>: 587 (TLS/STARTTLS)</li><li><strong>SSL/TLS</strong>: Yes</li><li><strong>Username</strong>: Your Outlook email address</li><li><strong>Password</strong>: Your Outlook email password</li></ul><h4><strong>3. Controller</strong></h4><p>You can now create a controller to handle requests for sending emails and email logic.</p><pre>using System.Net.Mail;<br>using System.Net;<br><br>public class EmailController : Controller<br>{<br>  private readonly SendEmailModel _emailConfig;<br>  public EmailController(SendEmailModel emailConfig)<br>  {<br>    _emailConfig = emailConfig;<br>  }<br><br>  public IActionResult SendLink(string FirstName, string LastName, string toEmail, SendEmailModel sendEmailModel)<br>  {<br>    MailMessage message = new MailMessage();<br>    message.From = new MailAddress(_emailConfig.From);<br>    message.Subject = &quot;Link for Submit a Request.&quot;;<br>    message.To.Add(new MailAddress(toEmail));<br><br>    // example url : https://localhost:0000/controllerName/actionName<br>    var Body = &quot;&lt;html&gt;&lt;body&gt; Dear, &quot; + FirstName + &quot; &quot; + LastName + &quot; , Please Click on this link &lt;a href=&#39;url&quot; + &quot;&#39;&gt;click&lt;/a&gt; &lt;/body&gt;&lt;/html&gt;&quot;;<br>    message.Body = Body;<br>    message.IsBodyHtml = true;<br>    <br>    using (var smtpClient = new SmtpClient(_emailConfig.SmtpServer))<br>    {<br>      smtpClient.Port = 587;<br>      smtpClient.Credentials = new NetworkCredential(_emailConfig.Username, _emailConfig.Password);<br>      smtpClient.EnableSsl = true;<br>      smtpClient.Send(message);<br>    }<br>    return RedirectToAction(&quot;Dashboard&quot;);<br>  }<br>}</pre><h4>4. Program.cs</h4><p>In Program.cs, configure your services to inject EmailConfiguration and EmailController .</p><pre>var emailConfig = builder.Configuration<br>.GetSection(&quot;EmailConfiguration&quot;)<br>.Get&lt;SendEmailModel&gt;();<br>builder.Services.AddSingleton(emailConfig);</pre><h4>Conclusion:</h4><p>System.Net.Mail offers a simple and efficient method for sending emails from C# programs. Developers may set up and send emails securely with attachments, HTML content, and numerous recipients using classes like MailMessage and SmtpClient. However, for greater performance and scalability in contemporary large-scale applications, more recent libraries such as MailKit are suggested.</p><h4>Happy Coding!!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc77fa66da9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of Generic Repositories in C#]]></title>
            <link>https://alifiyakapasi07.medium.com/the-magic-of-generic-repositories-in-c-e790e238e7e6?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/e790e238e7e6</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 01:31:38 GMT</pubDate>
            <atom:updated>2024-09-16T01:31:38.298Z</atom:updated>
            <content:encoded><![CDATA[<p>A generic repository in C# offers an abstraction, reusable layer for CRUD operations on different kinds of entities. Code duplication can be minimized and maintainability enhanced by centralizing data access logic within a generic class. In addition to encouraging testability, this pattern adheres to the DRY (Don’t Repeat Yourself) principle.</p><h3>Benefits of a Generic Repository:</h3><ol><li><strong>Code Reusability: </strong>The ability to reuse code for other entities is a primary justification for utilizing a generic repository. For CRUD operations, you write the code once in the generic repository rather than repeatedly.</li><li><strong>Separation of Concerns and Abstraction: </strong>Data access logic and business logic are separated in a generic repository. Your code becomes clearer and simpler to update as a result. The only thing that has to care about business logic is that the data is retrieved, not how it is retrieved.</li><li><strong>Testability: </strong>It is simpler to mock a generic repository for unit tests because it is an abstraction of the data access layer. As a result, you can test your business logic in units without relying on the database.</li><li><strong>Consistent Data Access Code:</strong> By guaranteeing that every entity is accessed in an identical manner, a generic repository enhances maintainability and lowers the likelihood of errors brought on by inconsistent data access logic.</li><li><strong>DRY Principle:</strong> By using a single piece of code to operate with numerous types of entities, you may prevent the duplication of data access code for various entities.</li></ol><p>To develop a generic repository pattern in C# for MongoDB, change your code as follows:</p><h4>Generic Repository Implementation:</h4><pre>using MongoDB.Driver;<br>using System;<br>using System.Collections.Generic;<br>using System.Linq.Expressions;<br>using System.Threading.Tasks;<br><br>namespace DEMO.Repository<br>{<br>    public class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt; where T : class<br>    {<br>        private readonly IMongoCollection&lt;T&gt; _collection;<br><br>        public GenericRepository(MongoDBContext context, string collectionName)<br>        {<br>            _collection = context.GetCollection&lt;T&gt;(collectionName);<br>        }<br><br>        public async Task&lt;List&lt;T&gt;&gt; GetAllAsync()<br>        {<br>            return await _collection.Find(FilterDefinition&lt;T&gt;.Empty).ToListAsync();<br>        }<br><br>        public async Task&lt;T&gt; GetByIdAsync(string id)<br>        {<br>            return await _collection.Find(Builders&lt;T&gt;.Filter.Eq(&quot;Id&quot;, id)).FirstOrDefaultAsync();<br>        }<br><br>        public async Task&lt;List&lt;T&gt;&gt; FindAsync(Expression&lt;Func&lt;T, bool&gt;&gt; filter)<br>        {<br>            return await _collection.Find(filter).ToListAsync();<br>        }<br><br>        public async Task AddAsync(T entity)<br>        {<br>            await _collection.InsertOneAsync(entity);<br>        }<br><br>        public async Task UpdateAsync(string id, T entity)<br>        {<br>            await _collection.ReplaceOneAsync(Builders&lt;T&gt;.Filter.Eq(&quot;Id&quot;, id), entity);<br>        }<br><br>        public async Task DeleteAsync(string id)<br>        {<br>            await _collection.DeleteOneAsync(Builders&lt;T&gt;.Filter.Eq(&quot;Id&quot;, id));<br>        }<br><br>        public async Task SoftDeleteAsync(string id)<br>        {<br>            var update = Builders&lt;T&gt;.Update.Set(&quot;IsDeleted&quot;, true);<br>            await _collection.UpdateOneAsync(Builders&lt;T&gt;.Filter.Eq(&quot;Id&quot;, id), update);<br>        }<br>    }<br>}</pre><h4><strong>Interface for Generic Repository:</strong></h4><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq.Expressions;<br>using System.Threading.Tasks;<br><br>namespace DEMO.Repository<br>{<br>    public interface IGenericRepository&lt;T&gt; where T : class<br>    {<br>        Task&lt;List&lt;T&gt;&gt; GetAllAsync();<br>        Task&lt;T&gt; GetByIdAsync(string id);<br>        Task&lt;List&lt;T&gt;&gt; FindAsync(Expression&lt;Func&lt;T, bool&gt;&gt; filter);<br>        Task AddAsync(T entity);<br>        Task UpdateAsync(string id, T entity);<br>        Task DeleteAsync(string id);<br>        Task SoftDeleteAsync(string id);<br>    }<br>}</pre><blockquote><strong>Use Case Example:</strong></blockquote><p>According to <a href="https://alifiyakapasi07.medium.com/repository-pattern-in-mvc-8d38f69a6d34"><strong>our example</strong></a>, the UserRepository would take on the form of this particular implementation of the generic repository:</p><pre>namespace DEMO.Repository<br>{<br>    public class UserRepository : GenericRepository&lt;UserModel&gt;, IUserRepository<br>    {<br>        public UserRepository(MongoDBContext context) : base(context, &quot;Users&quot;)<br>        {<br>        }<br><br>        // If you need specific methods for the UserModel, you can add them here.<br>        // Example of a custom method:<br>        public async Task&lt;List&lt;UserModel&gt;&gt; GetAllActiveUsersAsync()<br>        {<br>            return await FindAsync(x =&gt; !x.IsDeleted);<br>        }<br>    }<br>}</pre><h4>Key Points:</h4><ul><li>By extending the GenericRepository, the UserRepository class is able to inherit all generic CRUD operations.</li><li>The constructor just sends the collection name (“Users”) and the MongoDBContext to the base generic repository.</li><li>If special queries that are not provided by the generic repository are needed by the UserModel, you can add any custom methods (such as GetAllActiveUsersAsync).</li></ul><h4>Conclusion:</h4><p>By implementing a generic repository, you can ensure uniform data access patterns across entities, which will improve your codebase. Unit testing is made easier, reusability is improved, and business logic and data access are clearly segregated. All things considered, this strategy promotes more scalable and maintainable applications.</p><h4>Happy Coding!!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e790e238e7e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Exception Handlers Save Programs from Crashing]]></title>
            <link>https://alifiyakapasi07.medium.com/how-exception-handlers-save-programs-from-crashing-2cb59516629e?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb59516629e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 14:34:33 GMT</pubDate>
            <atom:updated>2024-09-14T14:34:33.075Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What are Exception Handlers?</strong></h3><p>When a program is executing, an exception handler is a block of code that deals with the exception. The program raises an exception when a problem or unexpected circumstance arises. The purpose of exception handlers is to “catch” exceptions and specify how to handle or resolve the issue, preventing sudden application crashes and enabling improved error handling.</p><h4><strong>Why Do We Use Handlers for Exceptions?</strong></h4><ol><li><strong>Error Handling</strong>: Errors are represented via exceptions. We can handle and respond to these issues without stopping the program thanks to exception handlers.</li><li><strong>Boost Code Robustness: </strong>By minimizing unexpected crashes and lowering the possibility of errors, exception handling strengthens the code.</li><li><strong>Separation of Error Handling from Main Logic</strong>: This technique makes code cleaner and easier to maintain by keeping error-handling code apart from the main program logic.</li></ol><h4>Advantages of Exception Handling</h4><ul><li><strong>Prevents crashes</strong>: Permits the software to continue running and handle faults.</li><li><strong>Improved readability</strong>: Error-handling code is kept apart from the primary logic.</li><li><strong>Debugging ease</strong>: Exception messages facilitate debugging and error identification.</li><li><strong>Robust code</strong>: Makes applications more dependable and fault-tolerant.</li></ul><h4>Types of Exceptions</h4><ol><li><strong>Checked Exceptions</strong>: Exclusions that are examined during compilation. Throws must be used in the method signature to either catch them or declare them.<br>Example: IOException, SQLException</li><li><strong>Unchecked Exceptions (Runtime Exceptions)</strong>: Exceptions that happen while the program is running. They do not need to be declared in the method signature, and they are not checked at compilation time.<br>Example: NullPointerException, ArrayIndexOutOfBoundsException</li><li><strong>Error</strong>: These are significant issues that an application shouldn’t try to resolve. Errors are conditions that arise from outside the application and usually signify serious problems.<br>Example: OutOfMemoryError, StackOverflowError</li></ol><h4>Example of Exception Handlers</h4><blockquote><strong>1. Basic try-catch Block (Handling runtime exception)</strong></blockquote><pre>using System;<br><br>class Program {<br>    static void Main() {<br>        try {<br>            int result = 10 / 0; // This will throw a DivideByZeroException<br>        } catch (DivideByZeroException e) {<br>            Console.WriteLine(&quot;Cannot divide by zero: &quot; + e.Message);<br>        }<br>    }<br>}<br><br>// Output:<br>// Cannot divide by zero: Attempted to divide by zero.</pre><blockquote><strong>2. Multiple catch Blocks (Handling multiple exceptions)</strong></blockquote><pre>using System;<br><br>class Program {<br>    static void Main() {<br>        try {<br>            int[] array = new int[5];<br>            array[5] = 100;  // This will throw an IndexOutOfRangeException<br>        } catch (DivideByZeroException e) {<br>            Console.WriteLine(&quot;DivideByZeroException caught.&quot;);<br>        } catch (IndexOutOfRangeException e) {<br>            Console.WriteLine(&quot;IndexOutOfRangeException caught: &quot; + e.Message);<br>        }<br>    }<br>}<br><br>// Output:<br>// IndexOutOfRangeException caught: Index was outside the bounds of the array.</pre><blockquote><strong>3. Finally Block (Always Executing Code)</strong></blockquote><p>The finally block is used to execute code that must run whether an exception occurs or not.</p><pre>using System;<br><br>class Program {<br>    static void Main() {<br>        try {<br>            int result = 10 / 2;<br>            Console.WriteLine(&quot;Result: &quot; + result);<br>        } catch (Exception e) {<br>            Console.WriteLine(&quot;Exception caught: &quot; + e.Message);<br>        } finally {<br>            Console.WriteLine(&quot;This will always execute, even if there is an exception.&quot;);<br>        }<br>    }<br>}<br><br>// Output:<br>// Result: 5<br>// This will always execute, even if there is an exception.</pre><blockquote><strong>4. Throwing an Exception Manually</strong></blockquote><p>You can use the throw keyword to throw an exception manually when a specific condition is met.</p><pre>using System;<br><br>class Program {<br>    static void Main() {<br>        try {<br>            ValidateAge(15);  // This will throw an exception<br>        } catch (Exception e) {<br>            Console.WriteLine(&quot;Exception caught: &quot; + e.Message);<br>        }<br>    }<br><br>    static void ValidateAge(int age) {<br>        if (age &lt; 18) {<br>            throw new Exception(&quot;Age must be greater than 18.&quot;);<br>        }<br>        Console.WriteLine(&quot;Age is valid.&quot;);<br>    }<br>}<br><br>// Output:<br>// Exception caught: Age must be greater than 18.</pre><blockquote><strong>5. Custom Exception</strong></blockquote><p>You can define your own exception class by inheriting from the Exception class.</p><pre>using System;<br><br>class InvalidAgeException : Exception {<br>    public InvalidAgeException(string message) : base(message) { }<br>}<br><br>class Program {<br>    static void Main() {<br>        try {<br>            ValidateAge(16);<br>        } catch (InvalidAgeException e) {<br>            Console.WriteLine(&quot;Custom Exception: &quot; + e.Message);<br>        }<br>    }<br><br>    static void ValidateAge(int age) {<br>        if (age &lt; 18) {<br>            throw new InvalidAgeException(&quot;You must be at least 18 years old.&quot;);<br>        }<br>        Console.WriteLine(&quot;Age is valid.&quot;);<br>    }<br>}<br><br>// Output:<br>// Custom Exception: You must be at least 18 years old.</pre><p>These C# examples demonstrate how exception handling functions. The finally block makes sure that a given piece of code runs every time, the try-catch construct lets you handle various kinds of problems, and throw lets you raise exceptions of your own.</p><h4>Happy Coding!!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb59516629e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Middleware in .NET MVC]]></title>
            <link>https://alifiyakapasi07.medium.com/understanding-middleware-in-net-mvc-8101b757f9a3?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/8101b757f9a3</guid>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 01:31:35 GMT</pubDate>
            <atom:updated>2024-09-09T01:31:35.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Middleware in .NET MVC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*-JqKIQLO-BBAcHYa" /><figcaption>Console Image of Logs of middleware</figcaption></figure><blockquote><strong>What is Middleware?</strong></blockquote><p>Software that serves as an interface between an operating system, database, and applications — particularly those running on a network — is referred to as middleware. Middleware is a layer in the application pipeline used in web development that handles requests and answers. Error handling, session management, logging, authentication, and other functions can be performed via middleware components.</p><blockquote><strong>Why Is Middleware Used?</strong></blockquote><ol><li><strong>Overcome Cross-Cutting Issues:</strong> Middleware can be used to modularize features that are common to all applications, such as caching, logging, authentication, and so on.</li><li><strong>Request/Response Processing:</strong> Middleware gives you the ability to alter HTTP responses before sending them to the client or process incoming requests for HTTP before they get to the application logic.</li><li><strong>Pipeline Customization:</strong> By arranging requests into a pipeline, middleware allows developers to customize how they go through the application. Every component has the option to either end the request or pass it on to the next middleware.</li></ol><blockquote><strong>Benefits of Middleware:</strong></blockquote><ol><li><strong>Concern Segregation: </strong>Middleware facilitates the division of various issues (such as error correction and authentication) into separate components.</li><li><strong>Reusability: </strong>Middleware can be utilized again in several projects or even in different sections of the same application.</li><li><strong>Modularity:</strong> The program is flexible and modular so you may add or remove middleware as needed.</li><li><strong>Scalability: </strong>By adding new components to handle various jobs, middleware makes it simple to scale and enhance the functionality of web applications.</li></ol><blockquote><strong>Types of Middleware:</strong></blockquote><ol><li><strong>Authentication Middleware</strong>: Manages authorization and user authentication.</li><li><strong>Logging Middleware</strong>: Logs requests and responses, useful for monitoring and debugging.</li><li><strong>Error Handling Middleware</strong>: Captures and handles pipeline error instances.</li><li><strong>Routing Middleware</strong>: Sends requests to the relevant endpoints or handlers.</li><li><strong>Caching Middleware</strong>: Increases efficiency by preventing redundant processing by caching responses.</li><li><strong>Session Middleware</strong>: Controls cookies and user-specific data while controlling user sessions.</li><li><strong>Compression Middleware</strong>: Responses are compressed to enhance network efficiency.</li></ol><h4>Example of Middleware in .NET MVC</h4><p>Middleware components in ASP.NET Core MVC are set up using the Configure function in the Program.cs file. Using custom middleware to log incoming requests is demonstrated by this example:</p><pre>// Custom middleware to log HTTP requests<br>public class RequestLoggingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br><br>    public RequestLoggingMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br><br>    public async Task Invoke(HttpContext context)<br>    {<br>        // Log the request path<br>        Console.WriteLine($&quot;Request URL: {context.Request.Path}&quot;);<br>        <br>        // Call the next middleware in the pipeline<br>        await _next(context);<br>        <br>        // Log the response status code<br>        Console.WriteLine($&quot;Response Status Code: {context.Response.StatusCode}&quot;);<br>    }<br>}<br><br>// Extension method to add the middleware to the pipeline<br>public static class RequestLoggingMiddlewareExtensions<br>{<br>    public static IApplicationBuilder UseRequestLogging(this IApplicationBuilder builder)<br>    {<br>        return builder.UseMiddleware&lt;RequestLoggingMiddleware&gt;();<br>    }<br>}</pre><p>How to Configure Middleware in Program.cs:</p><pre>// Add custom request logging middleware to the pipeline<br>app.UseRequestLogging();<br><br>app.UseRouting();</pre><p>In this particular scenario, each HTTP request is logged with the request URL and response status code via the custom middleware RequestLoggingMiddleware.</p><blockquote><strong>Conclusion:</strong></blockquote><p>For web applications to handle multifaceted problems like error handling, logging, and authentication, middleware is necessary. Through the use of a pipeline, it improves scalability, modularity, and reusability. The use of middleware streamlines and organizes the development of applications.</p><h4>Happy Coding !!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8101b757f9a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repository Pattern in MVC]]></title>
            <link>https://alifiyakapasi07.medium.com/repository-pattern-in-mvc-8d38f69a6d34?source=rss-c7db647e0e86------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d38f69a6d34</guid>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Alifiyakapasi]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 17:02:20 GMT</pubDate>
            <atom:updated>2024-09-05T17:02:20.171Z</atom:updated>
            <content:encoded><![CDATA[<p>A design pattern for controlling data access in software applications is the repository pattern. Applications that follow the Model-View-Controller (MVC) architecture structure are especially subject to it.</p><p><strong>What is the Repository Pattern?</strong></p><p>Data access logic can be abstracted and encapsulated using the Repository Pattern. It serves as a mediator between your application’s business logic and the data source, which could be a database, an API, or another type of storage. The main goal is to detach data access from business logic by offering a clear interface.</p><p>Key Components:</p><ol><li><strong>Repository Interface</strong>: Repository Interface: Specifies how the data can be accessed. Typically, it has functions like Update, Add, and Remove..</li><li><strong>Implementation of the Repository: </strong>This part handles the real data access logic and offers a concrete implementation of the methods specified in the interface.</li><li><strong>Data Source: </strong>The real data supplier or storage (like a database).</li></ol><h4>The Repository Pattern’s Advantages :</h4><ol><li><strong>Separation of Concerns</strong>: You can draw separate boundaries between these concerns by dividing data access logic from business logic. As a result, the codebase is easier to maintain and more modular.</li><li><strong>Testability: </strong>During unit testing, it’s simpler to simulate or dummy repositories. This lets you test your logic for business logic separate from the data access layer.</li><li><strong>Flexibility</strong>: Only the repository implementation, not the business logic, needs to change when the data source is changed (for example, from a SQL database to a NoSQL database).</li><li><strong>Consistency</strong>: Gives users a standardized method for organizing and retrieving data across the various program sections.</li><li><strong>Decoupling</strong>: Makes it easier to change or replace the data access logic without affecting other components of the application by facilitating in the decoupling of the data access layer from the rest of the application.</li></ol><p><strong>Why Use Repository Pattern in MVC?</strong></p><p>In the context of MVC (Model-View-Controller), the Repository Pattern is often used to:</p><ol><li><strong>Encapsulate Data Access</strong>: In the MVC paradigm, views display the data, models describe the data, and controllers manage user input. Instead of going straight to the data source, controllers use repositories to interact with the data via a well-defined interface. This maintains the models’ and controllers’ attention on their tasks and cleanliness.</li><li><strong>Promote Code Reusability</strong>: You can repurpose the same data access functionality across several application components by utilizing repositories. For instance, distinct controllers can consistently access the same data by using the same repository.</li><li><strong>Boost Maintainability: </strong>When data access is managed by a repository, modifications to the data source or access logic solely impact the repository. This makes maintenance easier and lowers the chance of new bugs coming in because the rest of the application is not impacted.</li><li><strong>Boost Testability: </strong>Controllers and business logic can be tested more quickly and separately without requiring a real data source by using repositories that are simple to mock or stub in unit tests.</li></ol><p>Here, we’ll put the repository pattern into practice using the service class library and repository:</p><p>First, make two class libraries for the repository and service.Yes, Click Solution, then choose New Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*C9wGWOEe65YeDtyq" /></figure><p>Hereafter, choose….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*NffM3zaWvCrHATA4" /></figure><p>Next, click, and provide whatever you wish.</p><p>Names are often provided as solutionName.Services</p><p>Next, select the.NET Framework, then click “Create.”</p><p>Subsequently, you must provide each other with references in order to establish connections.</p><p>Here, DEMO.Services and DEMO.Repository are created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/0*WWegW2CBIeMeNQC-" /></figure><p>Thus, make reference to Services in the Demo and to the Repository in the Service. Demo -&gt; Services -&gt; Repository</p><ul><li>The most important thing to keep in mind is to be careful not to develop a circular dependency.</li><li>When two or more components are dependent on one another, it can be challenging to break the loop because each component is necessary for the other to work correctly. This is known as a circular dependency.</li></ul><p>How to give references:</p><p>Select the DEMO.Services Project by right-clicking on the DEMO Project, then choose Add ⇒ Project Reference and click OK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*NXqeZIb_P4ycNIb7" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*vwUcXIFOtqTqHF_J" /></figure><p>Add a reference for DEMO.Repository and do the same for DEMO.Services.</p><p>I’ll give an example of a repository and service for an earlier project here.</p><p>Click <a href="https://alifiyakapasi07.medium.com/crud-operation-in-asp-net-mvc-aba53f9233b7">here</a> to read that story.</p><p><strong>UserController.cs</strong></p><pre>public class UserController : Controller<br>{<br>    private readonly IUserService _userService;<br><br>    public UserController(IUserService userService)<br>    {<br>        _userService = userService;<br>    }<br><br>    // GET: User<br>    public async Task&lt;ActionResult&gt; Index()<br>    {<br>        var models = await _userService.GetAllUsersAsync();<br>        return View(models);<br>    }<br><br>    // GET: User/Create<br>    public ActionResult Create()<br>    {<br>        return View();<br>    }<br><br>    // POST: User/Create<br>    [HttpPost]<br>    [ValidateAntiForgeryToken]<br>    public async Task&lt;ActionResult&gt; Create(UserModel model)<br>    {<br>        if (ModelState.IsValid)<br>        {<br>            await _userService.CreateUserAsync(model);<br>            return RedirectToAction(&quot;Index&quot;);<br>        }<br>        return View(model);<br>    }<br><br>    // GET: User/Edit/id<br>    public async Task&lt;ActionResult&gt; Edit(string id)<br>    {<br>        var model = await _userService.GetUserByIdAsync(id);<br>        return View(model);<br>    }<br><br>    // POST: User/Edit/id<br>    [HttpPost]<br>    [ValidateAntiForgeryToken]<br>    public async Task&lt;ActionResult&gt; Edit(string id, UserModel model)<br>    {<br>        if (ModelState.IsValid)<br>        {<br>            await _userService.UpdateUserAsync(id, model);<br>            return RedirectToAction(&quot;Index&quot;);<br>        }<br>        return View(model);<br>    }<br><br>    // GET: User/Delete/id<br>    public async Task&lt;ActionResult&gt; Delete(string id)<br>    {<br>        await _userService.DeleteUserAsync(id);<br>        return RedirectToAction(&quot;Index&quot;);<br>    }<br>}</pre><p><strong>UserService.cs</strong></p><pre>public class UserService : IUserService<br>{<br>    private readonly IUserRepository _userRepository;<br><br>    public UserService(IUserRepository userRepository)<br>    {<br>        _userRepository = userRepository;<br>    }<br><br>    public async Task&lt;List&lt;UserModel&gt;&gt; GetAllUsersAsync()<br>    {<br>        return await _userRepository.GetAllActiveUsersAsync();<br>    }<br><br>    public async Task&lt;UserModel&gt; GetUserByIdAsync(string id)<br>    {<br>        return await _userRepository.GetUserByIdAsync(id);<br>    }<br><br>    public async Task CreateUserAsync(UserModel model)<br>    {<br>        if (model == null)<br>            throw new ArgumentNullException(nameof(model));<br><br>        await _userRepository.AddUserAsync(model);<br>    }<br><br>    public async Task UpdateUserAsync(string id, UserModel model)<br>    {<br>        if (model == null)<br>            throw new ArgumentNullException(nameof(model));<br><br>        await _userRepository.UpdateUserAsync(id, model);<br>    }<br><br>    public async Task DeleteUserAsync(string id)<br>    {<br>        await _userRepository.DeleteUserAsync(id);<br>    }<br>}</pre><p><strong>IUserService.cs</strong></p><pre>public interface IUserService<br> {<br>     Task&lt;List&lt;UserModel&gt;&gt; GetAllUsersAsync();<br>     Task&lt;UserModel&gt; GetUserByIdAsync(string id);<br>     Task CreateUserAsync(UserModel model);<br>     Task UpdateUserAsync(string id, UserModel model);<br>     Task DeleteUserAsync(string id);<br> }</pre><p><strong>UserRepository.cs</strong></p><pre>public class UserRepository : IUserRepository<br> {<br>     private readonly IMongoCollection&lt;UserModel&gt; _collection;<br><br>     public UserRepository(MongoDBContext context)<br>     {<br>         _collection = context.UserCollection;<br>     }<br><br>     public async Task&lt;List&lt;UserModel&gt;&gt; GetAllActiveUsersAsync()<br>     {<br>         return await _collection.Find(x =&gt; !x.IsDeleted).ToListAsync();<br>     }<br><br>     public async Task&lt;UserModel&gt; GetUserByIdAsync(string id)<br>     {<br>         return await _collection.Find(x =&gt; x.Id == id).FirstOrDefaultAsync();<br>     }<br><br>     public async Task AddUserAsync(UserModel model)<br>     {<br>         await _collection.InsertOneAsync(model);<br>     }<br><br>     public async Task UpdateUserAsync(string id, UserModel model)<br>     {<br>         await _collection.ReplaceOneAsync(x =&gt; x.Id == id, model);<br>     }<br><br>     public async Task DeleteUserAsync(string id)<br>     {<br>         // Ideally, you would handle the soft delete here<br>         var update = Builders&lt;UserModel&gt;.Update.Set(x =&gt; x.IsDeleted, true);<br>         await _collection.UpdateOneAsync(x =&gt; x.Id == id, update);<br>     }<br> }</pre><p><strong>IUserRepository.cs</strong></p><pre>public interface IUserRepository<br>{<br>    Task&lt;List&lt;UserModel&gt;&gt; GetAllActiveUsersAsync();<br>    Task&lt;UserModel&gt; GetUserByIdAsync(string id);<br>    Task AddUserAsync(UserModel model);<br>    Task UpdateUserAsync(string id, UserModel model);<br>    Task DeleteUserAsync(string id);<br>}</pre><p><strong>In Program.cs</strong></p><pre>// Register repositories and services<br>builder.Services.AddScoped&lt;IUserRepository, UserRepository&gt;();<br>builder.Services.AddScoped&lt;IUserService, UserService&gt;();</pre><p><strong>Structure of Project</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*kAeUN-ukCMwrYnuZ" /></figure><h4>Happy Coding!!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d38f69a6d34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>