<?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.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F446219%2F25e8cb7a-748e-48da-9478-128692644a92.png</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>I turned C# compiler errors into a game of Snake</title>
      <dc:creator>muneeb-devp</dc:creator>
      <pubDate>Mon, 09 Nov 2026 16:40:21 +0000</pubDate>
      <link>https://dev.to/muneebdevp/i-turned-c-compiler-errors-into-a-game-of-snake-dml</link>
      <guid>https://dev.to/muneebdevp/i-turned-c-compiler-errors-into-a-game-of-snake-dml</guid>
      <description>&lt;p&gt;Every C# editor has a tiny graphics card hiding in it. It only draws three colours, it only refreshes when you type, and most people spend their whole day trying to make it go blank.&lt;/p&gt;

&lt;p&gt;It's the error squiggle. I built Snake on it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdsjh6uz9xnjy38b315nk.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdsjh6uz9xnjy38b315nk.gif" alt="Snake being played with red and yellow squiggles in a C# file" width="720" height="331"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.nuget.org/packages/Squiggly" rel="noopener noreferrer"&gt;Squiggly&lt;/a&gt; is a NuGet package. Add it to a project, create a file with &lt;code&gt;// squiggly&lt;/code&gt; on the first line, press Ctrl+. and pick &lt;strong&gt;New game: Snake&lt;/strong&gt;. The snake's head is a red error. Its body is a row of yellow warnings. The food is those faint grey dots you've been ignoring for years.&lt;/p&gt;

&lt;p&gt;It works in Visual Studio, VS Code (with C# Dev Kit) and Rider, and there's no plugin for any of them. It's just an analyzer.&lt;/p&gt;

&lt;p&gt;There's Tetris and Minesweeper too, because once you have a screen, you kind of have to.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wait, what's an analyzer?
&lt;/h2&gt;

&lt;p&gt;If you've never written one: Roslyn, the C# compiler, lets you plug in your own checks. An &lt;strong&gt;analyzer&lt;/strong&gt; is a class that gets handed your code and can report &lt;strong&gt;diagnostics&lt;/strong&gt;. Those are the same kind of thing as &lt;code&gt;CS0103: The name 'x' does not exist&lt;/code&gt;, and your editor draws them as squiggles. The severity picks the colour: errors are red, warnings are yellow (green in Visual Studio), and info shows up as a few grey dots.&lt;/p&gt;

&lt;p&gt;The other half is &lt;strong&gt;code fixes&lt;/strong&gt;, which is the lightbulb menu. A code fix provider says "I know how to fix diagnostic X" and offers menu entries. Each entry is an edit to the file.&lt;/p&gt;

&lt;p&gt;So you've got something that can draw coloured marks anywhere in a file, and a menu of buttons that can edit that file. That's a screen and a controller. I'm sorry. I couldn't not.&lt;/p&gt;

&lt;h2&gt;
  
  
  The screen is a comment
&lt;/h2&gt;

&lt;p&gt;An analyzer can only underline text that already exists, so the game needs something to draw on. When you start a game, Squiggly writes a block of comments into the file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// squiggly v1 game=snake seed=8812
//|........................................|
//|........................................|
//|........................................|
   (10 rows like this)
// keys:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each board cell is two characters wide, because monospace characters are about twice as tall as they are wide, and two of them make a roughly square cell. To light up a cell, the analyzer reports a diagnostic that covers those two characters. That's the whole rendering engine. A pixel is a &lt;code&gt;Diagnostic&lt;/code&gt; with a two-character &lt;code&gt;Location&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And since it's all comments, the file still compiles. Well, it compiles until a red pixel shows up. More on that later.&lt;/p&gt;

&lt;h2&gt;
  
  
  Version one was miserable to play
&lt;/h2&gt;

&lt;p&gt;My first plan was that the lightbulb would be the gamepad. Caret on the header, Ctrl+., &lt;strong&gt;Move up&lt;/strong&gt;. Ctrl+., &lt;strong&gt;Move up&lt;/strong&gt;. Ctrl+., &lt;strong&gt;Move left&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It worked, and it was awful. Playing Snake through a context menu feels like filing a tax return. In Rider I was pressing Option+Enter for every single step, and it got old fast.&lt;/p&gt;

&lt;p&gt;What I actually wanted was arrow keys. But analyzers can't see the keyboard. No key events, no mouse, no clock. They get the text of the file and that's it. Arrow keys don't change the text, they just move the caret, so as far as Roslyn knows, nothing happened.&lt;/p&gt;

&lt;p&gt;So the controls had to be text too. There's a &lt;code&gt;// keys:&lt;/code&gt; line under the board, and you type on it: &lt;code&gt;w a s d&lt;/code&gt; to steer. Each letter changes the document, the editor re-runs the analyzer, and the snake moves one step. If you hold &lt;code&gt;d&lt;/code&gt; down, key repeat makes the snake glide across the board, which is as close to real time as this thing will ever get.&lt;/p&gt;

&lt;h2&gt;
  
  
  The analyzer isn't allowed to remember anything
&lt;/h2&gt;

&lt;p&gt;This was the part I found most interesting.&lt;/p&gt;

&lt;p&gt;My first header stored the whole game: direction, head position, tail, where the food was. Something like &lt;code&gt;dir=R head=10,5 tail=LL food=0,2&lt;/code&gt;. But once you're typing moves, that header is stale straight away, because an analyzer can't write to the file. Only code fixes can.&lt;/p&gt;

&lt;p&gt;Keeping the game in memory doesn't work either. Roslyn runs analyzers concurrently, reloads them whenever it feels like it, and sometimes runs them on an older snapshot of the document. A static field holding "the current game" would drift away from what's on screen pretty quickly. Roslyn's own analyzer rules warn you about exactly this.&lt;/p&gt;

&lt;p&gt;So the header shrank to two things, the game and a seed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// squiggly v1 game=snake seed=8812
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On every keystroke, Squiggly starts a brand new game from that seed and replays every key on the keys line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="n"&gt;GameState&lt;/span&gt; &lt;span class="nf"&gt;Replay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;IGame&lt;/span&gt; &lt;span class="n"&gt;game&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;GameState&lt;/span&gt; &lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="n"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;game&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ParseKeys&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;game&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;Step&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then it draws whatever state it ends up with. Every frame is computed from scratch. That sounds wasteful, but replaying a 2,000-move game and rendering it takes about a quarter of a millisecond on my M1 Pro, and nobody is getting to 2,000 moves of Snake in a comment.&lt;/p&gt;

&lt;p&gt;Doing it this way gave me a bunch of things for free:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Undo.&lt;/strong&gt; Ctrl+Z deletes the last key, and the snake takes a step back.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Save games.&lt;/strong&gt; The file is the save. Commit it, push it, open a PR with your high score.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cheating.&lt;/strong&gt; Died? Delete the last few letters. I can't stop you, and honestly I don't want to.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Tests.&lt;/strong&gt; Same seed plus same keys always gives the same board, so the tests check exact boards for known games.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Randomness that doesn't flicker
&lt;/h3&gt;

&lt;p&gt;All of that only holds if the randomness repeats. If the food spawned somewhere new every time the analyzer ran, it would teleport around while you typed. So there's no &lt;code&gt;System.Random&lt;/code&gt; and no clock anywhere in the game code.&lt;/p&gt;

&lt;p&gt;Squiggly uses SplitMix64, a tiny random number generator you can write in about a dozen lines, seeded with the game seed and the move number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Prng&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;For&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Seed&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Tick&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stream&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;"Seed 8812, move 40" puts the food in the same cell on every machine. I also didn't want &lt;code&gt;System.Random&lt;/code&gt; because its algorithm is an implementation detail that has changed between .NET versions, and I didn't want your saved game to change when you updated the SDK.&lt;/p&gt;

&lt;h2&gt;
  
  
  Things the IDEs taught me
&lt;/h2&gt;

&lt;p&gt;Before writing any game code, I built a throwaway spike to see whether the idea held up at all. A few things I learned:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Rider won't offer code fixes on hidden diagnostics.&lt;/strong&gt; My plan was to hang the menu on an invisible diagnostic on the header line. Rider just ignored it. So the visible one, the HUD that says "Snake, score 4, length 7", became the menu anchor instead.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The colours belong to your theme, not to me.&lt;/strong&gt; I get three severities and that's it. VS Code draws them red, yellow and grey. Visual Studio makes warnings green. So the palette is "whatever your theme thinks an error looks like".&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;If an analyzer throws, the IDE switches it off.&lt;/strong&gt; So everything is wrapped, and an internal error shows up as a warning on the header instead of killing the game.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Code fixes need their own DLL.&lt;/strong&gt; Roslyn wants analyzers and code fixes in separate assemblies, since the command-line compiler loads analyzers but has no use for editor code. The package ships two DLLs, with the game engine compiled into the analyzer.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Not slowing down your actual code
&lt;/h2&gt;

&lt;p&gt;The analyzer runs on every file in your project, and almost none of them are games. So the first thing it does is check the first five lines for &lt;code&gt;// squiggly&lt;/code&gt;. If that's not there, it stops. On a 5,000-line file that check takes about 90 nanoseconds and allocates nothing.&lt;/p&gt;

&lt;p&gt;Still, put it in its own little "Arcade" project, not in your work code. The pixels are real diagnostics, so a red pixel is a real compile error, and &lt;code&gt;dotnet build&lt;/code&gt; fails while a game is in progress. Install it in your main project and you'll get the most honest CI failure of your career: build failed, losing at Snake.&lt;/p&gt;

&lt;p&gt;(If you want a green build mid-game, you can lower the severities in &lt;code&gt;.editorconfig&lt;/code&gt;. Your snake changes colour, but that's the deal.)&lt;/p&gt;

&lt;h2&gt;
  
  
  Tetris and Minesweeper
&lt;/h2&gt;

&lt;p&gt;Tetris uses the same trick. &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;d&lt;/code&gt; move, &lt;code&gt;w&lt;/code&gt; rotates, &lt;code&gt;s&lt;/code&gt; drops a row and &lt;code&gt;x&lt;/code&gt; slams it down. The falling piece is red, locked blocks are yellow, and the grey dots show where it's going to land.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvru600s1qbafrh42kz12.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvru600s1qbafrh42kz12.gif" alt="Tetris being played with squiggles in a C# file" width="720" height="552"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Minesweeper is the odd one out. You pick cells instead of steering, so every covered cell gets its own diagnostic, and the lightbulb on a cell offers &lt;strong&gt;Reveal&lt;/strong&gt; or &lt;strong&gt;Flag&lt;/strong&gt;. This is the one game where the menu is actually nice to use. Your first reveal is always safe, because I'm not a monster.&lt;/p&gt;

&lt;h2&gt;
  
  
  Try it
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;dotnet new console &lt;span class="nt"&gt;-n&lt;/span&gt; Arcade &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nb"&gt;cd &lt;/span&gt;Arcade
dotnet add package Squiggly
&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"// squiggly"&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; Game.cs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open &lt;code&gt;Game.cs&lt;/code&gt;, put the caret on line 1, press Ctrl+. (Alt+Enter in Rider) and pick a game. Then click at the end of the &lt;code&gt;// keys:&lt;/code&gt; line and start typing.&lt;/p&gt;

&lt;p&gt;The code is on GitHub at &lt;a href="https://github.com/muneeb-devp/squiggly" rel="noopener noreferrer"&gt;muneeb-devp/squiggly&lt;/a&gt;. If you've never written an analyzer, there's a &lt;a href="https://github.com/muneeb-devp/squiggly/blob/main/docs/HOW-IT-WORKS.md" rel="noopener noreferrer"&gt;beginner's guide&lt;/a&gt; in the repo that follows one keystroke all the way through. It's a surprisingly good way to learn how analyzers and code fixes work, since your bugs literally crawl across the screen.&lt;/p&gt;

&lt;p&gt;If you get a good Snake score, post your keys line in the comments. I'll replay it. I'll probably believe you.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>gamedev</category>
      <category>showdev</category>
    </item>
    <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;&amp;nbsp;&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" rel="noopener noreferrer"&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.&amp;nbsp;&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&amp;nbsp;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.&amp;nbsp;&lt;/p&gt;




&lt;h2&gt;
  
  
  &amp;nbsp;
&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&amp;nbsp;&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?&amp;nbsp;&lt;/p&gt;

&lt;p&gt;The answer is&amp;nbsp;&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&amp;nbsp; 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&amp;nbsp;&lt;strong&gt;Python, PHP, Prolog, Smalltalk, LISP, COBOL, Haskell, Lua, Ada, VB.NET, C#, F#&lt;/strong&gt;&amp;nbsp;to name a few.&amp;nbsp;&lt;/p&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.c-sharpcorner.com%2Farticle%2Ftemp%2F118821%2FImages%2FScreenshot%25202023-08-03%2520161202.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.c-sharpcorner.com%2Farticle%2Ftemp%2F118821%2FImages%2FScreenshot%25202023-08-03%2520161202.png" alt="Compilation process" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;Now the next question that comes to mind is, what even is a&amp;nbsp;&lt;strong&gt;Managed module&lt;/strong&gt;? Simply put, Managed module is a file type specific to Microsoft called&amp;nbsp;&lt;strong&gt;PE32&lt;/strong&gt;&amp;nbsp;(Portal Executable 32) or&amp;nbsp;&lt;strong&gt;PE32+&lt;/strong&gt;&amp;nbsp;(Portable Executable for 64bit systems). Here's a brief (not at all comprehensive by design) description of a&amp;nbsp;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&amp;nbsp;&lt;strong&gt;IntelliSense&lt;/strong&gt;&amp;nbsp;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;&amp;nbsp;&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,&amp;nbsp;&lt;strong&gt;Assemblies are a logical grouping of one or more managed modules and any associated resource files.&lt;/strong&gt;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.c-sharpcorner.com%2Farticle%2Fintroduction-to-clr%2FImages%2FScreenshot%25202023-08-03%2520214310.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.c-sharpcorner.com%2Farticle%2Fintroduction-to-clr%2FImages%2FScreenshot%25202023-08-03%2520214310.png" alt="Managed modules in assemblies" width="800" height="400"&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&amp;nbsp;&lt;strong&gt;Manifest&lt;/strong&gt;. The&amp;nbsp;&lt;strong&gt;Assembly Manifest&lt;/strong&gt;&amp;nbsp;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&amp;nbsp;version number, dependency information (i.e. referenced assemblies)&lt;/strong&gt;.&amp;nbsp;&lt;/p&gt;

&lt;p&gt;&amp;nbsp;&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,&amp;nbsp;&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;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;The compiler first checks all of the types that are being referenced by the&amp;nbsp;&lt;strong&gt;Main&lt;/strong&gt;&amp;nbsp;method, in our example it only refers to a single type&amp;nbsp;&lt;strong&gt;System.Console.&lt;/strong&gt;&amp;nbsp;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;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.c-sharpcorner.com%2Farticle%2Fintroduction-to-clr%2FImages%2FScreenshot%25202023-08-03%2520223323.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.c-sharpcorner.com%2Farticle%2Fintroduction-to-clr%2FImages%2FScreenshot%25202023-08-03%2520223323.png" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&amp;nbsp;&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.&amp;nbsp;&lt;/p&gt;

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