<?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 Hamid Musayev on Medium]]></title>
        <description><![CDATA[Stories by Hamid Musayev on Medium]]></description>
        <link>https://medium.com/@hamidmusayev?source=rss-4a305044804f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UfqEDrRQy7dHaE6EJUeBHg@2x.jpeg</url>
            <title>Stories by Hamid Musayev on Medium</title>
            <link>https://medium.com/@hamidmusayev?source=rss-4a305044804f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:54:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamidmusayev/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[How to develop an API gateway using YARP Reverse Proxy]]></title>
            <link>https://medium.com/@hamidmusayev/how-to-develop-an-api-gateway-using-yarp-reverse-proxy-ff6e606a8d12?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff6e606a8d12</guid>
            <category><![CDATA[yarp]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 08:05:15 GMT</pubDate>
            <atom:updated>2025-07-16T08:05:15.693Z</atom:updated>
            <content:encoded><![CDATA[<p>YARP (Yet Another Reverse Proxy) is Microsoft’s modern, highly extensible reverse proxy built with ASP.NET Core. In this post, I’ll show you how to horizontally scale your .NET Core app using YARP with minimal boilerplate and maximum flexibility.</p><h4>Why Horizontal Scaling?</h4><p>Vertical scaling (adding more CPU/RAM) has limits. Horizontal scaling means spinning up multiple instances of your app and distributing traffic across them.</p><h3>Overview of the Architecture</h3><pre>[Client]<br>   |<br>   v<br>[YARP Reverse Proxy]  &lt;-- .NET app with YARP (MyProxy)<br>   |       |       |<br>   v       v       v<br>[App1]  [App2]  [App3]   &lt;-- Your actual app instances (MyApp instances)</pre><h3>Project Setup</h3><p>We’ll create two .NET Core projects:</p><ol><li><strong>MyApp</strong>: The app to be scaled out.</li><li><strong>MyProxy</strong>: A YARP-powered reverse proxy that routes to multiple MyApp instances.</li></ol><h4>1. Create the Backend App</h4><pre>dotnet new web -n MyApp</pre><p>In Program.cs:</p><pre>var builder = WebApplication.CreateBuilder(args);<br>var app = builder.Build();<br><br>app.MapGet(&quot;/&quot;, () =&gt;<br>{<br>  var host = Environment.MachineName;<br>  return $&quot;Hello from {host} at {DateTime.Now}&quot;;<br>});<br><br>app.Run();</pre><p>Run multiple instances on different ports:</p><pre>dotnet run  — urls “http://localhost:5001&quot;<br>dotnet run  - urls &quot;http://localhost:5002&quot;<br>dotnet run  - urls &quot;http://localhost:5003&quot;<br></pre><h4>2. Create the YARP Reverse Proxy</h4><pre>dotnet new web -n MyProxy<br>cd MyProxy<br>dotnet add package Yarp.ReverseProxy</pre><p>In Program.cs:</p><pre>using Yarp.ReverseProxy.Configuration;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddReverseProxy()<br>    .LoadFromMemory(GetRoutes(), GetClusters());<br><br>var app = builder.Build();<br>app.MapReverseProxy();<br>app.Run();<br><br>// YARP route config<br>static IReadOnlyList&lt;RouteConfig&gt; GetRoutes() =&gt; new[]<br>{<br>    new RouteConfig<br>    {<br>        RouteId = &quot;default&quot;,<br>        ClusterId = &quot;backend&quot;,<br>        Match = new RouteMatch { Path = &quot;{**catch-all}&quot; }<br>    }<br>};<br><br>static IReadOnlyList&lt;ClusterConfig&gt; GetClusters() =&gt; new[]<br>{<br>    new ClusterConfig<br>    {<br>        ClusterId = &quot;backend&quot;,<br>        Destinations = new Dictionary&lt;string, DestinationConfig&gt;<br>        {<br>            { &quot;app1&quot;, new DestinationConfig { Address = &quot;http://localhost:5001&quot; } },<br>            { &quot;app2&quot;, new DestinationConfig { Address = &quot;http://localhost:5002&quot; } },<br>            { &quot;app3&quot;, new DestinationConfig { Address = &quot;http://localhost:5003&quot; } }<br>        },<br>        LoadBalancingPolicy = &quot;RoundRobin&quot;<br>    }<br>};</pre><p>Now run your proxy:</p><pre>dotnet run  — urls “http://localhost:5000&quot;</pre><h4>3. Test It Out</h4><p>Navigate to http://localhost:5000. Refresh the page and you’ll see responses rotating between your backend instances. Just like that — you’ve horizontally scaled your app!</p><p><strong>What’s Happening Under the Hood?</strong></p><ul><li>YARP listens on port 5000</li><li>Incoming requests are matched by route (catch-all)</li><li>Requests are load-balanced across the three destination instances</li><li>You can switch to other load balancing strategies (LeastRequests, Random, etc.)</li></ul><h3>Going to Production — Containerize Your Services</h3><p>Create Dockerfile for each project. Example for MyApp:</p><pre>FROM mcr.microsoft.com/dotnet/aspnet:7.0<br>WORKDIR /app<br>COPY ./bin/Release/net7.0/publish/ .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;MyApp.dll&quot;]</pre><p>Use Docker Compose or Kubernetes</p><pre>services:<br>  app:<br>    image: myapp<br>    deploy:<br>      replicas: 3<br><br>  proxy:<br>    image: myproxy<br>    ports:<br>      - &quot;80:80&quot;</pre><p>Or set up ingress with Kubernetes and let YARP live inside a service mesh.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff6e606a8d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your ASP.NET Core APIs with a Reusable Memory Cache Attribute]]></title>
            <link>https://medium.com/@hamidmusayev/supercharge-your-asp-net-core-apis-with-a-reusable-memory-cache-attribute-d8ec143dc34f?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8ec143dc34f</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 10:48:36 GMT</pubDate>
            <atom:updated>2025-07-14T08:31:59.064Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Tired of repeating the same memory caching logic in every controller? What if you could cache any endpoint with a single line of code?</em></blockquote><h3>Why Memory Caching Matters</h3><p>When building APIs, repeated calls to the same logic — like database queries or external service calls — can kill performance. That’s where caching shines. ASP.NET Core’s IMemoryCache is blazing fast and perfect for storing frequently accessed data in RAM.</p><p>But here’s the catch: using it manually everywhere leads to messy, repetitive code.</p><p><strong>So let’s automate it.</strong></p><p>We’ll create a powerful <strong>attribute-based memory caching system</strong> that’s:</p><ul><li>Non-invasive</li><li>Highly configurable</li><li>Lightning-fast</li><li>Easy to use</li></ul><h3>Step 1: Define the CacheMemory Attribute</h3><pre>[AttributeUsage(AttributeTargets.Method)]<br>public class CacheMemoryAttribute : Attribute<br>{<br>    public int DurationInMinutes { get; set; }<br><br>    public string[] VaryByQuery { get; set; } = [];<br>    public string[] VaryByRoute { get; set; } = [];<br>    public string[] VaryByHeader { get; set; } = [];<br><br>    public string? GroupKey { get; set; }<br>}</pre><p>This attribute will decorate your API methods, and you can control:</p><ul><li>Cache <strong>duration</strong></li><li>Optional Query, Route, Header parameters to <strong>differentiate keys</strong></li><li>Optional Group Key to group caches to invalidate effortless</li></ul><h3>Step 2: Build the Action Filter</h3><pre>public class CacheMemoryFilter: IAsyncActionFilter {<br>   private readonly IMemoryCache _cache;<br>   private static readonly string GroupMapPrefix = &quot;CacheGroupMap:&quot;;<br><br>   public CacheMemoryFilter(IMemoryCache cache) {<br>      _cache = cache;<br>   }<br><br>   public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {<br>      var attribute = context.ActionDescriptor.EndpointMetadata<br>         .OfType &lt; CacheMemoryAttribute &gt; ()<br>         .FirstOrDefault();<br><br>      if (attribute == null) {<br>         await next();<br>         return;<br>      }<br><br>      var request = context.HttpContext.Request;<br>      var routeData = context.RouteData;<br>      var headers = request.Headers;<br>      var keyParts = new List &lt; string &gt; {<br>         request.Path<br>      };<br><br>      foreach(var key in attribute.VaryByQuery.OrderBy(k =&gt; k)) {<br>         if (request.Query.TryGetValue(key, out<br>               var value)) {<br>            keyParts.Add($&quot;q:{key}={value}&quot;);<br>         }<br>      }<br><br>      foreach(var key in attribute.VaryByRoute.OrderBy(k =&gt; k)) {<br>         if (routeData.Values.TryGetValue(key, out<br>               var value)) {<br>            keyParts.Add($&quot;r:{key}={value}&quot;);<br>         }<br>      }<br><br>      foreach(var key in attribute.VaryByHeader.OrderBy(k =&gt; k)) {<br>         if (headers.TryGetValue(key, out<br>               var value)) {<br>            keyParts.Add($&quot;h:{key}={value}&quot;);<br>         }<br>      }<br><br>      var cacheKey = string.Join(&quot;|&quot;, keyParts);<br><br>      if (_cache.TryGetValue(cacheKey, out<br>            var cached)) {<br>         context.HttpContext.Response.Headers[&quot;X-Cache&quot;] = &quot;HIT&quot;;<br>         context.Result = new OkObjectResult(cached);<br>         return;<br>      }<br><br>      var resultContext = await next();<br><br>      if (resultContext.Result is ObjectResult result) {<br>         _cache.Set(cacheKey, result.Value, TimeSpan.FromMinutes(attribute.DurationInMinutes));<br>         context.HttpContext.Response.Headers[&quot;X-Cache&quot;] = &quot;MISS&quot;;<br><br>         if (!string.IsNullOrEmpty(attribute.GroupKey)) {<br>            var groupMapKey = $ &quot;{GroupMapPrefix}{attribute.GroupKey}&quot;;<br><br>            var keys = _cache.GetOrCreate(groupMapKey, entry =&gt; {<br>               entry.SlidingExpiration = TimeSpan.FromHours(1);<br>               return new HashSet &lt; string &gt; ();<br>            });<br><br>            lock(keys) {<br>               keys.Add(cacheKey);<br>            }<br><br>            _cache.Set(groupMapKey, keys);<br>         }<br>      }<br>   }<br>}</pre><p>This filter:</p><ol><li><strong>Checks if caching is enabled</strong> using the [CacheMemory] attribute.</li><li><strong>Builds a unique cache key</strong> using:</li></ol><ul><li>URL path</li><li>Query parameters</li><li>Route values</li><li>Headers</li></ul><p><strong>3. Looks up the key in memory</strong>:</p><ul><li>If found → returns cached result (X-Cache: HIT)</li><li>If not found → runs the action, saves the result in cache (X-Cache: MISS)</li></ul><p><strong>4. Supports cache grouping</strong> (optional) for later bulk invalidation.</p><h3>Step 3: Register as filter</h3><p>In Program.cs:</p><pre>builder.Services.AddMemoryCache();<br>builder.Services.AddControllers(options =&gt;<br>{<br>    options.Filters.Add&lt;CacheMemoryFilter&gt;();<br>});</pre><p>Then your filter is globally available.</p><h3>Step 4: Use It Anywhere</h3><p>Here’s how clean your controller now looks:</p><pre>[HttpGet(&quot;products/{region}&quot;)]<br>[CacheMemory(<br>    DurationInMinutes = 5,<br>    VaryByQuery = new[] { &quot;category&quot;, &quot;page&quot; },<br>    VaryByRoute = new[] { &quot;region&quot; },<br>    VaryByHeader = new[] { &quot;Accept-Language&quot; },<br>    Group = &quot;product&quot;<br>)]<br>public IActionResult GetProducts(string region, string category, int page)<br>{<br>    return Ok(new<br>    {<br>        Region = region,<br>        Category = category,<br>        Page = page,<br>        Time = DateTime.UtcNow<br>    });<br>}</pre><p>No more boilerplate. Just decorate and go.</p><h4>Cache Key Format Example</h4><p>For request:</p><pre>GET /products/us?category=books&amp;page=2<br>Header: Accept-Language: en-US</pre><p>Cache key becomes:</p><pre>/products/eu|q:category=electronics|q:page=2|r:region=eu|h:Accept-Language=az-AZ</pre><h4>Notes</h4><ul><li>The prefix (q:, r:, h:) helps you avoid collisions between similarly named values from different sources.</li><li>You can lowercase and normalize values if needed (e.g. for header casing).</li><li>Be cautious when using user-specific headers (like Authorization) — they may create unnecessary cache fragmentation.</li></ul><h3>Recommended: Invalidate Cache on Data Change</h3><p>Memory cache is fast — but <strong>not smart</strong>. When data changes, stale results could be returned unless we explicitly <strong>invalidate or evict the cache</strong>.</p><p>Here’s how to handle it.</p><h3><strong>Option 1</strong>: Using helper method:</h3><p>Place this method to your code</p><pre>public void InvalidateGroup(string groupKey)<br>{<br>    var groupMapKey = $&quot;{GroupMapPrefix}{groupKey}&quot;;<br><br>    if (_cache.TryGetValue&lt;HashSet&lt;string&gt;&gt;(groupMapKey, out var keys))<br>    {<br>        foreach (var key in keys)<br>        {<br>            _cache.Remove(key);<br>        }<br><br>        _cache.Remove(groupMapKey);<br>    }<br>}</pre><p>And use</p><pre>// Example definition using GroupKey<br>[CacheMemory(DurationInMinutes = 5, VaryByQuery = [&quot;id&quot;], GroupKey = &quot;products&quot;)]<br>public IActionResult GetProduct(int id) =&gt; Ok(…);<br><br>// Somewhere else in your code:<br>cacheFilter.InvalidateGroup(&quot;products&quot;);</pre><h3><strong>Option 2 (Recommended)</strong>: Attribute invalidation:</h3><ol><li>Create CacheGroupKillAttirbute attribute</li></ol><pre>[AttributeUsage(AttributeTargets.Method, Inherited = false)]<br>public class CacheGroupKillAttribute: Attribute<br>{<br>    public string GroupKey { get; }<br><br>    public CacheGroupKillAttribute(string groupKey)<br>    {<br>        GroupKey = groupKey;<br>    }<br>}</pre><p>2. Modify CacheMemoryFilter to Handle Cache Group Killing</p><pre>public class CacheMemoryFilter : IAsyncActionFilter<br>{<br>    private readonly IMemoryCache _cache;<br>    private static readonly string GroupMapPrefix = &quot;CacheGroupMap:&quot;;<br><br>    public CacheMemoryFilter(IMemoryCache cache)<br>    {<br>        _cache = cache;<br>    }<br>    <br>    // Add here<br>    private void InvalidateGroup(string groupKey)<br>    {<br>        var groupMapKey = $&quot;CacheGroupMap:{groupKey}&quot;;<br><br>        if (_cache.TryGetValue&lt;HashSet&lt;string&gt;&gt;(groupMapKey, out var keys))<br>        {<br>            foreach (var key in keys)<br>            {<br>                _cache.Remove(key); // Remove all keys in the group<br>            }<br><br>            _cache.Remove(groupMapKey); // Remove the group map entry itself<br>        }<br>    }<br><br>    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)<br>    {<br>        // Check if the CacheEvict attribute is on the action<br>        var groupKillAttribute = context.ActionDescriptor.EndpointMetadata<br>            .OfType&lt;CacheGroupKillAttribute&gt;()<br>            .FirstOrDefault();<br><br>        if (groupKillAttribute != null)<br>        {<br>            // Kill cache for the specified group before proceeding<br>            InvalidateGroup(groupKillAttribute.GroupKey);<br>        }<br><br>        // Continue with the normal execution</pre><p>3. Using the CacheGroupKillAttribute in Your Controller</p><pre>[HttpPost(&quot;products&quot;)]<br>[CacheGroupKillAttribute(&quot;product&quot;)]  // Invalidate cache for the &quot;product&quot; group<br>public IActionResult UpdateProducts()<br>{<br>    // Update logic here (e.g., save the new product to the database)<br>    return Ok();<br>}</pre><h4>How It Works</h4><ul><li><strong>Step 1</strong>: The CacheGroupKillAttribute is applied to the action method, specifying the GroupKey (e.g., &quot;product&quot;).</li><li><strong>Step 2</strong>: When the action is invoked, the CacheMemoryFilter detects the CacheGroupKillAttribute.</li><li><strong>Step 3</strong>: The filter automatically invalidates all cached keys associated with that group (i.e., all cache entries that have the same GroupKey).</li><li><strong>Step 4</strong>: The controller continues with its normal action logic, and if caching is enabled, it will cache new responses.</li></ul><h3>Conclusion</h3><p>If you’re building modern APIs in ASP.NET Core, performance and clarity go hand-in-hand. This attribute-based memory caching pattern will help you.</p><h4>Why This Pattern</h4><ul><li>Separation of concerns</li><li>DRY principle</li><li>Reusable, maintainable, scalable</li><li>Zero impact on your service layer</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8ec143dc34f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Signatures: The Backbone of Secure File Sharing]]></title>
            <link>https://medium.com/@hamidmusayev/digital-signatures-the-backbone-of-secure-file-sharing-2062f68706f4?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2062f68706f4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 12:57:34 GMT</pubDate>
            <atom:updated>2025-06-11T12:57:34.984Z</atom:updated>
            <content:encoded><![CDATA[<p>In a world where digital content is constantly exchanged, ensuring the authenticity, integrity, and accountability of files is more important than ever. Whether you’re downloading software, sending legal documents, or verifying a financial record, you need a mechanism to trust that what you receive is exactly what was sent — and by whom.</p><p>That mechanism is called a <strong>digital signature</strong>.</p><h3>What Is a Digital Signature?</h3><p>A <strong>digital signature</strong> is a cryptographic construct that serves three essential purposes:</p><ol><li>✅ <strong>Integrity</strong> — Detects if the file has been modified.</li><li>✅ <strong>Authenticity</strong> — Proves the identity of the sender.</li><li>✅ <strong>Non-repudiation</strong> — Prevents the sender from denying they signed it.</li></ol><p>Digital signatures are not the same as file hashes (e.g., MD5, SHA-256). A hash only detects change. A digital signature proves <strong>who</strong> sent the file and <strong>ensures it hasn’t been tampered with</strong>.</p><h3>How Digital Signatures Work</h3><p>Digital signatures rely on <strong>asymmetric cryptography</strong> — a system based on two mathematically linked keys:</p><ul><li><strong>Private Key</strong> — known only to the signer andused to generate signatures.</li><li><strong>Public Key</strong> — shared with others and used to verify signatures.</li></ul><h3>Signing Process (by Sender)</h3><ol><li>The sender calculates a <strong>hash</strong> of the file using a secure algorithm (e.g., SHA-256).</li><li>The hash is <strong>encrypted with the sender’s private key</strong>.</li><li>This encrypted hash becomes the <strong>digital signature</strong>.</li><li>The sender shares:</li></ol><ul><li>The <strong>file</strong></li><li>The <strong>signature</strong></li><li>Their <strong>public key</strong> or a <strong>certificate</strong></li></ul><h3>Verification Process (by Receiver)</h3><ol><li>The receiver computes the <strong>hash</strong> of the received file.</li><li>They decrypt the <strong>signature</strong> using the sender’s <strong>public key</strong> to recover the original hash.</li><li>The two hashes are compared:</li></ol><ul><li>✅ If they match, the file is authentic and untampered.</li><li>❌ If they differ, the file has been altered or forged.</li></ul><h3>Why Digital Signatures Are Secure</h3><ul><li><strong>Tampering / Data Corruption</strong> — Hash mismatch reveals even a 1-bit change.</li><li><strong>Impersonation / Spoofing</strong> — Only the true sender has the private key.</li><li><strong>Man-in-the-Middle Attacks</strong>—Invalid signatures reveal tampering</li><li><strong>Repudiation</strong>—Signer cannot deny authorship (non-repudiation)</li><li><strong>Hash-only forgery</strong> — Encrypted hash ties the file to the signer</li></ul><h3>Example: Signing and Verifying Software Integrity with GPG</h3><p>To show how digital signatures secure file distribution, let’s walk through the full cycle of <strong>signing a file</strong> and then <strong>verifying it</strong> — exactly how open-source developers and DevOps teams ensure trust in distributed artifacts.</p><h3>Scenario</h3><p>You are Alice, a developer releasing a file called secureapp.zip. You want others to verify that this file came from you and hasn’t been tampered with.</p><h3>Step 1: Generate Your GPG Key Pair (One-time setup)</h3><pre>gpg --full-generate-key</pre><p>Follow the prompts:</p><ul><li>Choose key type: <strong>RSA and RSA</strong></li><li>Key size: <strong>4096 bits</strong></li><li>Expiration: optional</li><li>Name, email, and passphrase</li></ul><p>To list your keys:</p><pre>gpg --list-keys</pre><h3>Step 2: Sign the File</h3><pre>gpg --output secureapp.zip.sig --detach-sign secureapp.zip</pre><p>This generates:</p><ul><li>secureapp.zip (original file)</li><li>secureapp.zip.sig (digital signature file)</li></ul><h3>Step 3: Share the File and Your Public Key</h3><p>Export your public key:</p><pre>gpg --export --armor your@email.com &gt; alice_public_key.asc</pre><p>Distribute the file, signature, and public key. Optionally upload your key to a key server.</p><h3>Step 4: Verify the File (Receiver Side — Bob)</h3><h4>Import Alice’s Public Key:</h4><pre>gpg --import alice_public_key.asc</pre><h4>Verify the Signature:</h4><pre>gpg --verify secureapp.zip.sig secureapp.zip</pre><p>Expected output if everything is valid:</p><pre>gpg: Signature made ... using RSA key ID 0xABCD1234<br>gpg: Good signature from &quot;Alice &lt;alice@example.com&gt;&quot;</pre><p>If the file has been altered:</p><pre>gpg: BAD signature</pre><h3>Real-World Applications</h3><ul><li><strong>Software distribution-</strong>Prevent malicious code injection</li><li><strong>Email security (PGP/S/MIME)-</strong>Authenticate sender and detect email tampering</li><li><strong>Code signing (macOS/Windows/Linux)-</strong>Verify executable integrity and origin</li><li><strong>Container image signing-</strong>Ensure container trust in CI/CD pipelines</li><li><strong>Blockchain &amp; smart contracts-</strong>Sign transactions and validate consensus data</li><li><strong>PDF/document signing-</strong>Legally bind authorship and integrity of documents</li></ul><h3>Conclusion</h3><p>Digital signatures are a foundational technology in cybersecurity. They not only ensure that files are <strong>unaltered</strong> but also confirm they were sent by a <strong>legitimate source</strong>. In a world full of spoofing, malware, and tampering, digital signatures give us one thing we desperately need: <strong>trust</strong>.</p><p>If you’re building or distributing software, handling sensitive documents, or just care about digital integrity — it’s time to sign your files.</p><h3>Tools to Work with Digital Signatures</h3><ul><li><strong>GPG/PGP</strong> Signing files, emails, software releases Cross-platform</li><li><strong>OpenSSL</strong> Custom or low-level cryptographic operations Cross-platform</li><li><strong>Sigstore/Cosign</strong> Container signing and CI/CD pipelines DevOps-native (Cloud)</li><li><strong>SignTool</strong> Signing Windows executables and drivers Windows</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2062f68706f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronizing Entity Framework Core Child Collections: A Clean and Reusable Approach]]></title>
            <link>https://medium.com/@hamidmusayev/synchronizing-entity-framework-core-child-collections-a-clean-and-reusable-approach-2ebd8e853f4d?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ebd8e853f4d</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 10:58:11 GMT</pubDate>
            <atom:updated>2026-04-01T11:17:09.481Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern backend development, especially with RESTful APIs with Entity Framework Core, managing nested collections like child entities is a common yet tricky task. The default behavior of EF Core often leads to unexpected results like inserting duplicate records if not managed carefully.</p><p>This article outlines a robust and reusable approach to synchronizing child collections in EF Core using a generic helper extension.</p><h3>Problem</h3><p>Let’s say you have an entity Company with a collection of Products. When updating the Company, you want to:</p><ul><li><strong>Update</strong> existing Products if they exist in the incoming list.</li><li><strong>Add</strong> new Products that are not in the database.</li><li><strong>Delete</strong> Products that exist in the database but are missing from the incoming list.</li></ul><pre>public class Company<br>{<br>    public int CompanyId { get; set; }<br>    public string Name { get; set; } = default!;<br>    public virtual List&lt;Product&gt; Products { get; set; } = new();<br>}<br><br>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string ProductName { get; set; } = default!;<br>    public decimal Price { get; set; }<br>    public int CompanyId { get; set; }<br>    public virtual Company Company { get; set; } = default!;<br>}</pre><h3>Naive Approach and Its Issues</h3><p>A naive update might look like this:</p><pre>public void Update(Company company)<br>{<br>    _context.Companies.Update(company);<br>}</pre><p>This approach tells EF Core to attach the entire object graph as modified. If the Products aren&#39;t tracked, EF will assume they are new and try to insert them, leading to:</p><ul><li>Duplicate product entries</li><li>Insert errors on existing primary keys</li><li>Lack of delete detection for removed items</li></ul><h3>The Proper Way</h3><p>Instead of bulk attaching the object graph, we should:</p><ol><li><strong>Load</strong> the existing company and its products from the database.</li><li><strong>Update</strong> the company’s scalar properties.</li><li><strong>Sync</strong> the child collection with the incoming list.</li></ol><h3>Solution: Use Manual Tracking and Differential Syncing</h3><pre>public async Task Update(Company company)<br>{<br>    await UpdateCompany(company);<br>    await UpdateProducts(company.CompanyId, company.Products);<br>}<br><br>public void UpdateCompany(Company)<br>{<br>    var existingCompany = _context.Companies<br>        .Include(c =&gt; c.Products)<br>        .FirstOrDefault(c =&gt; c.CompanyId == company.CompanyId);<br><br>    if (existingCompany == null)<br>        throw new Exception(&quot;Company not found&quot;);<br><br>    // Update scalar properties of Company<br>    _context.Entry(existingCompany).CurrentValues.SetValues(company);<br>    // We will update Products later<br>    _context.Entry(existingCompany).Collection(s =&gt; s.Products).IsModified = false;<br><br>    await _context.SaveChanges();<br>}<br><br>public void UpdateProducts(int companyId, List&lt;Product&gt; products)<br>{<br>    // Step 1: Update or Add<br>    foreach (var incomingProduct in products)<br>    {<br>        var existingProduct = _context.Products<br>            .FirstOrDefault(p =&gt; p.ProductId == incomingProduct.ProductId);<br><br>        if (existingProduct != null)<br>        {<br>            // Update existing<br>            _context.Entry(existingProduct).CurrentValues.SetValues(incomingProduct);<br>        }<br>        else<br>        {<br>            // Add new<br>            _context.Products.Add(incomingProduct);<br>        }<br>    }<br><br>    // Step 2: Remove deleted ones<br>    var incomingProductIds = new HashSet&lt;int&gt;(products.Select(p =&gt; p.ProductId));<br><br>    var productsToRemove = _dataContext.Products<br>        .Where(p =&gt; p.CompanyId == companyId &amp;&amp; !incomingProductIds.Contains(p.ProductId))<br>        .ToList();<br><br>    _dataContext.Products.RemoveRange(productsToRemove);<br>}</pre><p>This pattern ensures EF Core tracks changes accurately and applies the correct inserts, updates, and deletes.</p><h3>Generic Solution: Generic Collection Sync Helper</h3><p>The SyncCollection helper method abstracts the repetitive logic and provides a centralized, consistent way to:</p><ul><li>Compare incoming and existing child collections using a key selector</li><li>Automatically update existing items</li><li>Insert missing items</li><li>Remove deleted items</li><li>Execute optional custom logic before deleting items (e.g., logging, soft-delete, validation)</li></ul><p>This approach follows the <em>DRY </em>(Don’t Repeat Yourself) principle, keeps business logic clean, and reduces bugs caused by copy-paste logic across your codebase.</p><p>Here is a clean, reusable helper to handle this:</p><pre>public static class EntityCollectionSyncExtensions<br>{<br>    public static void SyncCollection&lt;TChild, TKey&gt;(<br>        this ICollection&lt;TChild&gt; dbCollection,<br>        IEnumerable&lt;TChild&gt; incomingCollection,<br>        Func&lt;TChild, TKey&gt; keySelector,<br>        Action&lt;TChild, TChild&gt; updateAction,<br>        Action&lt;TChild&gt;? addAction = null,<br>        Action&lt;TChild&gt;? onRemove = null,<br>        Func&lt;TChild, bool&gt;? filterForRemoval = null<br>    ) where TChild : class<br>    {<br>        var incomingDict = incomingCollection.ToDictionary(keySelector);<br>        var dbItems = dbCollection.ToList();<br><br>        // Update existing and mark for removal if missing<br>        foreach (var dbItem in dbItems)<br>        {<br>            var key = keySelector(dbItem);<br>            if (incomingDict.TryGetValue(key, out var incomingItem))<br>            {<br>                updateAction(dbItem, incomingItem); // update existing<br>            }<br>            else<br>            {<br>                if (filterForRemoval == null || filterForRemoval(dbItem))<br>                {<br>                    onRemove?.Invoke(dbItem);<br>                    dbCollection.Remove(dbItem); // EF will track this removal<br>                }<br>            }<br>        }<br><br>        // Add new items<br>        foreach (var incomingItem in incomingCollection)<br>        {<br>            var key = keySelector(incomingItem);<br>            if (!dbItems.Any(x =&gt; keySelector(x)?.Equals(key) == true))<br>            {<br>                addAction?.Invoke(incomingItem);<br>                dbCollection.Add(incomingItem);<br>            }<br>        }<br>    }<br>}</pre><h3>Example Usage: Updating a Company and Its Products</h3><p>Assume Product has a primary key ProductId:</p><pre>public async Task Update(Company company)<br>{<br>    var existingCompany = await _context.Companies<br>        .Include(c =&gt; c.Products)<br>        .FirstOrDefaultAsync(c =&gt; c.CompanyId == company.CompanyId);<br><br>    if (existingCompany == null)<br>        throw new Exception(&quot;Company not found&quot;);<br><br>    // Update scalar properties of Company<br>    _context.Entry(existingCompany).CurrentValues.SetValues(company);<br><br>    // Don&#39;t auto-track child collection changes here<br>    _context.Entry(existingCompany).Collection(c =&gt; c.Products).IsModified = false;<br><br>    // Sync Products collection<br>    existingCompany.Products.SyncCollection(<br>        company.Products,<br>        keySelector: p =&gt; p.ProductId,<br>        updateAction: (dbProduct, incomingProduct) =&gt;<br>        {<br>            _context.Entry(dbProduct).CurrentValues.SetValues(incomingProduct);<br>        },<br>        addAction: incomingProduct =&gt;<br>        {<br>            incomingProduct.CompanyId = company.CompanyId;<br>            // If using EF tracking proxies, you can optionally:<br>            // _context.Entry(incomingProduct).State = EntityState.Added;<br>        },<br>        onRemove: dbProduct =&gt;<br>        {<br>            _context.Set&lt;Product&gt;().Remove(dbProduct);<br>        }<br>    );<br><br>    await _context.SaveChangesAsync();<br>}</pre><h3>Conclusion</h3><p>Handling nested collections properly is essential for maintaining data integrity and application performance. With this SyncCollection helper, you can encapsulate your synchronization logic in a reusable, maintainable, and scalable way.</p><p>Use this pattern consistently across your services to simplify update operations and reduce bugs related to collection mismatches in Entity Framework Core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ebd8e853f4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decouple Application Logic Using Domain Events in .NET]]></title>
            <link>https://medium.com/@hamidmusayev/decouple-application-logic-using-domain-events-in-net-d755d9dfd7f9?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d755d9dfd7f9</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Thu, 29 May 2025 12:22:55 GMT</pubDate>
            <atom:updated>2025-05-29T12:23:39.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decouple Application Logic Using Domain Events in .NET</h3><p>In real-world applications, your business logic often needs to trigger multiple side effects. For example, when a user registers:</p><ul><li>You want to save them to the database.</li><li>Send a welcome email.</li><li>Track the registration in analytics.</li></ul><p>A common mistake is putting all that logic inside a single method. This leads to a bloated, tightly coupled service — hard to test, extend, or maintain.</p><h3>🚫 The Problem: Tightly Coupled Code</h3><pre>public class UserService<br>{<br>    public async Task RegisterUser(string email, string password)<br>    {<br>        var user = new User(email, password);<br>        await _userRepository.SaveAsync(user);<br><br>        // tightly coupled<br>        await _emailService.SendWelcomeEmail(user.Email);<br><br>        // tightly coupled<br>        await _analyticsService.TrackUserRegistration(user.Id);<br>    }<br>}</pre><p>Any new logic — like logging, publishing to Kafka, or sending SMS — will just keep growing inside RegisterUser.</p><h3>The Solution: Domain Events</h3><p>Instead of directly invoking other services, we <strong>publish an event</strong>. Other parts of the system can then <strong>subscribe</strong> and react accordingly.</p><h3>Step-by-Step Implementation in .NET</h3><h3>1. Define a Marker Interface</h3><pre>public interface IDomainEvent { }</pre><h3>2. Create the Domain Event</h3><pre>public class UserRegisteredDomainEvent : IDomainEvent<br>{<br>    public Guid UserId { get; }<br>    public string Email { get; }<br><br>    public UserRegisteredDomainEvent(Guid userId, string email)<br>    {<br>        UserId = userId;<br>        Email = email;<br>    }<br>}</pre><h3>3. Define a Generic Event Handler Interface</h3><pre>public interface IDomainEventHandler&lt;TEvent&gt; where TEvent : IDomainEvent<br>{<br>    Task HandleAsync(TEvent domainEvent);<br>}</pre><h3>4. Implement Event Handlers</h3><h4>Welcome Email Handler</h4><pre>public class SendWelcomeEmailHandler : IDomainEventHandler&lt;UserRegisteredDomainEvent&gt;<br>{<br>    private readonly IEmailService _emailService;<br><br>    public SendWelcomeEmailHandler(IEmailService emailService)<br>    {<br>        _emailService = emailService;<br>    }<br><br>    public async Task HandleAsync(UserRegisteredDomainEvent domainEvent)<br>    {<br>        await _emailService.SendWelcomeEmail(domainEvent.Email);<br>    }<br>}</pre><h4>Analytics Handler</h4><pre>public class TrackAnalyticsHandler : IDomainEventHandler&lt;UserRegisteredDomainEvent&gt;<br>{<br>    private readonly IAnalyticsService _analyticsService;<br><br>    public TrackAnalyticsHandler(IAnalyticsService analyticsService)<br>    {<br>        _analyticsService = analyticsService;<br>    }<br><br>    public async Task HandleAsync(UserRegisteredDomainEvent domainEvent)<br>    {<br>        await _analyticsService.TrackUserRegistration(domainEvent.UserId);<br>    }<br>}</pre><h3>5. Build the Dispatcher</h3><pre>public interface IDomainEventsDispatcher<br>{<br>    Task DispatchAsync&lt;TEvent&gt;(TEvent domainEvent) where TEvent : IDomainEvent;<br>}</pre><pre>public class DomainEventsDispatcher : IDomainEventsDispatcher<br>{<br>    private readonly IServiceProvider _serviceProvider;<br><br>    public DomainEventsDispatcher(IServiceProvider serviceProvider)<br>    {<br>        _serviceProvider = serviceProvider;<br>    }<br><br>    public async Task DispatchAsync&lt;TEvent&gt;(TEvent domainEvent) where TEvent : IDomainEvent<br>    {<br>        var handlers = _serviceProvider.GetServices&lt;IDomainEventHandler&lt;TEvent&gt;&gt;();<br>        foreach (var handler in handlers)<br>        {<br>            await handler.HandleAsync(domainEvent);<br>        }<br>    }<br>}</pre><h3>6. Register Everything in Startup.cs / DI Container</h3><pre>services.AddScoped&lt;IDomainEventsDispatcher, DomainEventsDispatcher&gt;();<br>services.AddScoped&lt;IDomainEventHandler&lt;UserRegisteredDomainEvent&gt;, SendWelcomeEmailHandler&gt;();<br>services.AddScoped&lt;IDomainEventHandler&lt;UserRegisteredDomainEvent&gt;, TrackAnalyticsHandler&gt;();</pre><h3>7. Use in Your Business Logic</h3><pre>public class UserService<br>{<br>    private readonly IDomainEventsDispatcher _dispatcher;<br><br>    public async Task RegisterUser(string email, string password)<br>    {<br>        var user = new User(email, password);<br>        await _userRepository.SaveAsync(user);<br>        var evt = new UserRegisteredDomainEvent(user.Id, user.Email);<br>        await _dispatcher.DispatchAsync(evt);<br>    }<br>}</pre><h4>Benefits</h4><ul><li>Clean Separation Each responsibility lives in its own handler.</li><li>Open/Closed Principle Add new handlers without touching core logic.</li><li>Testability You can mock or test handlers independently.</li><li>Flexibility Easily extend with new side effects (e.g., logging, Kafka, audit trail).</li></ul><h4>Final</h4><p>Domain Events are a powerful pattern in <strong>Clean Architecture</strong>. They help break down rigid monolithic logic into flexible, testable pieces.</p><p>If your service classes are bloated and full of side-effects, it’s time to refactor using Domain Events. Future you will thank you.</p><h4>Optional: MediatR Integration</h4><p>If you want less boilerplate, you can use <a href="https://github.com/jbogard/MediatR">MediatR</a> to handle dispatching. It abstracts away the manual dispatcher and works with built-in DI.</p><h3>Bonus: Structure</h3><p>Here’s a clean, <strong>domain-driven structure</strong> tailored for implementing <strong>Domain Events</strong> in a modular .NET application using Clean Architecture principles.</p><pre>/src<br>│<br>├── Core/<br>│   ├── Domain/<br>│   │   ├── Events/<br>│   │   │   └── UserRegisteredDomainEvent.cs<br>│   │   ├── Entities/<br>│   │   │   └── User.cs<br>│   │   └── Interfaces/<br>│   │       └── IDomainEvent.cs<br>│<br>│   ├── Abstractions/<br>│   │   ├── IDomainEventHandler.cs<br>│   │   └── IDomainEventsDispatcher.cs<br>│<br>├── Application/<br>│   ├── Services/<br>│   │   └── UserService.cs<br>│   └── EventHandlers/<br>│       ├── SendWelcomeEmailHandler.cs<br>│       └── TrackAnalyticsHandler.cs<br>│<br>├── Infrastructure/<br>│   ├── Email/<br>│   │   └── EmailService.cs<br>│   ├── Analytics/<br>│   │   └── AnalyticsService.cs<br>│   └── Events/<br>│       └── DomainEventsDispatcher.cs<br>│<br>├── WebAPI/<br>│   └── Program.cs / Startup.cs<br>│<br>├── Tests/<br>│   └── Application.Tests/<br>│       └── UserServiceTests.cs</pre><h4>Explaination</h4><p>Core/Domain/Events/ Contains all Domain Events (e.g., UserRegisteredDomainEvent)</p><p>Core/Domain/Entities/ Your domain models like User, Product, etc.</p><p>Core/Interfaces/ Base interfaces like IDomainEvent Core/Abstractions/ Cross-cutting interfaces like IDomainEventHandler, IDomainEventsDispatcher</p><p>Application/Services/ Application layer logic (e.g., UserService)</p><p>Application/EventHandlers/ Handlers that subscribe to domain events</p><p>Infrastructure/Events/ Concrete DomainEventsDispatcher implementation</p><p>Infrastructure/Email/ Email service or 3rd-party integrations</p><p>WebAPI/ Controllers, Dependency Injection setup</p><p>Tests/ Unit tests, mocks, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d755d9dfd7f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delegates, Events, and Actions in C#: From Zero to Hero]]></title>
            <link>https://medium.com/@hamidmusayev/delegates-events-and-actions-in-c-from-zero-to-hero-2f463681f0d5?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f463681f0d5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Wed, 28 May 2025 21:06:10 GMT</pubDate>
            <atom:updated>2025-05-28T21:06:10.618Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re learning C# and run into <em>delegates</em>, <em>events</em>, or <em>actions</em>, they might sound abstract at first. But once you understand them, they open the door to flexible, event-driven, and clean code — especially when building systems that react to things dynamically.</p><p>Let’s break it down from the ground up.</p><h3>What Is a Delegate?</h3><p>A <strong>delegate</strong> is a <em>type-safe function pointer</em>. It lets you treat methods as variables — pass them around, store them, and invoke them later.</p><h4>Basic Syntax</h4><pre>public delegate int Calculate(int a, int b);</pre><p>This defines a delegate type Calculate that can reference any method with two int parameters returning an int.</p><h4><strong>Example Usage</strong></h4><pre>class Program<br>{<br>    public static int Add(int x, int y) =&gt; x + y;<br>    public static int Multiply(int x, int y) =&gt; x * y;<br><br>    static void Main()<br>    {<br>        Calculate calc = Add;<br>        Console.WriteLine(calc(3, 4));  // 7<br>        calc = Multiply;<br>        Console.WriteLine(calc(3, 4));  // 12<br>    }<br>}</pre><p><strong>Key points:</strong></p><ul><li>Assign any matching method to the delegate.</li><li>Invoke it like a function (calc(3, 4)).</li><li>Pass <strong>behavior</strong> (method logic), not just data.</li></ul><h3>Multicast Delegates</h3><p>Delegates can hold <strong>multiple methods</strong> (an invocation list).</p><h4>Basic Syntax</h4><pre>public delegate void Notify();</pre><h4>Example Usage</h4><pre>class Program<br>{<br>    public static void SendEmail() =&gt; Console.WriteLine(&quot;Email sent.&quot;);<br>    public static void SendSMS() =&gt; Console.WriteLine(&quot;SMS sent.&quot;);<br><br>    static void Main()<br>    {<br>        Notify notify = SendEmail;<br>        notify += SendSMS;<br>        notify();  // Output: Email sent. \n SMS sent.<br>    }<br>}</pre><p><strong>Key points:</strong></p><ul><li>All methods are called in sequence.</li><li>Return values are ignored if delegate returns void.</li><li>Useful for <strong>event systems</strong>.</li></ul><h3>What Is an Event?</h3><p>An <strong>event</strong> is a wrapper around a delegate designed for the <em>publish-subscribe</em> pattern.</p><p>It connects:</p><ul><li><strong>Publisher</strong> → defines and raises the event.</li><li><strong>Subscriber</strong> → attaches handlers to respond when the event fires.</li></ul><h4>Basic Syntax</h4><pre>public class Alarm<br>{<br>    public event Notify OnAlarm;<br><br>    public void Ring()<br>    {<br>        OnAlarm?.Invoke();<br>    }<br>}</pre><h4>Usage Example</h4><pre>class Program<br>{<br>    static void Main()<br>    {<br>        Alarm alarm = new Alarm();<br>        alarm.OnAlarm += () =&gt; Console.WriteLine(&quot;Alarm ringing!&quot;);<br>        alarm.OnAlarm += () =&gt; Console.WriteLine(&quot;Call the police!&quot;);<br>        alarm.Ring();<br>    }<br>}</pre><p><strong>Key points:</strong></p><ul><li>Only the <strong>publisher</strong> can trigger the event (Invoke).</li><li>Subscribers <strong>attach</strong> using += or <strong>detach</strong> with -=.</li><li>Provides <strong>encapsulation</strong> over delegate invocation.</li></ul><h3>Using Built-in EventArgs</h3><p>In real-world events, you often want to pass <em>extra data</em> to the subscribers (not just fire an event).</p><p>C# provides the base class <strong>EventArgs</strong> for that. You create custom event argument types by extending it.</p><h4>Define a Custom EventArgs</h4><pre>public class AlarmEventArgs : EventArgs<br>{<br>    public string Location { get; set; }<br>    public DateTime Time { get; set; }<br><br>    public AlarmEventArgs(string location, DateTime time)<br>    {<br>        Location = location;<br>        Time = time;<br>    }<br>}</pre><h4>Declare the Event with EventHandler</h4><p>Instead of custom delegates, you use:</p><pre>public class Alarm<br>{<br>    // Declare the event using EventHandler&lt;T&gt;<br>    public event EventHandler&lt;AlarmEventArgs&gt; OnAlarm;<br><br>    public void Ring(string location)<br>    {<br>        Console.WriteLine(&quot;Alarm is ringing!&quot;);<br><br>        // Check if there are any subscribers, then invoke the event<br>        OnAlarm?.Invoke(this, new AlarmEventArgs(location, DateTime.Now));<br>    }<br>}</pre><h4>Raise the Event</h4><pre>public void Ring()<br>{<br>    OnAlarm?.Invoke(this, new AlarmEventArgs(&quot;Main Office&quot;, DateTime.Now));<br>}</pre><h4>Subscribe and Handle</h4><pre>alarm.OnAlarm += (sender, e) =&gt;<br>{<br>    Console.WriteLine($&quot;Alarm at {e.Location} on {e.Time}&quot;);<br>};</pre><p><strong>Key points:</strong></p><ul><li>Always follow the pattern: (object sender, EventArgs e).</li><li>Use EventHandler&lt;T&gt; for strong typing.</li><li>Custom EventArgs lets you pass <strong>rich data</strong> to handlers.</li></ul><h3>Built-in Delegate Types: Action, Func, Predicate</h3><p>You don’t always need custom delegates — C# provides <strong>generic delegates</strong>:</p><h4>Action</h4><p>Represents methods that <strong>return void</strong>.</p><pre>Action&lt;int, string&gt; display = (num, text) =&gt;<br>{<br>    Console.WriteLine($&quot;{num}: {text}&quot;);<br>};<br><br>display(1, &quot;Hello&quot;);</pre><h4>Func</h4><p>Represents methods that <strong>return a value</strong>.</p><pre>Func&lt;int, int, int&gt; sum = (a, b) =&gt; a + b;<br>int result = sum(2, 3);  // 5</pre><h4>Predicate</h4><p>Represents a method that <strong>returns a bool</strong>.</p><pre>Predicate&lt;int&gt; isEven = n =&gt; n % 2 == 0;<br>bool check = isEven(4);  // true</pre><p><strong>Key points:</strong></p><ul><li>Use Action for void-returning functions.</li><li>Use Func for value-returning functions.</li><li>Use Predicate for Boolean-returning functions.</li><li>Saves you from declaring custom delegate types.</li></ul><h3>Summary</h3><p>Concept Description Delegate Type-safe function pointer, holds references to methods. Multicast Delegate that holds <strong>multiple</strong> methods. Event Delegate wrapped with restricted access for pub-sub. EventArgs Base class for passing extra data with events. EventHandler Standard event pattern with strong-typed EventArgs. Action / Func Built-in generic delegates for common use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f463681f0d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Events Explained: How Events Can Improve Code Flexibility]]></title>
            <link>https://medium.com/@hamidmusayev/c-events-explained-how-events-can-improve-code-flexibility-38bd204056d8?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/38bd204056d8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 22:25:22 GMT</pubDate>
            <atom:updated>2025-03-25T22:25:22.569Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll explore Events in C#, including how to define and use them. We’ll also demonstrate how Events enhance code flexibility and maintainability with practical examples.</p><blockquote>In C#, <strong>events</strong> are a way for objects to communicate with each other using the <strong>observer pattern</strong>. They are special types of <strong>delegates</strong> that allow a class to notify subscribers when something happens.</blockquote><ul><li>A <strong>publisher</strong> class defines the event.</li><li><strong>Subscribers</strong> register event handler methods to respond when the event is raised.</li></ul><h3><strong>Syntax of Events in C#</strong></h3><h4><strong>Step 1: Define a Delegate</strong></h4><p>A delegate specifies the method signature for event handlers.</p><pre>public delegate void MyEventHandler(string message);</pre><h4><strong>Step 2: Declare an Event in a Class</strong></h4><p>The event is declared using the delegate type.</p><pre>public class Publisher<br>{<br>    public event MyEventHandler MyEvent;  // Declaring an event<br><br>    public void RaiseEvent(string msg)<br>    {<br>        if (MyEvent != null)  // Check if there are subscribers<br>        {<br>            MyEvent(msg);  // Raise the event<br>        }<br>    }<br>}</pre><h4><strong>Step 3: Subscribe to the Event</strong></h4><p>Objects (subscribers) attach event handlers to the event.</p><pre>public class Subscriber<br>{<br>    public void OnEventTriggered(string msg)<br>    {<br>        Console.WriteLine(&quot;Event received: &quot; + msg);<br>    }<br>}<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        Publisher pub = new Publisher();<br>        Subscriber sub = new Subscriber();<br><br>        // Subscribe to the event<br>        pub.MyEvent += sub.OnEventTriggered;<br><br>        // Raise the event<br>        pub.RaiseEvent(&quot;Hello, C# Events!&quot;);<br><br>        // Unsubscribe (optional)<br>        pub.MyEvent -= sub.OnEventTriggered;<br>    }<br>}</pre><h3>Built-in EventHandler Delegate</h3><p>C# provides a built-in EventHandler delegate to simplify event handling.</p><pre>public event EventHandler MyEvent;</pre><p>Or with event arguments:</p><pre>public event EventHandler&lt;MyEventArgs&gt; MyEvent;</pre><p>Where MyEventArgs is a custom class inheriting from EventArgs.</p><h4>Key Points</h4><ul><li>Events are based on <strong>delegates</strong>.</li><li>Only the class that <strong>declares</strong> an event can raise it.</li><li>Subscribers use += to attach event handlers and -= to detach them.</li><li>Use EventHandler or EventHandler&lt;T&gt; for standard event patterns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*a2TzoChjHVYwih_GPqIvAA.png" /></figure><h3>Use Cases of Events in C#</h3><p>Events are useful in scenarios where an action in one part of a program needs to trigger responses in other parts without creating tight coupling. For example:</p><p>UI and User Interaction (WinForms, WPF, Blazor). Button Click Event in WinForms</p><pre>private void button1_Click(object sender, EventArgs e)<br>{<br>    MessageBox.Show(&quot;Button Clicked!&quot;);<br>}</pre><h4>Difference Between Calling a Method Directly vs. Using Events</h4><p><strong>Calling a Method Directly</strong></p><ul><li>The caller knows the exact method to invoke.</li><li><strong>Tightly coupled</strong> (Caller must know about the method’s existence)</li></ul><p><strong>Using Events (Delegates)</strong></p><ul><li>The caller triggers an event, and any registered method handles it.</li><li><strong>Loosely coupled</strong> (Caller doesn’t know who will handle the event)</li></ul><h3>Example: Using Events (Loosely Coupled)</h3><pre>public class OrderProcessor<br>{<br>    public event EventHandler OrderProcessed; // Event declaration<br><br>    public void ProcessOrder()<br>    {<br>        Console.WriteLine(&quot;Processing order...&quot;);<br>        OrderProcessed?.Invoke(this, EventArgs.Empty); // Raising an event<br>    }<br>}<br><br>public class EmailService<br>{<br>    public void SendEmail(object sender, EventArgs e)<br>    {<br>        Console.WriteLine(&quot;Email sent: Order processed.&quot;);<br>    }<br>}<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        OrderProcessor orderProcessor = new OrderProcessor();<br>        EmailService emailService = new EmailService();<br><br>        // Subscribe to event (loosely coupled)<br>        orderProcessor.OrderProcessed += emailService.SendEmail;<br><br>        orderProcessor.ProcessOrder(); // Triggers event<br>    }<br>}</pre><p><em>Check out my </em><a href="https://www.linkedin.com/in/hamid-musayev"><em>LinkedIn</em></a><em> and </em><a href="https://github.com/HamidMusayev"><em>Github</em></a><em> if you are interested.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38bd204056d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate Limiting Algorithms and Custom Implementation in .NET Core Web API]]></title>
            <link>https://medium.com/@hamidmusayev/rate-limiting-algorithms-and-custom-implementation-in-net-core-web-api-5f243b2ab9f4?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f243b2ab9f4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 20:32:44 GMT</pubDate>
            <atom:updated>2025-04-09T10:39:33.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rate Limiting Algorithms and Custom Implementation in .NET Core Web API</h3><p>Rate limiting is a technique used to control the number of requests a client can make to a server within a specified timeframe. This mechanism prevents API abuse and protects the server from being overwhelmed. .NET Core provides built-in support for rate limiting, starting from .NET 7. In this article, we will explore different rate limiting algorithms and implement them in a .NET Core Web API. But before starting implementation let’s explore about rate limiting algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYSu2DOplCkeEenj.png" /></figure><h3>Common Rate Limiting Algorithms</h3><h4>1. Fixed Window Algorithm</h4><p>The fixed window algorithm enforces a limit on requests within predefined time intervals (e.g., 100 requests per minute). If the limit is exceeded within the window, additional requests are rejected until the next interval starts. This method is simple but can cause spikes at the start of each window.</p><h4>2. Sliding Window Algorithm</h4><p>Unlike the fixed window approach, the sliding window algorithm maintains a rolling count of requests over a defined time span. By tracking request timestamps, it ensures a smoother distribution of requests, reducing sudden traffic surges and making the system more resilient to bursts.</p><h4>3. Token Bucket Algorithm</h4><p>This model allows a steady flow of requests by refilling tokens at a fixed rate. Each request consumes a token, and if none are available, excess requests are either delayed or dropped. This method supports occasional traffic bursts while maintaining long-term request control, making it ideal for APIs with fluctuating demand.</p><h4>4. Concurrency Limiting</h4><p>Instead of controlling requests based on time, concurrency limiting restricts the number of simultaneous active requests. When the limit is reached, new requests must wait or be rejected. This is particularly useful for protecting backend resources, such as databases, from excessive load.</p><h3>Implementing Rate Limiting in .NET Core Web API</h3><h4>Setting Up the Project</h4><p>Create a new .NET Core Web API project targeting .NET 7 or later.</p><pre>var builder = WebApplication.CreateBuilder(args);</pre><pre>builder.Services.AddRateLimiter(options =&gt;<br>{<br>    // Rate limiter configurations<br>});<br>var app = builder.Build();<br>app.UseRateLimiter();<br>app.MapControllers();<br>app.Run();</pre><h4>Implementing Fixed Window Algorithm</h4><pre>builder.Services.AddRateLimiter(options =&gt;<br>{<br>    options.AddFixedWindowLimiter(&quot;Fixed&quot;, limiterOptions =&gt;<br>    {<br>        limiterOptions.PermitLimit = 100; // Maximum allowed requests per window<br>        limiterOptions.Window = TimeSpan.FromMinutes(1); // Time window duration<br>        limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; // Defines queue processing order<br>        limiterOptions.QueueLimit = 5; // Maximum queued requests before rejecting<br>    });<br>});</pre><h4>Implementing Sliding Window Algorithm</h4><pre>builder.Services.AddRateLimiter(options =&gt;<br>{<br>    options.AddSlidingWindowLimiter(&quot;Sliding&quot;, limiterOptions =&gt;<br>    {<br>        limiterOptions.PermitLimit = 100; // Maximum allowed requests per window<br>        limiterOptions.Window = TimeSpan.FromMinutes(1); // Time window duration<br>        limiterOptions.SegmentsPerWindow = 4; // Number of segments within the window<br>        limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; // Defines queue processing order<br>        limiterOptions.QueueLimit = 5; // Maximum queued requests before rejecting<br>    });<br>});</pre><h4>Implementing Token Bucket Algorithm</h4><pre>builder.Services.AddRateLimiter(options =&gt;<br>{<br>    options.AddTokenBucketLimiter(&quot;TokenBucket&quot;, limiterOptions =&gt;<br>    {<br>        limiterOptions.TokenLimit = 100; // Maximum tokens that can be stored in the bucket<br>        limiterOptions.TokensPerPeriod = 10; // Tokens added per replenishment period<br>        limiterOptions.ReplenishmentPeriod = TimeSpan.FromSeconds(10); // Time interval for token replenishment<br>        limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; // Defines queue processing order<br>        limiterOptions.QueueLimit = 5; // Maximum queued requests before rejecting<br>    });<br>});</pre><h4>Implementing Concurrency Limiting</h4><pre>builder.Services.AddRateLimiter(options =&gt;<br>{<br>    options.AddConcurrencyLimiter(&quot;Concurrency&quot;, limiterOptions =&gt;<br>    {<br>        limiterOptions.PermitLimit = 10; // Maximum concurrent requests allowed<br>        limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; // Defines queue processing order<br>        limiterOptions.QueueLimit = 5; // Maximum queued requests before rejecting<br>    });<br>});</pre><h3>Conclusion</h3><p>Rate limiting is essential for API security and performance. In this article, we explored different rate limiting algorithms and implemented them using .NET Core’s built-in middleware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f243b2ab9f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in .NET Core Web API: A Comprehensive Guide]]></title>
            <link>https://medium.com/@hamidmusayev/testing-in-net-core-web-api-a-comprehensive-guide-5f0e6f5a9dbc?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f0e6f5a9dbc</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 19:45:54 GMT</pubDate>
            <atom:updated>2025-03-17T19:45:54.331Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing in .NET Core Web API: A Comprehensive Guide</h3><p>In the world of modern software development, building robust and reliable APIs is crucial. However, even the most well-designed APIs can fail if they aren’t tested in depth. Testing ensures that your application behaves as expected, handles errors gracefully, and meets the requirements of your users. In this article, we’ll explore how to effectively test a .NET Core Web API, covering unit testing, integration testing, and best practices to ensure your API is production-ready.</p><h3>Types of Testing in .NET Core Web API</h3><p>There are several types of testing you can perform on a .NET Core Web API. The most common ones are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P13rc2P_VZei3Z2y.jpg" /></figure><ol><li><strong>Unit Testing</strong>: Testing individual components (e.g., controllers, services) in isolation.</li><li><strong>Integration Testing</strong>: Testing how multiple components work together.</li><li><strong>End-to-End (E2E) Testing</strong>: Testing the entire application from start to finish.</li></ol><h3>1. Unit Testing</h3><p>Unit testing focuses on testing individual components of your application in isolation. For example, you might test a controller action or a service method without making actual HTTP requests or hitting a database.</p><blockquote>Example: Testing a Controller</blockquote><p>Suppose you have a ProductsController that depends on an IProductService. Here’s how you can write unit tests for it using <strong>xUnit</strong> and <strong>Moq</strong>:</p><pre>public class ProductsController : ControllerBase<br>{<br>    private readonly IProductService _productService;<br><br>    public ProductsController(IProductService productService)<br>    {<br>        _productService = productService;<br>    }<br><br>    [HttpGet(&quot;{id}&quot;)]<br>    public async Task&lt;IActionResult&gt; GetProduct(int id)<br>    {<br>        var product = await _productService.GetProductByIdAsync(id);<br>        if (product == null)<br>        {<br>            return NotFound();<br>        }<br>        return Ok(product);<br>    }<br>}</pre><blockquote>Unit Test Code:</blockquote><pre>using Microsoft.AspNetCore.Mvc;<br>using Moq;<br>using Xunit;<br><br>public class ProductsControllerTests<br>{<br>    [Fact]<br>    public async Task GetProduct_ReturnsNotFound_WhenProductDoesNotExist()<br>    {<br>        // Arrange<br>        var mockService = new Mock&lt;IProductService&gt;();<br>        mockService.Setup(service =&gt; service.GetProductByIdAsync(It.IsAny&lt;int&gt;()))<br>                   .ReturnsAsync((Product)null);<br><br>        var controller = new ProductsController(mockService.Object);<br><br>        // Act<br>        var result = await controller.GetProduct(1);<br><br>        // Assert<br>        Assert.IsType&lt;NotFoundResult&gt;(result);<br>    }<br><br>    [Fact]<br>    public async Task GetProduct_ReturnsOk_WhenProductExists()<br>    {<br>        // Arrange<br>        var mockService = new Mock&lt;IProductService&gt;();<br>        var product = new Product { Id = 1, Name = &quot;Test Product&quot; };<br>        mockService.Setup(service =&gt; service.GetProductByIdAsync(1))<br>                   .ReturnsAsync(product);<br><br>        var controller = new ProductsController(mockService.Object);<br><br>        // Act<br>        var result = await controller.GetProduct(1);<br><br>        // Assert<br>        var okResult = Assert.IsType&lt;OkObjectResult&gt;(result);<br>        var returnedProduct = Assert.IsType&lt;Product&gt;(okResult.Value);<br>        Assert.Equal(product.Id, returnedProduct.Id);<br>    }<br>}</pre><h3>2. Integration Testing</h3><p>Integration testing ensures that multiple components of your application work together correctly. For example, you might test how your controller interacts with a real database or middleware.</p><blockquote>Example: Testing an API Endpoint</blockquote><p>To perform integration testing, you can use the Microsoft.AspNetCore.Mvc.Testing package to create an in-memory test server.</p><blockquote>Integration Test Code:</blockquote><pre>using System.Net.Http;<br>using System.Threading.Tasks;<br>using Microsoft.AspNetCore.Mvc.Testing;<br>using Xunit;<br><br>public class ProductsControllerIntegrationTests : IClassFixture&lt;WebApplicationFactory&lt;Startup&gt;&gt;<br>{<br>    private readonly HttpClient _client;<br><br>    public ProductsControllerIntegrationTests(WebApplicationFactory&lt;Startup&gt; factory)<br>    {<br>        _client = factory.CreateClient();<br>    }<br><br>    [Fact]<br>    public async Task GetProduct_ReturnsSuccessStatusCode()<br>    {<br>        // Act<br>        var response = await _client.GetAsync(&quot;/api/products/1&quot;);<br><br>        // Assert<br>        response.EnsureSuccessStatusCode();<br>    }<br><br>    [Fact]<br>    public async Task GetProduct_ReturnsNotFound_ForInvalidId()<br>    {<br>        // Act<br>        var response = await _client.GetAsync(&quot;/api/products/999&quot;);<br><br>        // Assert<br>        Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode);<br>    }<br>}</pre><h3>3. End-to-End (E2E) Testing</h3><p>E2E testing involves testing the entire application from start to finish, including the database, middleware, and external services. While integration tests focus on specific parts of the application, E2E tests simulate real user scenarios.</p><blockquote>Example: Testing a Complete Workflow</blockquote><p>You can use tools like <strong>Selenium</strong> or <strong>Playwright</strong> for browser-based E2E testing, or continue using WebApplicationFactory for API-level E2E tests.</p><h3>Best Practices for Testing in .NET Core</h3><ol><li><strong>Write Isolated Tests</strong>: Ensure tests don’t depend on each other.</li><li><strong>Use Mocks Wisely</strong>: Mock external dependencies like databases or third-party services.</li><li><strong>Test Edge Cases</strong>: Include tests for invalid inputs, exceptions, and boundary conditions.</li><li><strong>Automate Tests</strong>: Integrate tests into your CI/CD pipeline to catch issues early.</li><li><strong>Keep Tests Fast</strong>: Avoid slow tests by using in-memory databases or mocks.</li><li><strong>Follow the Arrange-Act-Assert Pattern</strong>: Clearly separate the setup, execution, and verification phases of your tests.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f0e6f5a9dbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception tracking with sentry in Flutter (global exception handling)]]></title>
            <link>https://medium.com/@hamidmusayev/this-article-has-given-practical-and-detailed-information-about-what-are-errors-in-flutter-2d0d0998d058?source=rss-4a305044804f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d0d0998d058</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Hamid Musayev]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 06:50:02 GMT</pubDate>
            <atom:updated>2025-03-17T19:47:51.616Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exception Tracking with Sentry in Flutter (Global Exception Handling)</h3><p>This article has given practical and detailed information about <strong>what are exceptions</strong> in Flutter framework and <strong>how we should handle them</strong> properly.<br>This will allow us to monitor the statistics and details of exceptions that users encounter in our application through various auxiliary tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*-8cJyJJb-Ej55jfv.png" /></figure><p>The article consists of the following parts:</p><ol><li>What is an exception and what are its types?</li><li>How to get all exceptions in Flutter?</li><li>Adding Sentry to a Flutter project</li><li>Exception tracking with Sentry</li></ol><h3>1. What is an exception and what are its types?</h3><blockquote>An exception — is an event that occurs during the execution of the program code and disrupts the normal course of the program execution.</blockquote><p>This means that exceptions occur during the run-time of the program. For example, we can check to retrieve any element from an empty list.</p><pre>void main() {<br>  List&lt;int&gt; list = []; // or List.empty();<br>  print(list[0]);<br>}</pre><p>As you can see, there are no syntax errors in this block of code. That’s why dart sdk won’t give us an error when we build and run our code.</p><p>But after running the program, during run-time, the following exception will be written in the console and the program execution will be completed.</p><pre>Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0</pre><blockquote>Flutter is built on the Dart language, and all exceptions in that language are subtypes of the Exception type. Dart gives us <strong>try, on, catch, finally</strong> keywords to handle errors.</blockquote><p>The usage of these keywords is as follows:</p><pre>void main() {<br>  try {<br>    double result = divide(10, 0);<br>    print(&#39;Nəticə: $result&#39;);<br>  } on IntegerDivisionByZeroException catch (e) {<br>    // It will only be executed if there is an error of this type<br>    print(&#39;IntegerDivisionByZeroException xətası: $e&#39;);<br>  } catch (e) {<br>    // It will be executed if there are other types of errors<br>    print(&#39;Xəta: $e&#39;);<br>  } finally {<br>    // It will be executed whether or not an error occurs<br>    print(&#39;Finally bloku icra olundu.&#39;);<br>  }<br>}</pre><pre>double divide(int a, int b) {<br>  if (b == 0) {<br>    throw IntegerDivisionByZeroException();<br>  }<br>  return a / b;<br>}</pre><p>Or we can create our own error type:</p><pre>class MyException implements Exception {<br>  String cause;<br>  CustomException(this.cause);<br>}</pre><pre>// usage<br>throw new MyException(&#39;This is exception message&#39;);</pre><h3>2. How to handle all exceptions in Flutter?</h3><p>In the first part, we talked about catching errors with try-catch. But is it always necessary? is it really correct that we write <strong>try-catch</strong> at the end of every operation?</p><p><strong>The answer is no</strong>, and doing so would result in us writing repetitive and sloppy code all the time. But what should we do to get all the errors that occurred within the application?</p><blockquote>Here the concept of<strong> Global exception handling</strong> comes to our aid.</blockquote><p>The following block of code written inside the main method is used to retrieve all exceptions that occur in the application.</p><pre>import &#39;dart:ui&#39;;</pre><pre>Future&lt;void&gt; main() async {<br>  await myErrorHandler.initialize();</pre><pre>  // Errors sent by Flutter<br>  FlutterError.onError = (details) {<br>    FlutterError.presentError(details);<br>    // here we can use the details object according to the logic we want<br>    ...<br>  };</pre><pre>  // Errors sent by the platform<br>  PlatformDispatcher.instance.onError = (error, stack) {<br>    // here we can use the error and stack object according to the logic we want<br>    ...<br>    return true;<br>  };</pre><pre>  runApp(MyApp());<br>}</pre><p>This method given to the builder argument of the MaterialApp widget allows us to get all the exceptions that occurred during Rendering.</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      builder: (context, widget) {</pre><pre>        Widget error = const Text(&#39;...rendering error...&#39;);<br>        if (widget is Scaffold || widget is Navigator) {<br>          error = Scaffold(body: Center(child: error));<br>        }</pre><pre>        ErrorWidget.builder = (errorDetails) =&gt; error;<br>        if (widget != null) return widget;<br>        throw (&#39;widget variable has no value (null)&#39;);<br>      },<br>    );<br>  }<br>}</pre><h3>3. Adding Sentry to a Flutter project</h3><p><strong>Sentry</strong> is an <strong>open source</strong> performance statistics and error management tool for applications written in various languages. It is also available as a <a href="https://develop.sentry.dev/self-hosted/">self-hosted</a> version for on-premises hosting.</p><p>To use sentry in a Flutter project, first add the <strong>sentry_flutter</strong> package to pubspec.yamlor run the flutter pub add sentry_flutter command.</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  sentry_flutter: ^7.9.0</pre><p>Then let’s configure the sentry with the SentryFlutter.init method inside the main method.</p><pre>import &#39;package:flutter/widgets.dart&#39;;<br>import &#39;package:sentry_flutter/sentry_flutter.dart&#39;;</pre><pre>Future&lt;void&gt; main() async {<br>  // Init sentry<br>  await Sentry.init((options) =&gt; <br>    options.dsn = &#39;https://example@sentry.io/my-dsn-from-sentry-site&#39;);<br>  <br>  // Init App<br>  runApp(MyApp()),<br>}</pre><p>Here we will need the value of options.dsn, i.e. the dsn address. To get this address, go to the <a href="https://sentry.io/signup/"><strong>sentry</strong></a> website and register.</p><p>After completing the registration <em>and passing the splash screen</em>, we are faced with this screen. Click the <strong>Create project</strong> button on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Q6tx7i569OoJPnUZ.png" /></figure><p>After selecting the platform Flutter and entering the project name, click the <strong>Create project</strong> button below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*3Fdr5b3Waca8brYj.png" /></figure><p>Here we copy the dsn address that was created for our project on the screen that opens and assign it to the options.dsn value that we wrote in the main method of our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*pBo5vVufv_syVUtl.png" /></figure><p>Then click on the <strong>Take me to Issues</strong> button below to go to the screen where the exceptions are listed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*_WUGj0EVzUJmqrZY.png" /></figure><p>Apparently the list here is empty since <strong>no exception has been sent from our application</strong> yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*kiF4YUszvFiXeI95.png" /></figure><h3>4. Exception tracking with Sentry</h3><p><strong>In the second part</strong>, we talked about getting all the exceptions that happened with the code block we wrote inside the main method.</p><p><strong>In the third part</strong>, we added sentry to our project.</p><p><strong>In the last section</strong>, let’s ensure that the received exceptions are sent to sentry. Let’s change our main method like this.</p><pre>import &#39;dart:ui&#39;;</pre><pre>import &#39;package:flutter/widgets.dart&#39;;<br>import &#39;package:sentry_flutter/sentry_flutter.dart&#39;;</pre><pre>Future&lt;void&gt; main() async {<br>  // Init sentry<br>  await Sentry.init((options) =&gt; options.dsn = &#39;https://example@sentry.io/my-dsn-from-sentry-site&#39;);<br>  <br>  // Flutter exception<br>  FlutterError.onError = (details) async {<br>    // Sending exception to sentry<br>    await Sentry.captureException(details.exception, stackTrace: details.stack);<br>    <br>    // Displaying the exception on the console<br>    FlutterError.presentError(details);<br>    <br>    // To close the application<br>    // exit(1);<br>  };</pre><pre>// Platform exception<br>  PlatformDispatcher.instance.onError = (error, stack) {<br>    // Sending exception to sentry<br>    Sentry.captureException(error, stackTrace: stack);<br>    <br>    // Displaying the exception on the console<br>    FlutterError.presentError(FlutterErrorDetails(exception: error, stack: stack));<br>    <br>    return false;<br>  };<br>  <br>  // Init App<br>  runApp(const MyApp());<br>}</pre><p>To test, let’s create a button inside MyApp and add an error to the onPressed argument.</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blueAccent),<br>        useMaterial3: true,<br>      ),<br>      home: Scaffold(<br>        body: Container(),<br>        floatingActionButton: FloatingActionButton(<br>          onPressed: () =&gt; throw Exception(&quot;This is an error message!&quot;),<br>          child: const Icon(Icons.error),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><blockquote><strong>Finally</strong>, let’s open the sentry screen. Here we can see the error we sent and its details.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*F_BXmXCjBajXD0Aw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*RkC0UfmQKS9v8h-w.png" /></figure><p><em>I hope the article was useful for you. Other sentry alternatives are: </em><a href="https://firebase.google.com/products/crashlytics">Firebase Crashlytics</a>, <a href="https://www.bugsnag.com/">Bugsnag</a>, <a href="https://instabug.com/">Instabug</a>, <a href="https://newrelic.com/">New Relic</a>, <a href="https://rollbar.com/">Rollbar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d0d0998d058" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>