<?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: muneeb-devp</title>
    <description>The latest articles on DEV Community by muneeb-devp (@muneebdevp).</description>
    <link>https://dev.to/muneebdevp</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%2F446219%2F9c5ac7b1-7f2d-40fa-941e-8f1218611257.jpg</url>
      <title>DEV Community: muneeb-devp</title>
      <link>https://dev.to/muneebdevp</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/muneebdevp"/>
    <language>en</language>
    <item>
      <title>Soft Delete using Entity Framework Core</title>
      <dc:creator>muneeb-devp</dc:creator>
      <pubDate>Mon, 08 Apr 2024 01:46:58 +0000</pubDate>
      <link>https://dev.to/muneebdevp/soft-delete-using-entity-framework-core-5bjd</link>
      <guid>https://dev.to/muneebdevp/soft-delete-using-entity-framework-core-5bjd</guid>
      <description>&lt;h1&gt;
  
  
  The &lt;strong&gt;D&lt;/strong&gt; in CRUD
&lt;/h1&gt;

&lt;p&gt;Deleting data from the database is a ubitiquous operation in almost any software application out there. The traditional approach for deleting data is using &lt;code&gt;DELETE&lt;/code&gt; query, but it comes with a catch: &lt;strong&gt;There is no undo button in databases for deleted records&lt;/strong&gt; (unless you have a backup strategy in place). This is how we normally delete a record from a relational database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DELETE FROM [dbo].[Users]
  WHERE [Users].[UserId] = 198943;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is known as &lt;strong&gt;Hard Delete&lt;/strong&gt;, which is known to be a &lt;strong&gt;destructive&lt;/strong&gt; operations since it is physically deleting the data from the database. This approach works fine for small scale traditional applications but for corporate giants, losing data is an unaffordable scenario.&lt;/p&gt;

&lt;h2&gt;
  
  
  Problems with Hard Delete:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Data Loss&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;It is very easy to specify an incorrect Id or no Id at all for the record to be deleted. This will result in irreversible data loss.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Performance Impact &amp;amp; Referential Integrity&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;In the above query, deleting a User record means we have to cascade delete on all of the data associated with that user i.e. the reviews, purchase history, wishlist e.t.c. In system with high transactions, such as a bank, this could be problematic as the database will hold lock on each record to delete it causing performance penalty.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Legal Requirements&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Certain countries have to abide by the data retention and data disposal procedures defined by the government or Internal governing bodies (EU). Thus, hard delete could cause penalities for non-compliance.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Soft Delete to the Rescue
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Soft Delete&lt;/strong&gt; does not use a &lt;code&gt;DELETE&lt;/code&gt; query but rather an &lt;code&gt;UPDATE&lt;/code&gt; query to signify the deletion of a record. This is possible because of an additional column in each database entity named &lt;code&gt;IsDeleted (bit)&lt;/code&gt;. Since we're not deleting anything from the database, this operation is &lt;strong&gt;Non-Destructive&lt;/strong&gt;, so the delete operation would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;UPDATE [dbo].[Users]
  SET [dbo].[Users].[IsDeleted] = 1
  WHERE [Users].[UserId] = 198943;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is equivalent to saying: &lt;strong&gt;&lt;em&gt;Hey remember that user with that specific ID, let's just pretend he doesn't exist anymore&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This approach eliminates all of the problems listed above, but will need some refactoring on the application layer so that deleted records do not show up in Read queries.&lt;/p&gt;

&lt;h2&gt;
  
  
  Soft Delete in Entity Framework Core
&lt;/h2&gt;

&lt;p&gt;Let's do a deep dive into how to implement &lt;code&gt;Soft Delete&lt;/code&gt; in EF Core:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Define the interface
&lt;/h3&gt;



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

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Implement the Interface
&lt;/h3&gt;

&lt;p&gt;Any Domain Entity that supports Soft Delete would have to implement this interface so that we can later check to see if we need to Soft Delete the record or Hard Delete it.&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 AppUser : ISoftDeletable
{
  [Key]
  [DatabaseGenerated(DatabaseGenerated.Identity)]
  public uint64_t UserId { get; set; }

  [Required]
  public string FirstName { get; set; } = string.Empty;

  [Required]
  public string LastName { get; set; } = string.Empty;

  [Required]
  public string Email { get; set; } = string.Empty;

  bool IsDeleted { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Add an Interceptor for Soft Deletable Entities
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors"&gt;Interceptors&lt;/a&gt; are a powerful way to intercept requests to database. It's a way to tap into what Entity Framework is asking the database to do and change it the way we want. Let's create an &lt;strong&gt;Interceptor&lt;/strong&gt; to Soft Delete entities that support Soft Deletion:&lt;br&gt;
&lt;/p&gt;

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

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

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

        return base.SavingChangesAsync(eventData, result, cancellationToken);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Register the SoftDeletable Interceptor
&lt;/h3&gt;

&lt;p&gt;Let's register the Interceptor as a singleton service into DI Container&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.services.AddSingleton&amp;lt;SoftDeleteInterceptor&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Configure DbContext to use the Interceptor
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.services.AddDbContext&amp;lt;AppDbContext&amp;gt;(
    (serviceProvider, options) =&amp;gt; options
        .UseSqlServer(connectionString)
        .AddInterceptors(
            serviceProvider
              .GetRequiredService&amp;lt;SoftDeleteInterceptor&amp;gt;()
          )
    );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's it, we've successfully configured Soft Delete in our application.&lt;/p&gt;

&lt;h3&gt;
  
  
  But Wait! Aren't we missing something?
&lt;/h3&gt;

&lt;p&gt;If you read the article carefully enough, you'd remember the line:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Hey remember that user with that specific ID, let's just pretend he doesn't exist anymore&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This is problematic because the data is not physically deleted and when we ask for all the records for a certain entity (that supports Soft Delete) it would return us the Soft Deleted records as well, which we don't want. So how do we tackle this problem?&lt;/p&gt;

&lt;p&gt;Let's just add a &lt;strong&gt;Query Filter&lt;/strong&gt; in our DbContext to exclude the Soft Deleted records:&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 AppDbContext(
    DbContextOptions&amp;lt;AppDbContext&amp;gt; options) : DbContext(options)
{
    public DbSet&amp;lt;AppUser&amp;gt; Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&amp;lt;AppUser&amp;gt;().HasQueryFilter(u =&amp;gt; !u.IsDeleted);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's it. We have successfully configured our App to use Soft Deletion.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>aspnet</category>
      <category>dotnet</category>
      <category>programming</category>
    </item>
    <item>
      <title>Introduction to CLR | Part I</title>
      <dc:creator>muneeb-devp</dc:creator>
      <pubDate>Fri, 04 Aug 2023 00:06:58 +0000</pubDate>
      <link>https://dev.to/muneebdevp/introduction-to-clr-part-i-1emi</link>
      <guid>https://dev.to/muneebdevp/introduction-to-clr-part-i-1emi</guid>
      <description>&lt;h1&gt;
  
  
  CLR 101
&lt;/h1&gt;

&lt;p&gt;CLR (&lt;strong&gt;Common Language Runtime&lt;/strong&gt;) is Microsoft's version of JVM (Java Virtual Machine). It's essentially a runtime engine that is at the core of .NET Framework. CLR does most of the heavy lifting for every kind of software that you write in the .NET world. CLR is what actually executes the instructions you wrote in your software on a processor-level and provides a variety of features (discussed below) to help you write more robust and secure software. &lt;/p&gt;

&lt;p&gt;Here's a list (not comprehensive by any means) of features that CLR provides to programmers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Dynamic Memory Management&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;JIT (Just In Time) Compilation of IL code&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Garbage Collection&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Type Safety&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Thread Management&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Cross-language interoperability&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Exception Handling&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Reflection&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Enforces CTS (Comman Type System)&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Code Execution&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Security&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;First released in 1999, alongside the .NET Framework and C# programming language, the .NET framework has evolved into a robust framework for developing performant and enterprise level Console, Web and Mobile applications. Windows operating system itself is built on top of .NET framewok, leveraging many of the core features of CLR described above. This has allowed windows to become the dominant operating system in the desktop OS market. &lt;/p&gt;




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

&lt;h2&gt;
  
  
  Compilation
&lt;/h2&gt;

&lt;p&gt;Traditional compilers were built to target a certain architecture of processor, directly translating source code into machine code. All this changed with the advent of Java and JVM, which instead compiled source code into byte-code, an intermediate language that could be interpreted by the JVM and then executed on any kind of platform, making the code truely portable. Microsoft took inspiration from this approach and bulit its own version in 1999. Initially .NET framework was just an abstraction layer over the Win32 API and COM but slowly evolved into a much bigger ecosystem for software development. The Common Language Runtime is &lt;strong&gt;language-agnostic&lt;/strong&gt;, which means when executing the IL instructions, it does not know what programming language it was written in. Puzzled? How is that even possible? &lt;/p&gt;

&lt;p&gt;The answer is &lt;strong&gt;CLS (Common Language Specification)&lt;/strong&gt;, it's a specification developed by Microsoft and standardized by ECMA that defined a common set of features and rules that must be adhered to generate assemblies for .NET. Any compiler that conforms to the CLS specification is qualified to produce assemblies  that can be executed by CLR and can even be used by other programming languages that have a CLS compliant compiler. At the time of writing, there are about a dozen or so languages that have CLS compliant compilers and can produce IL code, including some of the most popular languages such as &lt;strong&gt;Python, PHP, Prolog, Smalltalk, LISP, COBOL, Haskell, Lua, Ada, VB.NET, C#, F#&lt;/strong&gt; to name a few. &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---SKmrLz4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.c-sharpcorner.com/article/temp/118821/Images/Screenshot%25202023-08-03%2520161202.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---SKmrLz4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.c-sharpcorner.com/article/temp/118821/Images/Screenshot%25202023-08-03%2520161202.png" alt="Compilation process" width="362" height="229"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Now the next question that comes to mind is, what even is a &lt;strong&gt;Managed module&lt;/strong&gt;? Simply put, Managed module is a file type specific to Microsoft called &lt;strong&gt;PE32&lt;/strong&gt; (Portal Executable 32) or &lt;strong&gt;PE32+&lt;/strong&gt; (Portable Executable for 64bit systems). Here's a brief (not at all comprehensive by design) description of a PE32 file parts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;PE32/PE32+ Header&lt;/strong&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*   Tells about the type of file i.e. is this a console app, a GUI or a DLL.&amp;amp;nbsp;
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;CLR header&lt;/strong&gt;&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*   Contains information to be interpreted by CLR
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;  Contains the CLR version number&lt;/li&gt;
&lt;li&gt;  metadata for the entry point of the managed module (Main method)&lt;/li&gt;
&lt;li&gt;  location and size of metadata for the module&lt;/li&gt;
&lt;li&gt;  resources&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Metadata&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*   Contains two main types of metadata tables:

        *   A table that describes the types defined in the module (classes, enums, structs, delegates e.t.c)
*   A table that defines the members (methods) referenced by the code
&lt;/code&gt;&lt;/pre&gt;


&lt;/li&gt;
&lt;li&gt;

&lt;p&gt;&lt;strong&gt;IL Code&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*   Code produced by the compiler
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
&lt;li&gt;  IL code is CPU-agnostic, you can think of it as an OO version of machine code.&lt;/li&gt;
&lt;li&gt;  That is what gets translated into machine code by CLR and then executed&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Any CLS compliant compiler for .NET is required to add all the metadata in the same file as the IL code. This tightly binds the managed module. Metdata for a managed module includes the defined types, methods, imports and dependencies on other modules and even all the information related to what parameter a certain method expects. This is what allows Visual Studio's &lt;strong&gt;IntelliSense&lt;/strong&gt; feature to give you exact information for each type, method, property, event e.t.c. Metdata also plays a cruicial role in code-verification process (a subject for future article), serialization of objects, and garbage collection.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;But wait, compilers produce Managed Modules but in the .NET world you'll almost always hear about &lt;strong&gt;Assemblies (exe/dll file)&lt;/strong&gt; as the output of a build. &lt;strong&gt;So how do Managed Modules and Assemblies differ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Simply put, &lt;strong&gt;Assemblies are a logical grouping of one or more managed modules and any associated resource files.&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dVrAwa4u--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.c-sharpcorner.com/article/introduction-to-clr/Images/Screenshot%25202023-08-03%2520214310.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dVrAwa4u--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.c-sharpcorner.com/article/introduction-to-clr/Images/Screenshot%25202023-08-03%2520214310.png" alt="Managed modules in assemblies" width="554" height="285"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;CLR works with Assemblies and not Managed Modules directly, so compiler by default automate the job of grouping multiple managed modules into an Assembly. The important thing to note about an Assembly is the &lt;strong&gt;Manifest&lt;/strong&gt;. The &lt;strong&gt;Assembly Manifest&lt;/strong&gt; itself is just a data table that describes what source files are included in the Assembly, publicly exported types and resource or data files associated with an assembly (if any). &lt;strong&gt;Assemblies are stand-alone components, they have a name and version number, dependency information (i.e. referenced assemblies)&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Now let's put all this together into a simple program to illustrate how CLR executes the code you write, &lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace Greeting
{
    class Hello {         
        static void Main()
        {
            Console.WriteLine("Hello");
            Console.WriteLine("Goodbye");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The compiler first checks all of the types that are being referenced by the &lt;strong&gt;Main&lt;/strong&gt; method, in our example it only refers to a single type &lt;strong&gt;System.Console.&lt;/strong&gt; An internal data structure in the CLR holds references to the address that contains the code for each method. When initializing this datastructure, CLR adds each entry to an internal function, which for the sake of argument we shall call JITCompiler here. The JITCompiler method bears the responsibility of compiling the method's IL code to native machine code and executing it. Here's a visual illustration of the process:&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wzqsYWDg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.c-sharpcorner.com/article/introduction-to-clr/Images/Screenshot%25202023-08-03%2520223323.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wzqsYWDg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://www.c-sharpcorner.com/article/introduction-to-clr/Images/Screenshot%25202023-08-03%2520223323.png" alt="" width="694" height="675"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;That's about it for this article. We'll go into more depth into CLR's internal working in future articles. &lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>programming</category>
      <category>computerscience</category>
    </item>
  </channel>
</rss>
