<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: neophyte</title>
    <description>The latest articles on DEV Community by neophyte (@neophyte4).</description>
    <link>https://dev.to/neophyte4</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F549554%2Fd73d4c6c-fbb7-4ec9-80e7-6783c1ebd533.png</url>
      <title>DEV Community: neophyte</title>
      <link>https://dev.to/neophyte4</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/neophyte4"/>
    <language>en</language>
    <item>
      <title>How to handle global exception in .NET Core</title>
      <dc:creator>neophyte</dc:creator>
      <pubDate>Sun, 27 Aug 2023 12:04:05 +0000</pubDate>
      <link>https://dev.to/neophyte4/how-to-handle-global-exception-in-net-core-dgo</link>
      <guid>https://dev.to/neophyte4/how-to-handle-global-exception-in-net-core-dgo</guid>
      <description>&lt;p&gt;In ASP.NET Core, you can handle global exceptions using middleware. Middleware is a component that sits in the request pipeline and can perform tasks before or after the request reaches your controller actions. Handling global exceptions through middleware allows you to centralize error handling and provide consistent behavior for your application.&lt;/p&gt;

&lt;p&gt;Here's how you can create middleware to handle global exceptions in .NET Core:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Create a Middleware Class:&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Create a new class for your middleware. This class should have a constructor that takes in RequestDelegate, which represents the next delegate in the pipeline. Inside the class, you can catch and handle exceptions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public sealed class GlobalErrorHandlingMiddleware
{
    private readonly ILogger&amp;lt;GlobalErrorHandlingMiddleware&amp;gt; _logger;
    private readonly RequestDelegate _next;

    public GlobalErrorHandlingMiddleware(ILogger&amp;lt;GlobalErrorHandlingMiddleware&amp;gt; logger, RequestDelegate next)
    {
        _logger = logger;
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {

            await _next(context);
        }
        catch(Exception ex)
        {
            _logger.LogError(ex, ex.Message);
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            await context.Response.WriteAsync("An error occurred.");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Register Middleware:&lt;/strong&gt;
In your program.cs class, add the middleware, GlobalExceptionMiddleware before registering MVC or routing middleware. This ensures that the exception handling middleware is executed for all requests.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.UseMiddleware&amp;lt;GlobalErrorHandlingMiddleware&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By placing the UseMiddleware() call in the appropriate position, you ensure that any unhandled exceptions thrown within the pipeline will be caught by your custom middleware and handled according to your logic.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>dotnetcore</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Immutability with Init-Only Properties in C#</title>
      <dc:creator>neophyte</dc:creator>
      <pubDate>Thu, 17 Aug 2023 17:33:01 +0000</pubDate>
      <link>https://dev.to/neophyte4/immutability-with-init-only-properties-in-c-bhn</link>
      <guid>https://dev.to/neophyte4/immutability-with-init-only-properties-in-c-bhn</guid>
      <description>&lt;p&gt;In C#, immutability refers to the property of an object that once it is created, its state cannot be changed. This is typically achieved by making sure that the object's properties cannot be modified after the object is instantiated. One way to achieve immutability in C# is by using init-only properties, introduced in C# 9.0.&lt;/p&gt;

&lt;p&gt;Init-only properties allow you to set the initial values of properties when an object is created, but they cannot be modified afterwards. This ensures that the object's state remains constant after it's been constructed. Here's how you can achieve immutability using init-only properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

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

&lt;/div&gt;



&lt;p&gt;In this example, the FirstName and LastName properties are declared as init-only properties using the init accessor. The constructor initializes these properties, and once the object is created, their values cannot be changed.&lt;/p&gt;

&lt;p&gt;Here's how you can use this Person class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var person = new Person("John", "Doe");

// This will result in a compilation error because init-only properties cannot be modified after initialization.
// person.FirstName = "Jane";

Console.WriteLine($"{person.FirstName} {person.LastName}");

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

&lt;/div&gt;



&lt;p&gt;Attempting to modify the FirstName property after initialization will result in a compilation error, enforcing the immutability of the object's state.&lt;/p&gt;

&lt;p&gt;Init-only properties provide a convenient way to create immutable objects without the need to write custom getter methods and private setters, as was required in previous versions of C#. They improve code readability and maintainability by clearly indicating which properties are intended to be set only during object initialization.&lt;/p&gt;

&lt;p&gt;Keep in mind that while init-only properties prevent you from directly modifying the property values, they do not make the entire object deeply immutable. If the properties themselves hold reference types (e.g., collections or other objects), those internal objects might still be mutable. If you want to ensure complete immutability, you need to ensure that the entire object graph is immutable.&lt;/p&gt;

&lt;p&gt;Here is one more example which is mostly use in Domain Driven style codebase.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public abstract class Entity
{
    protected Entity(Guid id) =&amp;gt; Id = id;

    protected Entity() { }

    public Guid Id { get; private init; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Where ViewModel should be placed in clean architecture?</title>
      <dc:creator>neophyte</dc:creator>
      <pubDate>Fri, 11 Aug 2023 07:17:12 +0000</pubDate>
      <link>https://dev.to/neophyte4/where-viewmodel-should-be-placed-in-clean-architecture-1p68</link>
      <guid>https://dev.to/neophyte4/where-viewmodel-should-be-placed-in-clean-architecture-1p68</guid>
      <description>&lt;p&gt;One of my friends asked me that where ViewModel should be placed in clean architecture? &lt;/p&gt;

&lt;p&gt;Here was my answer:&lt;/p&gt;

&lt;p&gt;As a professional .NET developer following the Clean Architecture principles, View Models should be placed in the Presentation Layer. In the context of Clean Architecture, the Presentation Layer is responsible for handling user interfaces, user interactions, and adapting the data from the Domain Layer into a format suitable for the views.&lt;/p&gt;

&lt;p&gt;The Presentation Layer is the outermost layer of the application, and it depends on the Application Layer, which in turn depends on the Domain Layer. The View Models act as an intermediary between the Presentation Layer and the Application Layer, providing the necessary data and behavior to be displayed in the user interface.&lt;/p&gt;

&lt;p&gt;To summarize, View Models belong to the Presentation Layer, which is part of the outer ring of the Clean Architecture. Placing them in this layer helps ensure a clear separation of concerns, maintainability, and testability of the application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ax--6D5T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azb8b1h8rkzaaq3pfeeu.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ax--6D5T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azb8b1h8rkzaaq3pfeeu.jpeg" alt="Clean Architecture diagram" width="328" height="319"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>beginners</category>
    </item>
    <item>
      <title>10 tips to prevent cross-site attack in .NET.</title>
      <dc:creator>neophyte</dc:creator>
      <pubDate>Thu, 10 Aug 2023 14:59:59 +0000</pubDate>
      <link>https://dev.to/neophyte4/10-tips-to-prevent-cross-site-attack-in-net-156k</link>
      <guid>https://dev.to/neophyte4/10-tips-to-prevent-cross-site-attack-in-net-156k</guid>
      <description>&lt;p&gt;Preventing Cross-Site Scripting (XSS) attacks in a .NET Core project involves implementing proper input validation, output encoding, and security configurations. &lt;br&gt;
Here are some steps to help you prevent XSS in your .NET Core project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Validate Input Data:&lt;/strong&gt;&lt;br&gt;
Valiate and sanitize all user inputs, including query parameters, form data, and cookies. Reject or sanitize any input that doesn't meet the expected format or content.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Use Parameterized Queries:&lt;/strong&gt;&lt;br&gt;
When interacting with databases, use parameterized queries or an Object-Relational Mapping (ORM) library that automatically escapes input values. This prevents SQL injection attacks, which can lead to XSS vulnerabilities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Output Encoding&lt;/strong&gt;&lt;br&gt;
Always encode dynamic data before displaying it in the HTML. .NET core provides HTML encoding functions that you should use when rendering data in views. For example, in Razor views, use @Html.Raw to output content as raw HTML, and use @Html.Encode to HTML-encode content.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Content Security Policy (CSP):&lt;/strong&gt;&lt;br&gt;
Implement a Content Security Policy to restrict the sources from which your application can load content (e.g., scripts, styles, images). This can mitigate the impact of malicious scripts injected into your pages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Use Razor Views Property:&lt;/strong&gt;&lt;br&gt;
Be careful with Razor Views. Avoid using @Html.Raw unless you're certain the content is safe. Use Razor's automatic HTML encoding by default.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Avoid Dangerous APIs:&lt;/strong&gt;&lt;br&gt;
Be cautious when using potentially dangerous APIs that can execute scripts. For example, when using innerHTML in javascript or the @Html.Raw method in Razor views, ensure that you're not inadvertently executing scripts. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Sanitize Rich Content:&lt;/strong&gt;&lt;br&gt;
If your application allows users to enter rich content (e.g., comments, descriptions), consider using a trusted and well-maintained HTML sanitizer library to sanitize the content before rendering it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Ganss.XSS;

string unsafeHtml = "&amp;lt;script&amp;gt;alert('XSS!');&amp;lt;/script&amp;gt;&amp;lt;p&amp;gt;This is safe.&amp;lt;/p&amp;gt;";
var sanitizer = new HtmlSanitizer();
string safeHtml = sanitizer.Sanitize(unsafeHtml);

// Now, the safeHtml variable contains sanitized HTML
// that can be safely displayed.

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;8. Ragular Security Updates:&lt;/strong&gt;&lt;br&gt;
Keep your .NET core framework and packages up-to-date. Updates may include security patches that address known vulnerabilities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. Security Headers:&lt;/strong&gt;&lt;br&gt;
Use appropriate HTTP security headers, such as X-XSS-Protection, to instruct browsers to prevent or mitigate XSS attacks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. Security Testing:&lt;/strong&gt;&lt;br&gt;
Conduct regular security testing, including automated and manual security assessments, to identify and fix potential vulnerabilities, including XSS.&lt;/p&gt;

&lt;p&gt;By following these best practices, you can significantly reduce the risk of XSS attacks in your .NET Core project. Stay informed about the latest security updates and practices to keep your application secure.&lt;/p&gt;

</description>
      <category>dotnetcore</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Simple steps to publish nuget package</title>
      <dc:creator>neophyte</dc:creator>
      <pubDate>Sat, 03 Dec 2022 16:39:21 +0000</pubDate>
      <link>https://dev.to/neophyte4/simple-steps-to-publish-nuget-package-3ck7</link>
      <guid>https://dev.to/neophyte4/simple-steps-to-publish-nuget-package-3ck7</guid>
      <description>&lt;p&gt;TL;DR;&lt;/p&gt;

&lt;h3&gt;
  
  
  Create and publish nuget package through dotnet cli
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PsB01mDo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1k1mv1kfgo1yqkwnu33m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PsB01mDo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1k1mv1kfgo1yqkwnu33m.png" alt="Image description" width="880" height="577"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RzRdU2zU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2vr94sb4ctzqusy4r9g4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RzRdU2zU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2vr94sb4ctzqusy4r9g4.png" alt="Image description" width="880" height="660"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OZntvveV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/941jn74ncgp8ppr69hq6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OZntvveV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/941jn74ncgp8ppr69hq6.png" alt="Image description" width="880" height="300"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Publish nuget package through GITHUB Actions
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name: Publish nuget package

on:
  push:
    branches: ["main"]
  workflow_dispatch:

permissions:
  contents: read

jobs:
    build:
      runs-on: windows-latest

      steps:
        - uses: actions/checkout@v3

        - name: Setup .NET core
          uses: actions/setup-dotnet@v2
          with:
            dotnet-version: 6.0.*

        - name: Build application
          run: dotnet build SecurityCode.Validator --configuration release

        - name: package
          run: dotnet pack SecurityCode.Validator --configuration release --output package

        - name: publish
          run: dotnet nuget push package\*.nupkg --api-key ${{secrets.NUGET_KEY}} --source https://api.nuget.org/v3/index.json 




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

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TU6II7up--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j9tz9dxkfvdxa3ydbnsi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TU6II7up--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j9tz9dxkfvdxa3ydbnsi.png" alt="Image description" width="880" height="352"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Happy Coding!!!&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
