<?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 Jonathan Antoine on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Antoine on Medium]]></description>
        <link>https://medium.com/@jonathanantoine?source=rss-f5f8d7ee25e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xEI8HYkbvcu08eIJ.</url>
            <title>Stories by Jonathan Antoine on Medium</title>
            <link>https://medium.com/@jonathanantoine?source=rss-f5f8d7ee25e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:18:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathanantoine/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[C# Async Void vs Task: Stop App Crashes]]></title>
            <link>https://jonathanantoine.medium.com/c-async-void-vs-task-stop-app-crashes-a8f726a1a5e6?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8f726a1a5e6</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 15:34:30 GMT</pubDate>
            <atom:updated>2025-12-03T15:34:30.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Task Exception Handling in .NET: Where one wrong keyword can turn your app into a ticking time bomb 💣</h3><p>When dealing with Tasks and exceptions in .NET, there is a lot of room to be lost in the guidelines. One wrong return type, and your application might vanish without a trace.</p><p>Let’s recap my knowledge in this post so we stop treating exception handling like Russian roulette.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*FNsNp3E8X-7lTB44.png" /></figure><h3>The Void of Despair (async void)</h3><p>When an exception is thrown in an async void method, the .NET runtime has a little panic attack. It doesn&#39;t know where to store the exception because there is no Task object associated with the call. The result? It crashes your process. Brutally.</p><pre>// Nowhere (void!) to store the exception<br>// ⚠️ This will crash your process if AnotherMethod fails<br>public async void VoidMethod()<br>{<br>    // exception is thrown here<br>    await AnotherMethod();<br>}</pre><p>Pro Tip: The only legitimate use case for async void is event handlers (like button clicks in UI apps). If you are writing a library or backend service, async void is like goto—technically legal, but your code reviewer will judge you.</p><h3>Safe Harbor (returning Task)</h3><p>If an exception is thrown in an async method returning Task, the runtime acts like a responsible adult. It captures the exception and stores it inside the returned Task object, marking it as Faulted.</p><p>A major benefit: your process does not crash immediately.</p><p>You can technically subscribe to TaskScheduler.UnobservedTaskException to catch these if they go unnoticed. However, be warned:</p><ol><li>This is not “live” — it only fires when the Garbage Collector finally collects the Task object.</li><li>Since .NET 4.5, unobserved exceptions <strong>don’t crash the process by default anymore</strong>, but ignoring them is still a bad habit.</li></ol><pre>// Global handler for unobserved task exceptions<br>TaskScheduler.UnobservedTaskException += (sender, e) =&gt;<br>{<br>    Console.WriteLine(&quot;[Unobserved] Exception caught: &quot; + e.Exception);<br>    <br>    // Mark as observed so the process is not terminated<br>    e.SetObserved();<br>};</pre><h3>Summary: The Life or Death Table</h3><p>For those who love synthetic views (like me), here is the breakdown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*DGWoFxL2cUUBVOF0sVycaQ.png" /></figure><h3>The “Fire and Forget” Pattern</h3><p>Sometimes, returning void is mandatory (e.g., you are implementing a specific delegate or event handler), but you want to sleep at night knowing your app won&#39;t crash.</p><p>You can apply the Fire and Forget pattern safely by wrapping your call. The goal is to ensure we never leave an exception unhandled in the void.</p><p>Here is a helper class that I use in my <a href="https://play.google.com/store/apps/details?id=com.jonathanantoine.TVST">apps</a> to keep things sane:</p><pre>namespace System.Threading.Tasks;<br><br>public static class TaskUtilities<br>{<br>#pragma warning disable RECS0165 // Asynchronous methods should return a Task instead of void<br>    public static async void FireAndForgetSafeAsync(this Task task, IErrorHandler handler = null)<br>#pragma warning restore RECS0165<br>    {<br>        try<br>        {<br>            // Always use ConfigureAwait(false) for library code to avoid deadlocks<br>            await task.ConfigureAwait(false);<br>        }<br>        catch (Exception ex)<br>        {<br>            handler?.HandleError(ex);<br>        }<br>    }<br>}<br><br>public interface IErrorHandler<br>{<br>    void HandleError(Exception ex);<br>}</pre><p>And here is how it can be used :</p><pre>// Now safe! The exception is caught and handled gracefully.<br>myAsyncMethod().FireAndForgetSafeAsync(myErrorHandler);</pre><p><em>Happy coding, and may your tasks always run to completion!</em> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8f726a1a5e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Mock SignalR (and WebSockets) in Cypress]]></title>
            <link>https://javascript.plainenglish.io/how-to-mock-signalr-and-websockets-in-cypress-da065611d25d?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/da065611d25d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 18:15:44 GMT</pubDate>
            <atom:updated>2025-10-14T09:10:01.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKq17ICcwqbBK4DgCNUtQQ.png" /><figcaption>AI generated</figcaption></figure><p>The Angular frontend I’m working on relies on <strong>SignalR</strong> to receive notifications from my API. Each time an item is updated, a message is pushed via SignalR, and the frontend refreshes the corresponding data.</p><h3>The Problem</h3><p>When writing Cypress tests, I stumbled upon a challenge: <strong>how can I simulate a SignalR message from the API to trigger a frontend reload?</strong></p><p>Several NPM packages claim to help with mocking SignalR or WebSocket servers but they all required modifying the application code to inject a “fake SignalR connection.” That’s a hard no for me: <strong>the app under test should never be polluted with test-only code.</strong></p><p>Moreover, since the Angular app is compiled and minified, swapping out the SignalR client implementation dynamically isn’t an option: the class and variable names are obfuscated.</p><h3>The Solution</h3><p>I came up with a lightweight approach that works surprisingly well:</p><ol><li>Start a <strong>fake WebSocket proxy server</strong> inside Cypress.</li><li>Let this proxy forward all initial traffic to the real SignalR server during the handshake phase.</li><li>Override the browser’s WebSocket implementation so all connections go through the proxy.</li><li>Once connected, <strong>send fake messages</strong> from Cypress to the frontend through the proxy.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kttYLgzexxsd88Z46cL0vA.png" /></figure><p>Let’s break this down.</p><blockquote><em>📌 </em>Disclaimer<em>: This article was written by a human and may contain inaccuracies, outdated assumptions, or biased interpretations. While care has been taken to ensure technical correctness, you should always verify with the official documentation and trusted sources before relying on any implementation details. 😉</em></blockquote><h3>1. Start a Fake WebSocket Server in Cypress</h3><p>Using the <a href="https://www.npmjs.com/package/ws">ws</a> package, you can easily spin up a local WebSocket server within Cypress:</p><pre>class WebSocketProxy {<br>  constructor() {<br>    this.server = null;<br>    this.connections = new Map();<br>    this.config = {<br>      localPort: 8090,<br>      targetUrl: &#39;ws://true-api&#39;,<br>      wsOptions: {<br>        handshakeTimeout: 10000,<br>        perMessageDeflate: false,<br>      }<br>    };<br>  }<br><br>  start() {<br>    console.log(&#39;Starting proxy on port &#39; + this.config.localPort);<br>    return new Promise((resolve, reject) =&gt; {<br>      this.server = new WebSocket.Server({ port: this.config.localPort });<br>      this.server.on(&#39;listening&#39;, resolve);<br>      this.server.on(&#39;error&#39;, reject);<br>      this.server.on(&#39;connection&#39;, <br>                    (soc, req) =&gt; this.handleClientConnection(soc, req));<br>    });<br>  }<br>}</pre><h3>2. Proxy All Calls to the Real SignalR Server Until Connected</h3><p>The core of the system lies in the handleClientConnection method. It forwards messages between the client and the real SignalR server, maintaining a mapping of connections and queueing messages until the handshake completes.</p><pre>handleClientConnection(clientSocket, request) {<br>  const connectionId = Date.now() + Math.random();<br><br>  // Extract query parameters from the client request<br>  const url = new URL(<br>          request.url,<br>          `ws://localhost:${this.config.localPort}`);<br><br>  // Extract WebSocket sub-protocols from Sec-WebSocket-Protocol header<br>  const clientProtocols <br>      = request.headers[&#39;sec-websocket-protocol&#39;];<br><br>  // Connect to the real SignalR server with query parameters<br>  const targetUrl = this.config.targetUrl + url.search;<br><br>  // Forward important headers from client to target<br>  const wsOptions = {<br>    ...this.config.wsOptions,<br>    headers: {<br>      &#39;Origin&#39;: request.headers.origin,<br>      &#39;User-Agent&#39;: request.headers[&#39;user-agent&#39;],<br>      // Forward WebSocket protocol header if present<br>      ...(clientProtocols <br>              &amp;&amp; { &#39;Sec-WebSocket-Protocol&#39;: clientProtocols })<br>    }<br>  };<br><br>  const targetSocket = new WebSocket(targetUrl, wsOptions);<br><br>  // Queue for messages received before target connection is open<br>  const messageQueue = [];<br><br>  this.connections.set(connectionId, {<br>    client: clientSocket,<br>    target: targetSocket,<br>    id: connectionId,<br>    messageQueue: messageQueue,<br>    handshakeComplete: false<br>  });<br><br>  // Forward messages from client to target server<br>  clientSocket.on(&#39;message&#39;, (data, isBinary) =&gt; {<br>    try {<br><br>      const message = data.toString();<br><br>      // Prepare message for target server<br>      const messageToSend = isBinary ? data : message;<br><br>      // Forward to target server (queue if not ready)<br>      if (targetSocket.readyState === WebSocket.OPEN) {<br>        targetSocket.send(messageToSend);<br>      } else if (targetSocket.readyState === WebSocket.CONNECTING) {<br>        messageQueue.push(messageToSend);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error forwarding client message:&#39;, error);<br>    }<br>  });<br><br>  // Forward messages from target server to client<br>  targetSocket.on(&#39;message&#39;, (data, isBinary) =&gt; {<br>    try {<br><br>      const message = data.toString();<br><br>      // Detect SignalR handshake completion (empty object response)<br>      const connection = this.connections.get(connectionId);<br><br>      // Forward to client - convert Buffer to string for text messages<br>      // only if not blocked <br>      if (clientSocket.readyState === WebSocket.OPEN <br>             &amp;&amp; !connection.handshakeComplete) {<br>        clientSocket.send(isBinary ? data : message);<br>      }<br><br>      if (connection &amp;&amp; (message === &#39;{}\x1e&#39; <br>                || message.trim() === &#39;{}\x1e&#39;)) {<br>        connection.handshakeComplete = true;<br>      }<br><br>    } catch (error) {<br>      console.error(&#39;Error forwarding server message:&#39;, error);<br>    }<br>  });<br><br>  // Handle target connection open<br>  targetSocket.on(&#39;open&#39;, () =&gt; {<br><br>    // Send any queued messages<br>    if (messageQueue.length &gt; 0) {<br>      messageQueue.forEach((data) =&gt; targetSocket.send(data));<br>      messageQueue.length = 0;<br>    }<br>  });<br><br>  // Handle errors<br>  clientSocket.on(&#39;error&#39;, (error) =&gt; {<br>    console.error(&#39;Client socket error:&#39;, error);<br>  });<br><br>  targetSocket.on(&#39;error&#39;, (error) =&gt; {<br>    console.error(&#39;Target socket error:&#39;, error);<br>    console.error(&#39;Target URL was:&#39;, targetUrl);<br><br>    // Close client connection if target fails<br>    if (clientSocket.readyState === WebSocket.OPEN) {<br>      clientSocket.close(1011, &#39;Target server connection failed&#39;);<br>    }<br>  });<br><br>  // Handle unexpected HTTP responses (non-101 status codes)<br>  targetSocket.on(&#39;unexpected-response&#39;, (request, response) =&gt; {<br>    console.error(&#39;❌ Unexpected response from target server:&#39;);<br>    console.error(&#39;Status:&#39;, response.statusCode, response.statusMessage);<br>    console.error(&#39;Headers:&#39;, JSON.stringify(response.headers, null, 2));<br><br>    let body = &#39;&#39;;<br>    response.on(&#39;data&#39;, (chunk) =&gt; body += chunk.toString());<br>    response.on(&#39;end&#39;, () =&gt; {<br>      console.error(&#39;Response body:&#39;, body);<br><br>      // Close client with appropriate error<br>      if (clientSocket.readyState === WebSocket.OPEN) {<br>        clientSocket.close(1002, `Server returned ${response.statusCode}`);<br>      }<br>    });<br>  });<br><br>  // Handle disconnections<br>  clientSocket.on(&#39;close&#39;, (code, reason) =&gt; {<br>    console.log(`Client disconnected - Code: ${code}, Reason: ${reason}`);<br>    if (targetSocket.readyState !== WebSocket.CLOSED &amp;&amp;<br>      targetSocket.readyState !== WebSocket.CLOSING) {<br>      targetSocket.close();<br>    }<br>    this.connections.delete(connectionId);<br>  });<br><br>  targetSocket.on(&#39;close&#39;, (code, reason) =&gt; {<br>    console.log(`Target server disconnected - Code: ${code}, ${reason}`);<br>    if (clientSocket.readyState !== WebSocket.CLOSED &amp;&amp;<br>      clientSocket.readyState !== WebSocket.CLOSING) {<br>      clientSocket.close(code, reason);<br>    }<br>    this.connections.delete(connectionId);<br>  });<br>}</pre><p>This setup ensures that before the real connection is established, any outgoing messages are queued and later sent once the connection opens.</p><h3>3. Redirect WebSocket Calls to the Proxy</h3><p>Now for the fun part: overriding the browser’s WebSocket constructor.</p><p>We can intercept the frontend’s main HTML request and inject a script that rewrites the window.WebSocket global, redirecting all connections to our proxy server:</p><pre>cy.intercept(&#39;GET&#39;, &#39;MY_FRONTEND_URL&#39;, (req) =&gt; {<br>  req.continue((res) =&gt; {<br>    const overrideScript = `<br>      &lt;script&gt;<br>        (function() {<br>          const OriginalWebSocket = window.WebSocket;<br>          window.WebSocket = function(url, protocols) {<br>            try {<br>              const newUrl = &#39;${proxyUrl}&#39; + new URL(url).search;<br>              url = newUrl;<br>            } catch (e) {<br>              console.error(&#39;[WebSocket Override] URL parsing error:&#39;, e);<br>              url = &#39;${proxyUrl}&#39;;<br>            }<br>            return new OriginalWebSocket(url, protocols);<br>          };<br><br>          Object.setPrototypeOf(window.WebSocket, OriginalWebSocket);<br>          window.WebSocket.prototype = OriginalWebSocket.prototype;<br>        })();<br>      &lt;/script&gt;<br>    `;<br><br>    res.body = res.body.replace(&#39;&lt;head&gt;&#39;, &#39;&lt;head&gt;&#39; + overrideScript);<br>  });<br>});</pre><h3>4. Sending Fake Messages from Cypress</h3><p>Once everything is connected, simulating a server push is trivial:</p><pre>const wsProxy = new WebSocketProxy();<br>wsProxy.sendToClients({ type: 1, target: &#39;MyMessage&#39; });</pre><p>The sendToClients method ensures messages are sent only to connected clients with a completed handshake:</p><pre>sendToClients(message) {<br>  const messageStr = typeof message === &#39;string&#39; <br>          ? message : JSON.stringify(message) + &#39;\x1e&#39;;<br>  this.connections.forEach((connection) =&gt; {<br>    if (connection.client.readyState === WebSocket.OPEN <br>                &amp;&amp; connection.handshakeComplete) {<br>      connection.client.send(messageStr);<br>    }<br>  });<br>}</pre><h3>Full Cypress Test Setup</h3><p>Here’s how your Cypress test suite could look:</p><pre>describe(&#39;My frontend tests&#39;, () =&gt; {<br><br>  before(() =&gt; {<br>    cy.injectWebSocketOverride(hubPath);<br>    cy.visit(&#39;MY FRONTEND URL&#39;);<br>    cy.wait(2000); // Wait for the handshake to complete<br>  });<br><br>  after(() =&gt; {<br>    cy.stopWebSocketProxy();<br>  });<br><br>  it(&#39;should handle SignalR messages gracefully&#39;, () =&gt; {<br>    triggerDevicesListReload();<br><br>    cy.sendWebSocketMessage({<br>      type: 1,<br>      target: &#39;MyMessage&#39;<br>    });<br><br>    // assertions...<br>  });<br>});</pre><h3>Closing Thoughts</h3><p>This approach allows you to <strong>fully test real-time behavior</strong> in your Angular app without modifying your production codebase. It leverages Cypress’s flexibility to control the browser environment and simulate WebSocket behavior — no mocking libraries, no application code changes.</p><ul><li>✅ Works with any WebSocket-based app (not just SignalR)</li><li>✅ Keeps test logic fully isolated</li><li>✅ Logs, monitors, and injects messages easily from Cypress</li></ul><p>As a future improvement, this setup could be extended to <strong>completely eliminate the dependency on the remote server</strong>, allowing all SignalR communications to be simulated locally. However, that will not be covered in this article.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da065611d25d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-mock-signalr-and-websockets-in-cypress-da065611d25d">How to Mock SignalR (and WebSockets) in Cypress</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Share Translations Between .NET Backend and TypeScript Frontend Using a .NET Source Generator]]></title>
            <link>https://jonathanantoine.medium.com/share-translations-between-net-backend-and-typescript-frontend-using-a-net-source-generator-0556ef4ddabb?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0556ef4ddabb</guid>
            <category><![CDATA[source-generator]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[asp-net-mvc]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 07:44:04 GMT</pubDate>
            <atom:updated>2025-07-03T07:44:04.669Z</atom:updated>
            <content:encoded><![CDATA[<h3>Share Translations Between .NET Backend and TypeScript Frontend Using a .NET Source Generator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2kkywn381idYa5I11FDWw.png" /></figure><p>In the past, we used .resx files in .NET for localization. These allowed developers to define translations in XML and automatically access them via generated C# classes. <a href="https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/localization?view=net-maui-9.0">This remains the recommended approach</a> in .NET for backend localization.</p><p>However, XML isn’t ideal for modern TypeScript frontends, and I wanted to recreate that smooth developer experience using JSON instead — ensuring type safety and avoiding duplication across backend and frontend.</p><p>To do that, I implemented a <strong>.NET Source Generator</strong> that parses translation JSON files and exposes them as strongly typed C# classes at compile time.</p><blockquote>📌 <em>Disclaimer</em>: This article was written by a human and may contain inaccuracies, outdated assumptions, or biased interpretations. While care has been taken to ensure technical correctness, you should always verify with the official documentation and trusted sources before relying on any implementation details. 😉</blockquote><h3>⚙️ What Is a .NET Source Generator?</h3><p>A Source Generator is a Roslyn-based feature introduced in .NET 5 that enables you to inspect user code during compilation and produce new source code dynamically. It runs as part of the compilation process, analyzing any file accessible via the Roslyn pipeline — like .json, .cs, or .xml files—and can generate additional C# source files as plain text.</p><p>This generated code is then seamlessly included in the final compilation output, just like handwritten code.</p><p>In many ways, source generators are a modern, safer, and more integrated replacement for T4 templates. Unlike T4, which generates files ahead of time and requires manual triggers, source generators hook directly into the compiler and offer build-time safety, better tooling support, and cleaner integration.</p><h3>🔧 Solution Structure</h3><p>The solution is made of 2 projects :</p><ul><li>The source generator ( a .net standard 2.0 library)</li><li>The consumer of the source generator (the project with the json translations files)</li></ul><h3>🧠 Source Generator Project</h3><p>A source code generator is a .net standard 2.0 Roslyn analyzer project that needs to be created with some specific MSBuild properties:</p><ul><li>IsRoslynComponent: Marks the project as a Roslyn analyzer component. This enables it to plug into the compilation pipeline and generate code dynamically.</li><li>IncludeBuildOutput: Set to false to avoid including the compiled DLL of the generator project into the output of the consumer project, since only its analysis behavior is needed.</li><li>EnforceExtendedAnalyzerRules: Activates additional analyzer rules to help the project conform to Microsoft’s best practices for analyzer development.</li></ul><p>As seen below, specific nuget packages needs to be referenced too :</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br><br> &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;netstandard2.0&lt;/TargetFramework&gt;<br>    &lt;EnforceExtendedAnalyzerRules&gt;true&lt;/EnforceExtendedAnalyzerRules&gt;<br>    &lt;IsRoslynComponent&gt;true&lt;/IsRoslynComponent&gt;<br>    &lt;IncludeBuildOutput&gt;false&lt;/IncludeBuildOutput&gt;<br>    &lt;LangVersion&gt;latest&lt;/LangVersion&gt;<br> &lt;/PropertyGroup&gt;<br><br> &lt;ItemGroup&gt;<br> &lt;!--<br>      Using Version=&quot;*&quot; will always fetch the latest stable version of the package.<br>    --&gt;<br>   &lt;PackageReference Include=&quot;System.Text.Json&quot; Version=&quot;*&quot;/&gt;<br>   &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.CSharp&quot; Version=&quot;4.14.0&quot; /&gt;<br>   &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.Analyzers&quot; Version=&quot;*&quot;&gt;<br>    &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br> &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><h3>🛠️ Source Generator Code</h3><p>The generator must implement IIncrementalGenerator and be annotated with [Generator]:</p><pre>[Generator]<br>public class TranslationsGenerator : IIncrementalGenerator<br>{<br>  public void Initialize(IncrementalGeneratorInitializationContext context)<br>  {<br>  }<br>}</pre><p>The Initialize method let you use the provided context to find out the information that you need, apply your own logic and informs that you will generate a source file RegisterSourceOutput method. In the following example I will target all the json files in a translations folder :</p><pre>public void Initialize(IncrementalGeneratorInitializationContext context)<br>{<br>  var translationFiles = context.AdditionalTextsProvider<br>    .Where(at =&gt;<br>          at.Path.EndsWith(&quot;.json&quot;)<br>          &amp;&amp; at.Path.IndexOf(&quot;translations&quot;, <br>                   StringComparison.InvariantCultureIgnoreCase) &gt;= 0))<br>    .Collect();<br><br>  var source = context.CompilationProvider.Combine(translationFiles);<br><br>  context.RegisterSourceOutput(source, ExecuteForAllLanguages);<br>}</pre><p>The ExecuteForAllLanguagesmethod will then parse the Json file and generate the code to expose one property by key using a StringBuilder to finally add the source text as a source file using the AddSource method :</p><pre>private void ExecuteForAllLanguages(<br>  SourceProductionContext context,<br>  (Compilation Left, ImmutableArray&lt;AdditionalText&gt; Right) valueTuple)<br>{<br>  var translationFiles = valueTuple.Right;<br>  if (translationFiles.IsDefaultOrEmpty)<br>  {<br>    return;<br>  }<br>  foreach (var translationFile in translationFiles)<br>  {<br>    var fullText = translationFile.GetText()?.ToString();<br>    if (string.IsNullOrEmpty(fullText))<br>    {<br>      continue;<br>    }<br>    var jsonDocument = JsonDocument.Parse(fullText!);<br>    var properties = ExtractProperties(jsonDocument.RootElement);<br>    var fileName = Path.GetFileNameWithoutExtension(translationFile.Path);<br>    var stringBuilder = new StringBuilder();<br>    stringBuilder.AppendLine(&quot;// &lt;auto-generated /&gt;&quot;);<br>    stringBuilder.AppendLine(&quot;using System;&quot;);<br>    stringBuilder.AppendLine(&quot;&quot;);<br>    stringBuilder.AppendLine($&quot;namespace MyNamespace&quot;);<br>    stringBuilder.AppendLine(&quot;{&quot;);<br>    stringBuilder.AppendLine(&quot;    public partial class MyTranslations&quot;);<br>    stringBuilder.AppendLine(&quot;    {&quot;);<br>    foreach (var key in properties.OrderBy(k =&gt; k.Key))<br>    {<br>      var sanitizedKey = SanitizePropertyName(key.Key);<br>      stringBuilder.AppendLine($&quot;        /// &lt;summary&gt;&quot;);<br>      stringBuilder.AppendLine($&quot;        /// Translation key: {key}&quot;);<br>      stringBuilder.AppendLine($&quot;        /// &lt;/summary&gt;&quot;);<br>      stringBuilder.AppendLine($&quot;        public string {sanitizedKey} =&gt; \&quot;{key.Value}\&quot;;&quot;);<br>      stringBuilder.AppendLine();<br>    }<br>    stringBuilder.AppendLine(&quot;    }&quot;);<br>    stringBuilder.AppendLine(&quot;}&quot;);<br>    context.AddSource(<br>      $&quot;Translations.{fileName}.g.cs&quot;, <br>      SourceText.From(stringBuilder.ToString(),<br>                      Encoding.UTF8));<br>  }<br>}<br><br>private Dictionary&lt;string, string&gt; ExtractProperties(JsonElement rootElement)<br>{<br>    var properties = new Dictionary&lt;string, string&gt;();<br><br>    if (rootElement.ValueKind != JsonValueKind.Object)<br>    {<br>        return properties;<br>    }<br><br>    foreach (JsonProperty jsonProperty in rootElement.EnumerateObject())<br>    {<br>        if (jsonProperty.Value.ValueKind == JsonValueKind.String)<br>        {<br>            properties[jsonProperty.Name] <br>                   = jsonProperty.Value.GetString() ?? string.Empty;<br>        }<br>    }<br><br>    return properties;<br>}</pre><h3>🧪 Applies the source generator in the consumer</h3><p>Now that the generator is working, we will need to update the consumer to tell it to reference project. Please notice the 2 specific and uncommon attribute that needs to be set :</p><pre>&lt;ItemGroup&gt;<br>  &lt;ProjectReference Include=&quot;..\SourceGenerators\SourceGenerator.csproj&quot; <br>                  ReferenceOutputAssembly=&quot;false&quot;<br>                  OutputItemType=&quot;Analyzer&quot;/&gt;<br>&lt;/ItemGroup&gt;</pre><p>We also need to specify where we want the generated files to be outputted by adding these properties :</p><pre>&lt;PropertyGroup&gt;<br>  &lt;EmitCompilerGeneratedFiles&gt;true&lt;/EmitCompilerGeneratedFiles&gt;<br>  &lt;CompilerGeneratedFilesOutputPath&gt;.\GeneratedFiles&lt;/CompilerGeneratedFilesOutputPath&gt;<br>&lt;/PropertyGroup&gt;</pre><p>And the final piece, often forgotten, is to include the json files in the compilation pipeline otherwise your source generator won’t even see it :</p><pre>&lt;ItemGroup&gt;<br>    &lt;AdditionalFiles Include=&quot;Translations\*.json&quot;/&gt;<br>&lt;/ItemGroup&gt;</pre><h3>✅ The result</h3><p>When you add a JSON file under the Translations/ folder, the generator creates a .g.cs file that exposes your translation keys:</p><pre>// &lt;auto-generated /&gt;<br>using System;<br><br>namespace MyNamespace<br>{<br>  public partial class MyTranslations<br>  {<br>    /// &lt;summary&gt;<br>    /// Translation key: [Error_MissingRequiredId, Paramètre obligatoire manquant: id]<br>    /// &lt;/summary&gt;<br>    public string Error_MissingRequiredId =&gt; &quot;Paramètre obligatoire manquant: id&quot;;<br>    <br>    /// &lt;summary&gt;<br>    /// Translation key: [Error_MissingRequiredName, Paramètre obligatoire manquant: name]<br>    /// &lt;/summary&gt;<br>    public string Error_MissingRequiredName =&gt; &quot;Paramètre obligatoire manquant: name&quot;;<br> }<br>}</pre><p>This approach ensures:</p><ul><li>✅ A single source of truth for translations</li><li>✅ Type safety with compile-time validation</li><li>✅ Strong separation of concerns</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0556ef4ddabb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging a Node.js CLI Command in VSCode]]></title>
            <link>https://javascript.plainenglish.io/debugging-a-node-js-cli-command-in-vscode-fb599c38fd66?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb599c38fd66</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[windsurf]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 14:41:58 GMT</pubDate>
            <atom:updated>2025-10-14T09:10:49.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Debugging a Node.js CLI Command in VSCode" src="https://cdn-images-1.medium.com/max/1024/0*O2fSz_4OWCjAuU6D" /></figure><p>There’s an <a href="https://code.visualstudio.com/docs/nodejs/nodejs-debugging">excellent tutorial</a> on debugging Node.js applications in the official documentation of Visual Studio Code ( PS : it also applies to Windsurf !) . Recently, I followed the recommended steps, and although my breakpoints were correctly hit, something unexpected happened at the end of the execution: nothing.</p><p>No logs. No exceptions. Just… silence.</p><p>After some digging, I discovered the fix: a one-liner in your launch.json file. Simply add this line:</p><pre>&quot;console&quot;: &quot;integratedTerminal&quot;,</pre><p>This instructs VSCode to run your program in the integrated terminal rather than the default debug console. With this setting, all outputs (logs, exceptions, prompts) behave as expected.</p><p>Here’s a screenshot to guide you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*q45DXSH4drTWjMAuxTHZsQ.png" /></figure><p>Tada! Your CLI tool now behaves properly under the debugger after you press F5.</p><p>Happy debugging!</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb599c38fd66" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/debugging-a-node-js-cli-command-in-vscode-fb599c38fd66">Debugging a Node.js CLI Command in VSCode</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET MAUI / Xamarin on Android: Cast Audio Files with MediaRouteButton for Real!]]></title>
            <link>https://jonathanantoine.medium.com/net-maui-xamarin-on-android-cast-audio-files-with-mediaroutebutton-for-real-3e90036225c2?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e90036225c2</guid>
            <category><![CDATA[net-maui]]></category>
            <category><![CDATA[xamarin]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[chromecast]]></category>
            <category><![CDATA[podcast]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Sun, 11 May 2025 16:14:12 GMT</pubDate>
            <atom:updated>2025-05-11T18:17:52.563Z</atom:updated>
            <content:encoded><![CDATA[<p>I love listening to podcasts on my Google Home and Nest speakers using my <a href="https://play.google.com/store/apps/details?id=com.jonathanantoine.Podcasts">Podcast Player app</a> — an app I originally built for my wife (how far can we go for love? 😄). It started as a Xamarin.Forms project and was recently migrated to .NET MAUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dm20EtDFx0n-HL3Fwb9Vqw.png" /></figure><p>Casting audio to Chromecast-enabled devices is, in theory, quite straightforward and well-documented in the <a href="https://developers.google.com/cast/docs/android_sender/integrate">official Cast documentation</a>. You set up a CastContext, manage the CastSession, and finally include a <a href="https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton">MediaRouteButton</a> in your UI, initialized with CastButtonFactory after verifying that Google Play Services are available:</p><pre>var button = new MediaRouteButton(Context);<br>if (ConnectionResult.Success ==<br>    GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(Context))<br>{<br>    CastButtonFactory.SetUpMediaRouteButton(Context, button);<br>}</pre><h3>Embedding MediaRouteButton in .NET MAUI / Xamarin</h3><p>To use this button in a .NET MAUI (or Xamarin) app, you need to implement a <a href="https://learn.microsoft.com/en-us/dotnet/maui/user-interface/handlers/?view=net-maui-9.0">custom handler</a> that maps your cross-platform control to Android’s native MediaRouteButton. Here&#39;s a basic handler setup:</p><pre>public class CastButtonDroidHandler <br>: ViewHandler&lt;CastButton, MediaRouteButton&gt;<br>{<br>    public CastButtonDroidHandler() : base(ViewMapper)<br>    {<br>    }<br>    protected override MediaRouteButton CreatePlatformView()<br>    {   <br>        var context = Platform.CurrentActivity;         <br>        var mediaRoutButton = new MediaRouteButton(context);<br>        if (ConnectionResult.Success <br>               == GoogleApiAvailability.Instance<br>                   .IsGooglePlayServicesAvailable(context))<br>        {<br>          CastButtonFactory.SetUpMediaRouteButton(context, mediaRoutButton);<br>        }<br><br>        return mediaRoutButton;<br>    }<br>}</pre><h3>The MediaRouteButton Worked… Until It Didn’t</h3><p>After migrating to .NET MAUI, users began reporting that the cast button stopped responding:</p><blockquote><em>“I can click on it, but nothing happens!”</em></blockquote><p>Strangely, I couldn’t reproduce the issue — until I force-closed the app using the Android task manager. On relaunch, the cast button broke.</p><p>What was happening? The app wasn’t <em>fully</em> killed — background audio kept it alive. When I relaunched it, Android created a new Activity, but .NET MAUI reused the previous handler and context. That context was now stale and no longer pointed to the current Activity, which broke the MediaRouteButton. 😵‍💫</p><h3>The Fix: Recreate the Button with a Fresh Context</h3><p>To solve this, I forced the control to be recreated with the correct context. I did this by subscribing to the Window.Destroying event and resetting the handler. It’s a bit hacky, but it works:</p><h4>Step 1 — Subscribe to the window’s destroying event:</h4><pre>Application.Current!.Windows[0].Destroying += (s, e) =&gt;<br>{<br>    _castButton.Handler?.DisconnectHandler();<br>    _recreateCastButton = true;<br>};</pre><h4>Step 2 — Recreate the cast button:</h4><pre>private void RecreateCastButton()<br>{<br>    if (_recreateCastButton &amp;&amp; _castButton.Parent is ContentView parent)<br>    {<br>        _recreateCastButton = false;<br>        parent.Content = null;<br>        parent.Content = _castButton = new CastButton();<br>    }<br>}</pre><h3>Conclusion</h3><p>Integrating Chromecast support in a .NET MAUI or Xamarin app is surprisingly simple — until it isn’t. If your MediaRouteButton mysteriously stops working after relaunching the app, it&#39;s likely due to a stale Android Activity context. Recreating the button when the app’s window is destroyed ensures it’s always bound to the correct activity. It’s a bit of a workaround, but it gets the job done—and your users can keep casting without issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypvrDfSiNbug7XOlmvILCA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e90036225c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maui / Xamarin : different Android’s manifest based on build configuration]]></title>
            <link>https://medium.com/c-sharp-programming/maui-xamarin-different-androids-manifest-based-on-build-configuration-125314778067?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/125314778067</guid>
            <category><![CDATA[xamarin]]></category>
            <category><![CDATA[maui]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 08:14:58 GMT</pubDate>
            <atom:updated>2025-04-25T08:19:19.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>Maui / Xamarin: Different Android Manifest Based on Build Configuration</h3><figure><img alt="Maui / Xamarin: Different Android Manifest Based on Build Configuration" src="https://cdn-images-1.medium.com/max/1024/1*Nb1dyzjU4rKdKkFrTO6GgA.png" /></figure><p>When building Android applications, I always test new builds on my development phone. It’s a good practice to ensure there are no environment-specific issues, performance remains solid, and the UI behaves well on real hardware. Of course, I also run Firebase UI automated tests to validate compatibility across various screen sizes and Android versions.</p><h3>The Problem</h3><p>Only one version of an application with a given package ID can exist on a single device. As a result, my debug version would always uninstall the production version. This made switching between builds frustrating, especially when accounts and configurations had to be reset each time.</p><h3>The Solution</h3><p>To solve this, I maintain two separate Android manifest files:</p><ul><li>One for <strong>production</strong></li><li>One for <strong>development</strong>, with a different package ID</li></ul><p>Then, I configured my .csproj to include the appropriate manifest depending on the active build configuration:</p><pre>&lt;PropertyGroup&gt;<br> &lt;AndroidManifest <br>    Condition=&quot; &#39;$(Configuration)|$(Platform)&#39; == &#39;Debug|AnyCPU&#39; &quot;&gt;<br>       Properties\AndroidManifest.debug.xml<br> &lt;/AndroidManifest&gt;<br> &lt;AndroidManifest <br>    Condition=&quot; &#39;$(Configuration)|$(Platform)&#39; != &#39;Debug|AnyCPU&#39; &quot;&gt;<br>          Properties\AndroidManifest.xml<br> &lt;/AndroidManifest&gt;<br><br>&lt;None<br>    Condition=&quot; &#39;$(Configuration)|$(Platform)&#39; != &#39;Debug|AnyCPU&#39; &quot;&gt;<br>       Properties\AndroidManifest.debug.xml<br> &lt;/None&gt;<br> &lt;None<br>    Condition=&quot; &#39;$(Configuration)|$(Platform)&#39; == &#39;Debug|AnyCPU&#39; &quot;&gt;<br>          Properties\AndroidManifest.xml<br> &lt;/None&gt;<br>&lt;/PropertyGroup&gt;</pre><h3>Additional Code Adjustments</h3><p>Some components, like my custom ContentProvider used for local notification images or configuration backups, also needed distinct authority strings based on the build. This was handled using preprocessor directives:</p><pre>[ContentProvider([AUTHORITY])]<br>public class FileContentProvider : FileProvider<br>{<br> public const string AUTHORITY = &quot;com.jonathanantoine.databasebackup&quot;<br> #if DEBUG<br>    + &quot;2&quot;<br> #endif<br>  ;<br>}</pre><h3>Final Thoughts</h3><p>This setup saves time and frustration when switching between debug and production builds. It ensures both can coexist on the same device and keeps my workflow smooth.</p><p>Do you use a similar approach or another technique to solve this?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=125314778067" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/maui-xamarin-different-androids-manifest-based-on-build-configuration-125314778067">Maui / Xamarin : different Android’s manifest based on build configuration</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add a Local NuGet (.nupkg) to Your .NET Project]]></title>
            <link>https://jonathanantoine.medium.com/how-to-add-a-local-nuget-nupkg-to-your-net-project-0254d222e2a6?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0254d222e2a6</guid>
            <category><![CDATA[nuget-package]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[nuget]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 07:57:43 GMT</pubDate>
            <atom:updated>2025-04-16T07:13:24.561Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Add a Local NuGet (.nupkg) to Your .NET Project</h3><figure><img alt="How to Add a Local NuGet (.nupkg) to Your .NET Project" src="https://cdn-images-1.medium.com/max/1024/0*6SxVYsHUmu_QX-RL" /><figcaption>How to Add a Local NuGet (.nupkg) to Your .NET Project</figcaption></figure><p>Did you know that you can use a local folder — either inside or outside your repository — as a NuGet source?</p><p>A NuGet package is a convenient way to bundle .NET libraries. It handles dependency management, selects the correct DLL for your target platform, and wraps everything into a single distributable file. Sometimes, you might want to use a package locally without publishing it to a NuGet server, for personal or practical reasons.</p><h3>Using a Local Folder as a NuGet Source</h3><p>You can add a local NuGet source by creating a NuGet.config file at the root of your repository with the following content:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;configuration&gt;<br>    &lt;packageSources&gt;<br>        &lt;add key=&quot;MyLocalPackages&quot; value=&quot;.\my-packages&quot; /&gt;<br>    &lt;/packageSources&gt;<br>&lt;/configuration&gt;</pre><p>Make sure your .nupkg file is placed in the my-packages folder. Then, in your .csproj file, you can add a reference to your local package just like any other package reference:</p><pre>&lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;Your.Package.Id&quot; Version=&quot;1.0.0&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><h3>Updating a package</h3><p>When you update the .nupkg file in your local folder, NuGet might not detect the change due to caching. To ensure your updated package is picked up, you&#39;ll need to clear the NuGet cache.</p><p>Use the following command to list the locations of all local NuGet caches:</p><pre>dotnet nuget locals all --list</pre><p>Then delete the folder that corresponds to your package’s ID from the cache directory.</p><h3>Does it work on Azure Dev Ops ?</h3><p>Yes, it should work by default, as long as you explicitly use your custom nuget.config file in your pipeline. Here&#39;s an example using the DotNetCoreCLI@2 task:</p><pre>- task: DotNetCoreCLI@2<br>  displayName: &#39;Restore nugets&#39;<br>  inputs:<br>    command: &#39;restore&#39;<br>    projects: &#39;$(projectName)/*.csproj&#39;<br>    feedsToUse: &#39;config&#39;<br>    nugetConfigPath: &#39;nuget.config&#39;</pre><h4>✅ Workaround</h4><p>To handle this, you can create a second nuget.config file (with a different name), where the package source uses a relative path from the <em>working directory used by Azure DevOps</em>, not your repo root. While not perfect, this workaround is reliable.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;configuration&gt;<br>  &lt;packageSources&gt;       <br>   &lt;!-- On Azure dev ops the nuget command is done on a separate folder --&gt;<br>   &lt;add key=&quot;MyAzureDevOpsSharedSource&quot; value=&quot;..\s\my-nugets&quot; /&gt;<br>  &lt;/packageSources&gt;<br>&lt;/configuration&gt;<br></pre><p>You can then reference this custom file in your pipeline instead of the nuget.config file used localy.</p><h3>Final tip</h3><p>You can also edit your global or user-level NuGet.config to apply the local source across multiple projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0254d222e2a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to disable HTTP 2 for my Kestrel Asp.Net Core project ?]]></title>
            <link>https://jonathanantoine.medium.com/how-to-disable-http-2-for-my-kestrel-asp-net-core-project-3f43cf5d1135?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f43cf5d1135</guid>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[kestrel]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 11:01:06 GMT</pubDate>
            <atom:updated>2024-11-12T11:01:06.411Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to disable HTTP 2 for my Kestrel Asp.Net Core project ?</h3><p>Several options are available when needing to disable HTTP2 on aWindows Machine. Disabling HTTP/2 can be a quick fix when troubleshooting compatibility or performance issues.</p><h3>Machine wide using a registry key</h3><p>The most common solution found online is to disable HTTP/2 system-wide by modifying the Windows registry:</p><ol><li>Navigate to this folder : HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters</li><li>Create DWORD (32 bits) EnableHttp2Tls and EnableHttp2Cleartext with 0 as value.</li><li>call iis reset</li></ol><p>This will work fine but it’s applied to your whole server which is undesired.</p><h3>Only your Asp.Net Core Kestrel API</h3><p>Kestrel is the default web server in ASP.NET projects, automatically selected when you use the WebHost.CreateDefaultBuilder&lt;Startup&gt;() method included in the default template of any new ASP.NET project.</p><p>However, you can take control of Kestrel’s configuration by explicitly calling the UseKestrel extension method. This allows you to specify the protocols to be used.</p><p>You can configure Kestrel on a per-endpoint basis or apply a default configuration for all endpoints. The snippet below demonstrates how to enable only HTTP/1.1 as the default protocol for all endpoints:</p><pre>WebHost.CreateDefaultBuilder&lt;Startup&gt;(args)<br> .UseKestrel(<br>   kestrelOptions =&gt; kestrelOptions<br>    .ConfigureEndpointDefaults(<br>     endpointDefaults =&gt; endpointDefaults.Protocols = HttpProtocols.Http1));<br></pre><h3>Bonus : how to check which HTTP protocol I use ?</h3><p>The easiest way is to open the Developer Tools in Edge / Firefox / Chrome and navigate to your website. In the <strong>Network</strong> panel, right-click on any column header and add the <strong>Protocol</strong> column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNaA1HRd5v3ucoKq4xY2ew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f43cf5d1135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting an Angular application inside a Docker container with nginx]]></title>
            <link>https://jonathanantoine.medium.com/hosting-an-angular-application-inside-a-docker-container-with-nginx-b10f3f0a4c26?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b10f3f0a4c26</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 18:16:53 GMT</pubDate>
            <atom:updated>2024-11-06T09:14:33.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*XaEq3YRIP-R7NSRByJFsBw.png" /></figure><p><a href="https://medium.com/@jonathanantoine/configure-nginx-as-a-reverse-proxy-to-another-container-in-a-docker-compose-network-9c8f0c2865cd">In a previous post, we explored how to configure NGINX as a reverse proxy</a> to deploy our Angular application alongside its API on an Azure Web App. Today, we’ll dive into creating a Docker container for our Angular app!</p><h3>What is an Angular application in production ?</h3><p>An Angular application is a Single Page Application (SPA), essentially consisting of a single HTML file that references JavaScript and CSS stylesheets — that’s it!</p><p><strong>Angular doesn’t include a built-in HTTP server</strong>, so you’ll need to set one up to serve your application. Although this post won’t cover those details, several options are available, including NGINX, Azure Web Apps, IIS, GitHub Pages, and more.</p><h3>Do not use ng serve</h3><p>Of course having to set up an http server while working on an app can be fastidious so the Angular team provide you one for development purpose : the <a href="https://angular.dev/cli/serve">ng serve command</a>.</p><p>This command is wonderful as by default it even provides you live reload : each change you make on your code is immediately reflected in your app without even having to press the F5 button.</p><pre>ng serve</pre><p>The only drawback is that … <strong>ng serve </strong><a href="https://github.com/angular/angular-cli/issues/5274"><strong>is not meant for production</strong></a>. This also applies to docker image : don’t create docker image using ng serve as it’s not its purpose. This could be useful to move your development environment to docker images and remove the need to have the tools on your own computer but don’t use it for production !</p><blockquote>Don’t use ng serve in production.</blockquote><p>In the following example we will create a full production optimized angular application and host it in a docker image behind an nginx server.</p><h3>Creating the Angular App</h3><p>For the sake of our example, let’s start by creating an empty angular app to play with. The simplest way is to install the angular CLI and ask it to create the app for you :</p><pre>npm install -g @angular/cli<br>ng new angular-app --style scss --ssr false</pre><p>This will create an empty application named “angular-app” without Server Side Rendering (SSR) and using scss for style sheets format. Required npm packages will also be installed.</p><p>Creating the production version can then be asked to the Angular CLI using this command :</p><pre>ng build --configuration=production</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*BU9HpuXjz1EDNO6SDtuZsQ.png" /></figure><h3>Creating a basic docker image</h3><p>Now that we have the recipe, lets create a docker image using it.</p><p>We will optimize the final image size by using <a href="https://docs.docker.com/get-started/docker-concepts/building-images/multi-stage-builds/">a multi-stages build</a> : one stage will rely on the stable nodejs official image (node:lts-slim) to generate the Angular final bundle and one stage will rely on the official nginx image (nginx:stable) to serve the Angular app files. Create a Dockerfile (no extension) and paste this content :</p><pre>FROM node:lts-slim as build<br>WORKDIR /src<br>RUN npm install -g @angular/cli<br>COPY . ./<br>RUN npm ci<br>RUN ng build --configuration=production<br><br>FROM nginx:stable AS final<br>EXPOSE 80<br>COPY --from=build src/dist/angular-app/browser  /usr/share/nginx/html</pre><p>Notice that we’re using npm ci to install packages exclusively from the package-lock.json file. This ensures that no unintended package updates occur during the production image build, providing consistent and reliable dependencies.</p><h3>Optimize the docker image build process</h3><p>This will work fine but the build time can be optimized.</p><p>The COPY command transfers everything from the source directory into the build image. Because of Docker&#39;s <a href="https://docs.docker.com/get-started/docker-concepts/building-images/understanding-image-layers/">layered architecture</a>, any changes in this directory will trigger the COPY step and all subsequent steps to re-run—significantly impacting build time, especially with commands like npm ci. To optimize, the first step is to copy only the package*.json files initially and run npm install. With this approach, npm install will only re-run if there&#39;s a change in the package*.json files, reducing unnecessary rebuilds.</p><pre>FROM node:lts-slim AS build<br>WORKDIR /src<br>RUN npm install -g @angular/cli<br><br>COPY package*.json ./<br>RUN npm ci<br><br>COPY . ./<br>RUN ng build --configuration=production<br><br>FROM nginx:stable AS final<br>EXPOSE 80<br>COPY --from=build src/dist/angular-app/browser  /usr/share/nginx/html</pre><p>Many files in the source directory aren’t needed when building the production version. Examples include IDE configuration files, Angular cache files, and the node_modules directory. To exclude these unnecessary files, let&#39;s create a .dockerignore file alongside our Dockerfile with the following content:</p><pre>**/.dockerignore<br>**/.env<br>**/.git<br>**/.gitignore<br>**/.project<br>**/.settings<br>**/.toolstarget<br>**/.vs<br>**/.vscode<br>**/.idea<br>**/*.*proj.user<br>**/*.dbmdl<br>**/*.jfm<br>**/azds.yaml<br>**/bin<br>**/charts<br>**/docker-compose*<br>**/Dockerfile*<br>**/node_modules<br>**/npm-debug.log<br>**/obj<br>**/secrets.dev.yaml<br>**/values.dev.yaml<br>LICENSE<br>README.md<br>**/.angular</pre><h3>Build the docker image</h3><p>To build the image, simply execute the docker build — t my-angular-app-image.command to get a result similar to this one :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6364g-FsH_nzlsRYiEcYA.png" /></figure><p>Your docker image is now ready and tagged (named) “my-angular-app-image“ for further usage.</p><h3>Create and run a container with this image</h3><p>The final step to create a container from thetagged image. We will name it “container” and bind the port 80 of the container (the one exposed by nginx) to the port 4200 of the host (our computer) :</p><pre>docker run  -p 4200:80 --name container -d my-angular-app-image</pre><p>And that’s all, the angular app can be reached by navigating to <a href="http://localhost:4200/">http://localhost:4200</a> in your browser.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b10f3f0a4c26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure nginx as a reverse proxy to another container in a docker compose network]]></title>
            <link>https://jonathanantoine.medium.com/configure-nginx-as-a-reverse-proxy-to-another-container-in-a-docker-compose-network-9c8f0c2865cd?source=rss-f5f8d7ee25e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c8f0c2865cd</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Jonathan Antoine]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 15:21:36 GMT</pubDate>
            <atom:updated>2024-10-23T15:55:56.665Z</atom:updated>
            <content:encoded><![CDATA[<h3>Configure nginx as a reverse proxy to another container in a docker compose network to deploy on azure web app</h3><p>Today, I deployed my Single Page Application (SPA) built with Angular (could also be React) and an ASP.NET Core API on an Azure Web App. It wasn’t as straightforward as I expected, and I ran into a problem related to port exposure.</p><p>I had two containers:</p><ol><li>One for the SPA, served via <strong>nginx</strong>.</li><li>One for the API.</li></ol><p>Both were deployed using a simple docker-compose file:</p><pre>services:<br>  front:<br>    depends_on:<br>      - api<br>    image: custom.azurecr.io/my-front:latest<br>    ports:<br>      - &quot;80:80&quot;<br>  api:<br>    image: custom.azurecr.io/my-api:latest<br>    ports:<br>      - &quot;8080:8080&quot;</pre><p>This setup worked perfectly on my local machine: the SPA was available on port 80, and the API on port 8080. However, once deployed to Azure, I hit a snag: <strong>Azure Web App only exposes a single port (443 or 80)</strong> to the outside world, while I needed two — one for the SPA and one for the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*v-FsFBZuzUrUXuBAQez3lw.png" /></figure><h3>Solutuion : using nginx as a reverse proxy</h3><p>After exploring various solutions, the simplest on for my development environment is <strong>to configure my nginx as a reverse proxy to my API inside the docker compose network</strong>. To do so we will use the <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">http_proxy module of nginx</a>.</p><pre>server {<br><br>    # catch all request<br>    listen       80 default_server;<br>    listen  [::]:80;<br>    server_name  _;<br><br>    # all /api request are proxified to my api inside the<br>    # docker compose network<br>    location /api/ {<br>        proxy_pass http://api:8080/;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br><br>    # other requests are served by the static files in the html <br>    # folder (my SPA)<br>    location / {<br>        root   /usr/share/nginx/html;<br>        try_files $uri $uri/ /index.html;<br>    }<br><br>}<br></pre><p>In this setup:</p><ul><li>All requests starting with /api/ are forwarded to the API running on port 8080 within the Docker Compose network.</li><li>Other requests are served by the static files (the SPA).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*Y9-3Y_tWFTfL5lij2NUX5Q.png" /></figure><p>While reproducing this at home, I will save you a couple of hours wondering why its not working :</p><ul><li>The last slash ‘/’ on the ‘location’ definition.</li><li>The last slash ‘/’ on the proxy_pass definition.</li></ul><h3>Applying this configuration</h3><p>To use this configuration, the easiest way is to update your <strong>Dockerfile </strong>to use it. This is done by copying it to the right place and override the default server configuration :</p><pre>COPY nginx/nginx.conf /etc/nginx/conf.d/default.conf</pre><h3>Updating the frontend</h3><p>Of course, you need to update your front end to target this new path instead of a fully different URL :</p><pre>const apiUrl = window.location.protocol + &quot;//&quot; <br>                + window.location.hostname <br>                + &quot;/api&quot;</pre><h3>Conclusion</h3><p>By using nginx as a reverse proxy, you can deploy both your SPA and ASP.NET Core API on an Azure Web App, despite Azure only exposing a single port. This solution allows you to route requests to the correct service within your Docker Compose network, with the SPA served on port 80 and API calls proxied to the internal API service. Updating your Dockerfile and frontend ensures everything works seamlessly in the cloud, just as it does locally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c8f0c2865cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>