<?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 Diego Pereira on Medium]]></title>
        <description><![CDATA[Stories by Diego Pereira on Medium]]></description>
        <link>https://medium.com/@dianper?source=rss-8f7c73a93c7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T35LpNWL840Zcma9RDoGow.png</url>
            <title>Stories by Diego Pereira on Medium</title>
            <link>https://medium.com/@dianper?source=rss-8f7c73a93c7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:49:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dianper/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[I used to need a Blueprint to build a service]]></title>
            <link>https://dianper.medium.com/i-used-to-need-a-blueprint-to-build-a-service-9902da84b4ab?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9902da84b4ab</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[blueprint]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 23:34:41 GMT</pubDate>
            <atom:updated>2026-08-27T23:34:41.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgAJLLy2oxejgGpphuBiBA.png" /></figure><h3>The Blueprint Was Never About the Code</h3><p>A few years ago, creating a new service at a company I worked for was very different from simply creating a repository and starting to write code.</p><p>Before a .NET, Node.js, or Python service could be created, we had to go through a blueprint process. I would open a PR, fill in a YAML file, and define things like which database the service would use, whether it needed Redis, how it should be distributed across data centers, what resources it would need in the cluster, how it would be monitored, and which external dependencies it would have.</p><p>This wasn’t just a template that any developer could fill out on their own. Some of those decisions affected shared infrastructure, reliability, security, or other services, so they often required input from an architect or principal engineer.</p><p>Once the blueprint was approved, the rest of the process was mostly automated. A repository was created with the expected structure, CI/CD configuration was added, and the pipeline was set up based on the choices made in the blueprint. From there, the service could be built into a Docker image and pushed to the container registry.</p><p>At the time, I was mostly focused on getting the service built. But the process was also forcing me to think about things I didn’t normally consider when writing application code: where the service would run, what it would depend on, how it would be deployed, how we would know it was healthy, and what would happen when one of its dependencies failed.</p><p>That was probably the first time I started to see that creating a service wasn’t just about the code. It was also about making the architectural decisions around that code explicit before it ever reached production.</p><h3>Architecture Became a Set of Decisions</h3><p>The interesting part of the blueprint was that very little of it was actually about the application code. It was mostly about the environment the service was going to live in: would it use SQL, MongoDB, or Cassandra? Did it need Redis? How should it be distributed across data centers? How much CPU and memory would it need? What level of observability was required? Which external systems would it depend on?</p><p>These might look like infrastructure details when considered individually, but together they shape a large part of a service’s operational architecture. A database choice affects things like scaling, backup and recovery, cost, and operational ownership. Distribution across data centers affects availability and latency. Resource requirements affect how the service is scheduled and scaled, while external dependencies introduce failure modes that the application needs to account for.</p><p>What I started to understand was that these decisions have a much wider impact than the service itself. They can affect shared infrastructure, other services, operational teams, and the way the system behaves in production.</p><p>That is also why some of these decisions couldn’t be made in isolation by the developer creating the service. Once a decision starts affecting shared infrastructure or organizational standards, it becomes an architectural decision rather than just an implementation detail.</p><h3>From Decisions to a Running Service</h3><p>The real value of the blueprint became clearer once I saw what happened after it was approved. The decisions captured in it were not just documentation; they were used to drive the platform.</p><p>A repository was created with the expected structure, CI/CD configuration was added, and the pipeline was set up based on the choices made in the blueprint. From there, the service could be built into a Docker image and pushed to the company’s container registry.</p><p>This meant that creating a new service didn’t start with setting up a repository, writing pipeline configuration, creating Docker files, or figuring out how to get the first build running. Most of that had already been standardized.</p><p>More importantly, there was a direct connection between architectural decisions and the engineering platform. A choice made when creating the service could influence how infrastructure was provisioned, how the application was configured, which pipeline capabilities were enabled, and what operational requirements were applied.</p><p>That’s when I started to see the blueprint differently. Its value wasn’t in the YAML itself, but in turning decisions and engineering practices into something the platform could consistently apply.</p><p>That, to me, is one of the most useful ideas behind platform engineering: taking practices that have already been figured out and turning them into reusable capabilities, so every team doesn’t have to solve the same problems again.</p><h3>From Platform to AI</h3><p>Over time, this kind of process naturally moves toward self-service. Instead of opening a PR and waiting for an architect or principal engineer to help with every decision, more of the organization’s knowledge can be built into templates, platform capabilities, policies, and automated checks.</p><p>That makes creating a service much easier, but it also creates a different problem. As the platform grows, developers have more things to understand: different templates, technologies, deployment models, databases, messaging systems, security requirements, and organizational rules. The platform may have successfully captured the organization’s knowledge, but finding the right path through all of it can become difficult.</p><p>This is where I think AI becomes genuinely interesting. Not because an agent can generate another repository or write boilerplate code — we already have plenty of tools for that — but because it could become an interface to the engineering knowledge the organization has already built.</p><p>Imagine being able to say:</p><blockquote>“I need a service that consumes events from a queue, stores the data in PostgreSQL, runs across two data centers, and exposes a REST API.”</blockquote><p>Instead of asking the developer to know which template to use and which options to select, an agent could map that intent to the platform’s existing capabilities and standards. It could identify the appropriate template, suggest the supported messaging and persistence options, generate the required configuration, and point out the decisions that still need human input.</p><p>The important part is that the agent wouldn’t be inventing an architecture from scratch. It would be navigating an architectural landscape that the organization has already defined.</p><p>That changes the question from <strong><em>“How do we get AI to design our systems?”</em></strong> to something I find much more interesting: <strong><em>“How do we make our existing engineering knowledge understandable and usable by AI?”</em></strong></p><h3>The Hard Part Is Not Generation. It Is Governance.</h3><p>Giving an agent access to architectural knowledge also changes the governance problem. With a traditional template, the boundaries are relatively clear: developers choose from a predefined set of options, and the template can enforce some of the organization’s standards. An agent introduces more flexibility, and there may be several technically valid ways to solve the same problem. The challenge is no longer just knowing what is possible, but understanding what is acceptable within the organization.</p><p>I think this is where the distinction between deterministic and contextual decisions becomes important. Approved technologies and dependencies, mandatory security controls, naming conventions, resource limits, observability requirements, and deployment constraints are all things we should be able to validate automatically. There should be very little ambiguity around them.</p><p>Other decisions are inherently more contextual. Choosing between two valid architectural approaches might depend on expected traffic, failure tolerance, latency requirements, existing dependencies, team expertise, operational cost, or how the system is expected to evolve. These are much harder to reduce to a set of rules.</p><p>This is also where I think the role of architects, staff engineers, and principal engineers becomes more important, not less. The goal shouldn’t be for senior engineers to manually approve every decision. It should be to define clear boundaries for teams and automation to make decisions independently.</p><p>Good architecture governance isn’t about controlling every implementation detail. It’s about making the important constraints explicit while leaving enough freedom inside those constraints for teams to move quickly. The clearer those boundaries are, the more autonomy we can safely give to automation, including AI agents.</p><h3>What I Would Automate First</h3><p>If I were building this kind of platform today, I wouldn’t start by asking AI to make architectural decisions. I’d start with the things we already know how to define and validate: approved technologies and dependencies, mandatory configuration, security requirements, resource limits, naming conventions, observability, and deployment policies.</p><p>These are good candidates for automation because the expected outcome is usually clear. We can encode the rules, enforce them consistently, and make them part of the platform instead of relying on every developer to remember them.</p><p>Once that foundation is in place, an agent can gradually take on decisions that require more context. The more predictable parts are handled automatically, the more room engineers have to focus on the decisions where experience and judgment actually matter.</p><p>The goal isn’t to automate every architectural decision. It’s to automate the decisions that don’t need much judgment in the first place.</p><h3>What Changed, What Didn’t</h3><p>When I think about that blueprint process now, I realize it taught me something I didn’t fully understand at the time: building software is about much more than writing the code.</p><p>The tools have changed. What used to be a YAML blueprint might now be a platform API, a template, a policy engine, a developer portal, or an AI agent. But the underlying problem is still the same: how do we capture the engineering decisions an organization has already made, make them reusable, and still leave room for judgment when a problem doesn’t fit the standard path?</p><p>AI gives us a new way to approach that problem. It can make organizational knowledge easier to discover and apply, but it can’t replace knowledge that was never made explicit in the first place.</p><p>That’s probably what I find most interesting about this evolution. We may eventually have fewer developers manually configuring infrastructure and more agents translating intent into platform capabilities, but the need for good architectural decisions doesn’t go away.</p><p>If anything, the more responsibility we give to automation, the more important it becomes to make those decisions explicit.</p><p>And ultimately, I think that leaves us with a fairly simple question:</p><p><strong><em>What are we comfortable automating, and where do we still need engineering judgment?</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9902da84b4ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Prompt to Page: AI-Driven Browser Navigation with Playwright MCP]]></title>
            <link>https://dianper.medium.com/from-prompt-to-page-ai-driven-browser-navigation-with-playwright-mcp-2f5cdda4a1a1?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f5cdda4a1a1</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 00:49:31 GMT</pubDate>
            <atom:updated>2026-08-19T00:49:31.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgX3lLtUimdVUy1SFUEBAQ.png" /></figure><p>If you’ve been working with AI tooling lately, you’ve probably come across MCP (Model Context Protocol), introduced by Anthropic. In simple terms, MCP provides a standard way for AI models to interact with external tools and data sources. You can think of it as a kind of plugin system for AI assistants.</p><p>In this article, I want to focus on something a bit more practical: <strong>Playwright MCP</strong>. It exposes browser automation capabilities through MCP, allowing an AI agent to interact with a web application using natural language instead of writing Playwright code for every step.</p><p>To make this concrete, I’ll use a real example: an AI agent navigating a <strong>.NET 10 Blazor Server application protected by Keycloak OIDC authentication</strong>.</p><p>Along the way, we’ll look at how to set everything up, how to write prompts that actually work, a rather important authentication gotcha I ran into, and where this approach fits compared to writing traditional Playwright tests.</p><h3><strong>What is Playwright MCP?</strong></h3><p>Playwright MCP is an open-source MCP server maintained by Microsoft. It builds on top of Playwright’s browser automation capabilities and exposes them as MCP tools that compatible AI clients can use.</p><p>One interesting part of how it works is that the agent doesn’t rely on screenshots to understand the page. Instead, Playwright MCP uses the <strong>accessibility tree</strong>. When the agent takes a snapshot, it gets a structured representation of the page with roles, labels, and references rather than raw pixels.</p><p>This gives the agent a much cleaner way to understand and interact with the page, without depending on how the UI happens to look visually.</p><pre><br># Example snapshot (accessibility tree)<br>- heading &quot;Sign in to your account&quot; [level=1]<br>- textbox &quot;Username or email&quot; [active]<br>- textbox &quot;Password&quot;<br>- button &quot;Sign In&quot;</pre><p>The agent uses these references to click, type, and navigate — deterministically.</p><h4><strong>What did I use to build this?</strong></h4><p>For the demo, I used VS Code with GitHub Copilot, mainly because it has built-in MCP support and makes it easy to keep reusable prompts in .prompt.md files.</p><p>That said, Playwright MCP isn’t tied to VS Code or Copilot. The same server can be used with Claude Desktop, Cursor, Windsurf, or any other MCP-compatible client. The main difference is how you configure the MCP server and, in some cases, how you provide the prompt to the agent.</p><h3><strong>The Demo App</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obZ0pLMvUo-oLI4qVBrnPQ.png" /></figure><p>For the demo, I wanted the application to be close to something you might actually find in an enterprise environment, rather than a simplified test page.</p><p>The stack is:</p><ul><li><strong>.NET 10 Blazor Server</strong> — server-side rendering with SignalR, with [Authorize] applied to protected pages.</li><li><strong>Keycloak 26 via Docker</strong> — a real OIDC provider rather than a mock. The realm configuration is imported automatically when Keycloak starts, so there’s no manual setup.</li><li><strong>OIDC Authorization Code Flow</strong> — the standard authentication flow for web applications.</li></ul><p>The application has four pages:</p><ul><li>/ — Public. The home page shows the current login status.</li><li>/dashboard — Protected. Shows a set of activity cards.</li><li>/profile — Protected. Displays the claims returned by Keycloak.</li><li>/contact — Protected. Contains a simple contact form.</li></ul><h4><strong>The “Correlation Failed” Gotcha</strong></h4><p>When running on plain HTTP locally, you’ll hit this error on the first login attempt:</p><pre>AuthenticationFailureException: Correlation failed.</pre><p>This happens because ASP.NET Core’s OIDC middleware creates correlation and nonce cookies before redirecting to Keycloak. When Keycloak redirects back, the browser needs to send those cookies — but the default cookie security policy marks them as Secure, and the browser drops them on HTTP.</p><p><strong>Fix:</strong></p><pre>.AddOpenIdConnect(options =&gt;<br>{<br>    // ... other config ...<br>    options.RequireHttpsMetadata = false; // dev only<br><br>    // prevent correlation/nonce cookies from being dropped on plain HTTP<br>    options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.None;<br>    options.CorrelationCookie.SameSite = SameSiteMode.Lax;<br>    options.NonceCookie.SecurePolicy = CookieSecurePolicy.None;<br>    options.NonceCookie.SameSite = SameSiteMode.Lax;<br>});</pre><h3><strong>Setting Up Playwright MCP</strong></h3><p>The entire MCP configuration is a single file:</p><pre>{<br>  &quot;servers&quot;: {<br>    &quot;playwright&quot;: {<br>      &quot;type&quot;: &quot;stdio&quot;,<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [&quot;@playwright/mcp@latest&quot;, &quot;--caps&quot;, &quot;storage&quot;]<br>    }<br>  }<br>}</pre><p>The --caps storage flag enables the browser_save_storage_state and browser_set_storage_state tools, which we&#39;ll use for the auth state pattern later.</p><p>In VS Code: open the Command Palette → <strong>MCP: List Servers</strong> → confirm playwright is running. Then switch Copilot Chat to <strong>Agent</strong> mode.</p><p>For other clients, check their respective MCP configuration docs — the server command is the same, only the config file format differs.</p><h3><strong>Designing the Prompts</strong></h3><p>Each scenario lives in a .prompt.md file under .github/prompts/.</p><p>In VS Code with Copilot, these become slash commands (e.g., /01-login-flow). In other clients, you copy the content into the chat.</p><p>The file format is straightforward:</p><pre>---<br>description: &quot;Short description of what this prompt does&quot;<br>---<br><br># Prompt title<br><br>## Steps<br>1. ...<br>2. ...</pre><h4><strong>Reporting Instructions</strong></h4><p>One of the more useful patterns: a .instructions.md file that defines how the agent should format its output across all prompts.</p><pre>// .github/instructions/playwright-reporting.instructions.md<br>---<br>applyTo: &quot;.github/prompts/**&quot;<br>---<br><br>Each step must be reported as:<br>✅ Step N — action — confirmation (URL: ...)<br>❌ Step N — action — error (URL: ..., Element: ..., Error: ...)<br><br>End every prompt with a summary block:<br>- Total steps / Passed / Failed / Skipped / Status</pre><p>The applyTo pattern scopes these rules to prompt files only. The result: every run produces a consistent, readable report regardless of which prompt you run.</p><h4>Credentials and the Auth State Pattern</h4><p>The most interesting design decision: <strong>how does the agent authenticate?</strong></p><p>The naive approach is putting credentials directly in the prompt. Fine for a demo, but it sets a bad precedent — credentials in version-controlled files is a habit worth breaking early.</p><p>The better approach is Playwright’s own recommended pattern: <a href="https://playwright.dev/docs/auth">storage state</a>. You authenticate once, save the browser session to a file, and subsequent prompts load that file instead.</p><p>This is the key distinction: the first login is still a human-driven bootstrap step, because Keycloak is doing an actual OIDC sign-in. After that, the rest of the flow can run headlessly by restoring the saved browser state from .auth/auth.json.</p><p><strong>Prompt 00 — Save Auth State:</strong></p><pre>## Steps<br>1. Navigate to http://localhost:5000<br>2. Click the Login link<br>3. Confirm the Keycloak page loaded<br>4. **STOP** — Ask the user: &quot;The Keycloak login page is open. <br>   Please type your credentials manually and press Sign In. <br>   Reply here when you are back on http://localhost:5000.&quot;<br>5. After the user confirms, verify #auth-status shows logged-in state<br>6. Save browser storage state to .auth/auth.json</pre><p>The agent stops at step 4 and waits for you to type credentials in the browser. You reply done in the chat, and the agent saves the session. From that point, prompts 04, 05, and 06 load .auth/auth.json — no credentials anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*jAqo9-_SAIUyFHFdR5XB-g.png" /><figcaption>00-save-auth-state.prompt.md</figcaption></figure><h3>The Demo Scenarios</h3><p>Seven prompts cover the main scenarios (prompt 00 was already covered above):</p><p><strong>Prompt 01 — Login Flow</strong> Full OIDC flow from the home page to authenticated state. This prompt intentionally includes test credentials because demonstrating the login flow <em>is</em> its purpose.</p><p><strong>Prompt 02 — Logout </strong>Verifies the complete logout cycle: clicks the Logout link, confirms Keycloak ends the SSO session, and checks the app returns to the unauthenticated state. Simple, but essential — a broken logout is a security issue, not just a UX one.</p><p><strong>Prompt 03 — Protected Page Redirect</strong> Navigate directly to /dashboard without a session. The agent verifies the redirect chain ends at localhost:8080/realms/demo — no login required to run this prompt, which makes it a clean isolated test.</p><p><strong>Prompt 04 — Authenticated Navigation </strong>Loads `/.auth/auth.json, then navigates between Dashboard, Profile, and Home. Verifies that the session persists across page transitions and that each protected page renders its content correctly.</p><p><strong>Prompt 05 — Form Submission</strong> Load auth state, navigate to /contact, fill all fields, submit, verify the success message. This is where Blazor&#39;s SignalR nature becomes relevant: the success state is a server-push update, not a page reload. The agent handles this correctly because it uses the accessibility tree snapshot, which reflects the current DOM state after the SignalR update.</p><p><strong>Prompt 06 — Full Demo</strong> All five scenarios in sequence with a consolidated report. This is the one I run at the start of the presentation.</p><p><strong>Prompt 07 — Validation Failure</strong> This one is intentionally different: it submits the contact form with empty fields, then with an invalid email, and verifies the app correctly rejects both. The report will show ✅ on the steps that expect rejection — making it clear that a ✅ doesn’t always mean “it worked”, it means “the expected outcome occurred”. It ends with a valid submission to confirm recovery. This is the most honest part of the demo.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EwmhfFVH-48qHr1uIdBHw.png" /><figcaption>06-full-demo.prompt.md</figcaption></figure><h4><strong>What worked well:</strong></h4><ul><li>The accessibility tree approach is fast. No waiting for visual rendering, no flaky selectors based on CSS classes</li><li>Adding explicit id attributes to Blazor components (id=&quot;auth-status&quot;, id=&quot;login-link&quot;, etc.) made agent targeting precise and resilient</li><li>The reporting instructions produced consistent output across all runs — useful when you want to compare results across runs or share them with the team</li></ul><h4><strong>What to watch out for:</strong></h4><ul><li>Session state doesn’t persist between Copilot Chat turns by default. If you open a new chat session, you need to re-run prompt 00 or restore state manually</li><li>Blazor SignalR establishes a websocket connection after initial page load. If the agent snapshots too early, it may see a loading state. In practice this wasn’t an issue, but worth knowing</li><li>The Correlation failed error on plain HTTP will block your first login — see the fix above</li></ul><h3>When to Use Playwright MCP (and When Not To)</h3><p>This is the section I think matters most.</p><h4><strong>Good use cases:</strong></h4><ul><li><strong>Demos and presentations:</strong> show the team how an authenticated flow works without writing test code</li><li><strong>Exploratory testing: </strong>quickly verify a new page or feature works before writing formal tests</li><li><strong>Onboarding: </strong>new team members can run prompts to understand app flows without reading code</li><li><strong>Documenting behavior: </strong>the agent output is a readable log of what the app does</li></ul><h4><strong>Where it falls short:</strong></h4><p>Every prompt execution consumes tokens — both for the instructions and for each tool call response (snapshots can be verbose). Running your full test suite this way would be expensive and slower than a traditional test runner.</p><h4><strong>For CI, use the Playwright .NET SDK instead:</strong></h4><pre>// The same scenarios, but as a proper test<br>[Fact]<br>public async Task Dashboard_RequiresAuthentication_RedirectsToKeycloak()<br>{<br>    await Page.GotoAsync(&quot;http://localhost:5000/dashboard&quot;);<br>    await Expect(Page).ToHaveURLAsync(new Regex(&quot;localhost:8080/realms/demo&quot;));<br>}</pre><p>The way I think about it: <strong>Playwright MCP is for humans in the loop; Playwright Test is for automated pipelines</strong>. They’re not stages — you don’t have to graduate from one to the other. You might have a full Playwright test suite in CI and still reach for MCP when you need to quickly verify something on a feature branch, demo a flow to a stakeholder, or debug why a test is failing. They solve different problems.</p><h3>Wrapping Up</h3><p>Playwright MCP removes the friction between “I want to verify this works” and actually doing it. No test file, no setup, no build — just describe what you want and watch it happen.</p><p>The patterns that made this demo work cleanly:</p><ol><li><strong>Semantic IDs on components: </strong>make the agent’s job unambiguous</li><li><strong>Reporting instructions: </strong>consistent output without repeating yourself in every prompt</li><li><strong>Auth state over credentials: </strong>the right habit regardless of AI tooling</li><li><strong>Small focused prompts + one orchestration prompt: </strong>easier to debug, easy to present</li></ol><p>The full project — including the Blazor app, Keycloak realm config, all prompts, and MCP setup — is on GitHub: <a href="https://github.com/dianper/demo-playwright-mcp"><em>github.com/dianper/demo-playwright-mcp</em></a></p><h3>References</h3><ul><li><a href="https://github.com/microsoft/playwright-mcp">Playwright MCP — GitHub (microsoft/playwright-mcp)</a></li><li><a href="https://modelcontextprotocol.io/introduction">Model Context Protocol — Official Docs</a></li><li><a href="https://www.anthropic.com/news/model-context-protocol">MCP Introduction — Anthropic</a></li><li><a href="https://playwright.dev/docs/auth">Playwright Auth — Storage State Pattern</a></li><li><a href="https://playwright.dev/dotnet/docs/intro">Playwright .NET — Getting Started</a></li><li><a href="https://quay.io/repository/keycloak/keycloak">Keycloak — Docker Hub</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/additional-claims">ASP.NET Core — OpenID Connect Authentication</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5cdda4a1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’re Probably Using AI Like Google — Not Like a Pair Programmer]]></title>
            <link>https://dianper.medium.com/youre-probably-using-ai-like-google-not-like-a-pair-programmer-9862070014ea?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9862070014ea</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 15:38:29 GMT</pubDate>
            <atom:updated>2026-03-10T16:31:10.947Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Many experienced developers use AI carefully… sometimes too carefully. Here’s how tools like Claude in Visual Studio become much more useful when you stop treating them like a better search engine.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QG8WesxBglxfgRAeUrQtPQ.png" /></figure><h3>Why many experienced developers use AI carefully</h3><p>There is a quiet group of developers in the AI era.</p><p>They are experienced, often with 10+ years in the industry. They know architecture, patterns, trade-offs, and they’ve seen enough hype cycles to be skeptical.</p><p>And they do use AI tools like Copilot or Claude. But usually in a very cautious way.</p><ul><li>They ask small questions.</li><li>Generate the occasional snippet.</li><li>Maybe explain an error message.</li></ul><p>In practice, the AI becomes something like a very good version of Stack Overflow.</p><p>And that’s completely reasonable. Experienced developers care about code quality, maintainability, and understanding what happens inside their systems. Blindly generating code is not appealing.</p><p>The caution makes sense. But there’s a difference between being skeptical of AI hype and underusing a tool that could genuinely reduce friction in your day-to-day work.</p><p>Many of these developers are leaving a lot of value on the table — not because the tools are bad, but because they’re being used with the wrong mental model.</p><p>AI in the IDE is not just a smarter search engine. When used with the right context, it can behave much closer to a pair programmer that understands your project.</p><h3>AI as an Advisor vs a Pair Programmer</h3><p>Many experienced developers use AI tools in a very specific way. They ask questions like:</p><ul><li>How do I configure AutoMapper for this scenario?</li><li>Why am I getting this NullReferenceException?</li><li>What’s the best way to structure this LINQ query?</li></ul><p>In these situations, the AI behaves like an advisor. It explains things, suggests approaches, and sometimes generates a small snippet that you adapt manually. This is useful. But it only uses a small part of what these tools can actually do.</p><p>The real shift happens when you start using AI as a pair programmer that understands your project context. Instead of asking how something works, you start asking the AI to implement things inside your existing architecture.</p><p><strong>Instead of this:</strong></p><pre>How do I create an AutoMapper mapping for Order and OrderDTO?</pre><p><strong>Try this:</strong></p><pre>Create the AutoMapper profile for Order -&gt; OrderDTO. <br>Follow the pattern used in the existing BaseProfile class in this project. <br>Flatten nested entities where appropriate and keep GUIDs unchanged.</pre><p>The difference may look small, but the mindset is completely different. One produces a generic answer. The other produces code that fits where it needs to live. In the first example, the AI is explaining something in isolation. In the second, it is working inside the reality of your project.</p><h3>Why Files Like CLAUDE.md Don’t Work the Same Way Everywhere</h3><p>One common mistake when working with AI coding tools is assuming that instructions work the same way everywhere. You might see recommendations like creating a CLAUDE.md file or adding .github/copilot-instructions to guide the AI. Sometimes this works well. But it depends a lot on the tool.</p><p>A concrete example: CLAUDE.md is a file used by Claude Code (Anthropic’s CLI). It is not automatically read by GitHub Copilot in Visual Studio. If you are using Claude as a model inside Copilot Chat in VS 2026, that file does nothing. The instructions don’t carry over automatically between tools — each integration has its own context model.</p><p>Different IDEs also consume context differently. In Visual Studio, suggestions are often influenced more by the solution structure, currently opened files, and nearby classes and types.</p><p>Because of this, the most reliable way to guide the model is providing real project context. When the AI can see your patterns, it becomes much more likely to generate code that actually fits your architecture.</p><h3>Model vs Agent: The Difference Between Thinking and Acting</h3><p>Another important distinction when working with AI in the IDE is the difference between a model and an agent.</p><p>When you interact with AI in a chat window, you are usually talking directly to the model. The model is excellent at reasoning — it can explain errors, suggest approaches, or help you understand unfamiliar code.</p><p>But modern IDE integrations are introducing something different: agents. An agent is the same intelligence — but with the ability to act on your project. Instead of just generating a snippet, it can modify multiple files and propose changes across the solution.</p><p><em>For example, given a prompt like:</em></p><pre>Create a POST endpoint for Orders following the same pattern used in CustomerController.</pre><p>An agent could then:</p><ul><li>Create the controller method</li><li>Add a service interface</li><li>Implement the service</li><li>Register it in dependency injection</li><li>Propose the changes as a diff</li></ul><p>In Visual Studio 2026, you get Claude as a model in Copilot Chat. The full Agent experience — with file-level actions and diffs — currently lives in VS Code. Many developers end up using both: VS Code for agentic tasks, Visual Studio for debugging and heavy C# navigation.</p><p>This is where AI starts to feel less like a tool and more like a developer assisting you with the mechanical parts of the work.</p><h3>Where AI Actually Helps Experienced Developers</h3><p>A common fear among experienced developers is that AI will try to write the core logic of the system — and do it poorly. In practice, the real value usually appears somewhere else.</p><p>For a developer with 10+ years of experience, the architectural decisions are rarely the bottleneck. The friction is usually everything around them. AI tends to be most useful in the mechanical parts of development that surround the actual design decisions.</p><p>Things like:</p><ul><li>Generating unit tests</li><li>Creating mocks and test data</li><li>Mapping DTOs</li><li>Writing boilerplate endpoints</li><li>Refactoring repetitive patterns</li><li>Explaining unfamiliar parts of the codebase</li></ul><p>These tasks are necessary, but they rarely require deep architectural thinking.</p><p>For many senior developers, this is where AI becomes surprisingly valuable. Not as a replacement for experience, but as a way to reduce cognitive load.</p><h3>A Different Way to Think About AI in the IDE</h3><p>For experienced developers, the challenge with AI is usually not learning the tool. It’s changing the mental model.</p><p>If AI is treated like a better search engine, it will mostly behave like one. Useful, but limited.</p><p>The real shift happens when you start treating it more like a pair programmer with access to your project context. It won’t replace experience. It won’t design your architecture.</p><p>But it can remove a lot of the friction around those decisions.</p><blockquote>Start small: next time you’d reach for Stack Overflow, try giving the AI a real file from your project as context. The difference in output quality is immediate.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9862070014ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI in the Backend: Architectural Patterns, Pitfalls, and Production-Safe Approaches]]></title>
            <link>https://dianper.medium.com/ai-in-the-backend-architectural-patterns-pitfalls-and-production-safe-approaches-edd0b4f844f1?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/edd0b4f844f1</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 15:22:34 GMT</pubDate>
            <atom:updated>2026-03-01T15:22:34.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Integrating AI into your backend can unlock powerful capabilities, but without the right architecture, it can quickly become a source of latency, failures, and security risks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aa150tGjen07krHviPkrSA.png" /></figure><p>In recent years, adding artificial intelligence to the backend has become remarkably easy. With just a few API calls to large language models, teams can generate analyses, summarize logs, or provide recommendations without writing complex algorithms. For many engineers, the temptation is strong: “let’s just integrate AI directly into the request path and call it done.” But behind this apparent simplicity lies real challenges. Unpredictable latency, cascading failures, security risks, and reduced observability can turn a promising feature into a critical production problem. For teams working on sensitive systems, such as IAM, security, or cloud platforms, understanding these trade-offs is essential before making any architectural decisions.</p><h4>Bad Patterns</h4><p>Many teams make the mistake of treating AI like just another API call. The simplest approach is to call a language model or AI service directly in the request path and return the result to the client. At first glance, this seems convenient and fast. But in production, this pattern introduces serious problems: unpredictable latency, cascading failures, increased tail latency, and potential security issues. Even experienced engineers can underestimate how quickly a single slow or failing AI request can affect the entire system. Below is a simple example of a bad pattern in a .NET backend:</p><pre>public async Task&lt;IActionResult&gt; AnalyzePolicy(Policy policy)<br>{<br>    var result = await llmClient.Analyze(policy);<br>    return Ok(result);<br>}</pre><p>This code is easy to write, but it blocks the request until the AI completes, exposing the system to timeouts, errors, and poor user experience. For systems handling sensitive data, like IAM or security platforms, the risks are even greater.</p><h4>Good Patterns: Production-Safe Approaches</h4><p>The key to safely integrating AI into backend systems is to treat it as a <strong>slow, non-deterministic, and potentially unreliable dependency</strong>. Instead of calling AI services directly in the request path, the recommended approach is to <strong>decouple AI processing using queues and background workers</strong>. This allows your system to remain responsive, reliable, and observable, while still taking advantage of AI capabilities.</p><p>A typical production-ready architecture looks like this:</p><pre>Client Request<br>  -&gt; API / Service<br>    -&gt; Queue (e.g., Azure Service Bus, RabbitMQ)<br><br>Background Worker / AI Service<br>  -&gt; LLM / AI Model<br>    -&gt; Store Results<br><br>Client Polls or Receives Notification</pre><p><strong>Benefits of this pattern:</strong></p><ul><li><strong>Async processing</strong>: Requests return quickly without blocking on AI calls.</li><li><strong>Reliability</strong>: Failures in AI calls don’t crash the request path.</li><li><strong>Scalability</strong>: You can scale workers independently of the API.</li><li><strong>Observability</strong>: Queue depth, processing time, and AI latency can be monitored easily.</li><li><strong>Security</strong>: Sensitive data can be sanitized before sending to AI, and retries or caching can be safely handled.</li></ul><h4>Observability &amp; Security Considerations</h4><p>Adding AI to a backend is not just about writing code; It also introduces <strong>new risks and monitoring requirements</strong>. Unlike traditional services, AI calls are slow, non-deterministic, and often external. Without proper observability, it’s easy for latency spikes, failed requests, or misbehaving models to silently degrade the system.</p><p><strong>Observability best practices include:</strong></p><ul><li><strong>Tracing</strong>: Use OpenTelemetry spans to track each AI request through the system, including queue wait time, worker processing, and LLM latency. Example in .NET:</li></ul><pre>using var activity = activitySource.StartActivity(&quot;llm_analysis&quot;);<br>activity?.SetTag(&quot;ai.model&quot;, &quot;gpt-4&quot;);<br>activity?.SetTag(&quot;ai.operation&quot;, &quot;policy_analysis&quot;)</pre><ul><li><strong>Metrics</strong>: Track queue depth, processing time, retry attempts, and AI error rates. Monitoring tail latency (p95/p99) is essential, since AI responses are highly variable.</li><li><strong>Logging</strong>: Record errors, timeouts, and unusual patterns, without exposing sensitive data. Make logs structured for easy alerting and analysis.</li></ul><p><strong>Security considerations are equally critical:</strong></p><ul><li><strong>Data sanitization</strong>: Never send raw sensitive data (tokens, passwords, PII) to external AI services. Transform domain models into sanitized DTOs.</li><li><strong>Prompt injection protection</strong>: Treat AI input carefully — malicious users could try to manipulate the model if raw input from untrusted sources is used.</li><li><strong>Vendor trust / self-hosting</strong>: For highly sensitive systems, consider running AI models in-house to avoid data leaving your infrastructure.</li></ul><p><strong>Other operational patterns to consider:</strong></p><ul><li><strong>Timeouts and circuit breakers</strong>: Never call AI services without them. In .NET, tools like Polly can help.</li><li><strong>Caching</strong>: Store AI results for repeated or similar requests to reduce latency and cost.</li><li><strong>Idempotency</strong>: Ensure worker jobs are safe to retry without causing inconsistent state.</li></ul><p>By combining <strong>async processing, structured observability, and strict security hygiene</strong>, teams can integrate AI safely into backend systems without risking production reliability or sensitive data.</p><h4>When to Use AI in Backend</h4><p>AI is not a silver bullet. Just because it’s easy to call a language model doesn’t mean it should be part of every backend flow. Understanding the right use cases is key to maintaining reliability, security, and performance.</p><p><strong>Use AI when:</strong></p><ul><li><strong>Analysis or reasoning is complex:</strong> For example, detecting anomalies in user permissions, summarizing audit logs, or generating risk scores. These tasks benefit from AI’s ability to process and interpret large amounts of semi-structured data.</li><li><strong>The output is non-critical or advisory:</strong> AI is ideal for recommendations, insights, or reports that don’t immediately enforce security or business-critical decisions.</li><li><strong>Batch or asynchronous processing is possible:</strong> Tasks that can run in the background — like nightly log analysis, policy reviews, or scoring — fit naturally with async architectures.</li><li><strong>Sanitization is possible:</strong> You can safely remove sensitive information before sending data to the AI service, ensuring compliance and security.</li></ul><p><strong>Avoid using AI when:</strong></p><ul><li><strong>Immediate enforcement is required:</strong> Don’t rely on AI for authentication, authorization, or any real-time security decisions. A slow or incorrect AI response can break critical flows.</li><li><strong>Deterministic logic is needed:</strong> For calculations, business rules, or validation that must always be consistent, AI adds unnecessary risk.</li><li><strong>Sensitive data cannot be sanitized:</strong> If you would need to send secrets, credentials, or personally identifiable information (PII) directly to an external AI service, the risk outweighs the benefit.</li><li><strong>Low-latency is critical:</strong> AI introduces variable latency that can’t be tolerated in request paths requiring milliseconds-level performance.</li></ul><p>By carefully choosing the right tasks for AI, you can <strong>enhance backend systems without compromising reliability, security, or observability</strong>. The goal is to treat AI as a powerful but controlled tool — an intelligent worker that complements, rather than replaces, your core backend logic.</p><h4>Conclusion</h4><p>Integrating AI into backend systems is tempting, but it comes with <strong>hidden complexity and risk</strong>. When done incorrectly, it can introduce unpredictable latency, cascading failures, security vulnerabilities, and observability blind spots.</p><p>The production-safe approach is to treat AI as a <strong>slow, non-deterministic dependency</strong>: use <strong>async processing</strong>, background workers, queues, and careful sanitization of data. Combine this with <strong>robust observability</strong> and operational patterns such as retries, caching, idempotency, and circuit breakers.</p><p>AI should be applied <strong>where it adds real value</strong> — complex analysis, risk scoring, log summarization, or advisory recommendations — while avoiding critical paths, deterministic logic, or sensitive data flows.</p><p>By following these architectural patterns and best practices, teams can leverage AI to <strong>enhance backend systems safely</strong>, making them smarter, more insightful, and production-ready — without sacrificing reliability, security, or performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd0b4f844f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability is not logging: lessons from running microservices in production]]></title>
            <link>https://dianper.medium.com/observability-is-not-logging-lessons-from-running-microservices-in-production-a289b39c76b6?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a289b39c76b6</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 14:01:10 GMT</pubDate>
            <atom:updated>2026-02-23T14:01:10.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioVr4DmVoP1fjko1V6s-Iw.png" /></figure><h3>A Scenario You Probably Know</h3><p>It’s a normal weekday. No deployments, no infrastructure changes, everything looks healthy, and yet authentication requests start timing out. Not all of them, just enough to raise concern. Some users can log in, others can’t, and retries sometimes work and sometimes don’t. CPU is fine, memory is fine, Kubernetes nodes are healthy, so you check the logs.</p><p>Each service has logs. The API gateway, the identity service, and downstream dependencies all look normal in isolation. No obvious exceptions, no crashes, and yet requests are failing. At this point, a simple question becomes surprisingly hard to answer.</p><p>What actually happened to a single request as it moved through the system?</p><ul><li>Which service was slow?</li><li>Where did the latency start?</li><li>Which dependency caused the failure?</li></ul><p>Logs show individual events, but they don’t tell the full story. That’s the difference between having logs and having true observability. Observability lets you understand your system from the outside, using the signals it produces. This is where OpenTelemetry changed how I design and operate distributed systems. Instead of isolated log entries, you can see the full lifecycle of a request across services, dependencies, and infrastructure, and most importantly, answer production questions in seconds rather than hours.</p><h3>Logs, Metrics, and Traces: the three pillars of observability</h3><p>Observability is built on three fundamental signals: logs, metrics, and traces, each serving a different purpose. Understanding how they work together is what allows you to diagnose production issues effectively, and with OpenTelemetry, these signals are standardized and correlated, making them significantly more powerful in distributed systems.</p><p>Let’s break them down.</p><h4>Logs: discrete events</h4><p>Logs are timestamped records of specific events that happened in your system.</p><p>2026-02-20T10:15:32Z User authentication failed for UserId: 12345</p><p>Logs are useful for answering questions like:</p><ul><li>What error occurred?</li><li>What was the input?</li><li>What was the state at that moment?</li></ul><p>In .NET, this typically looks like:</p><pre>_logger.LogWarning(&quot;Authentication failed for UserId: {UserId}&quot;, userId);</pre><p>Logs provide detailed, contextual information, but they alone cannot show how a request moves across multiple services. They capture isolated events, not the relationships between them.</p><h4>Metrics: numeric signals over time</h4><p>Metrics are numeric measurements aggregated over time, such as the number of authentication requests, error rate, request duration, or CPU usage. They help answer questions like whether the system is healthy, if the error rate is increasing, or if latency is getting worse. With OpenTelemetry, you can define metrics like this:</p><pre>var meter = new Meter(&quot;IdentityService&quot;);<br>var loginCounter = meter.CreateCounter&lt;int&gt;(&quot;identity.login.attempts&quot;);<br>loginCounter.Add(1, new KeyValuePair&lt;string, object?&gt;(&quot;result&quot;,  &quot;success&quot;));</pre><p>Metrics are excellent for dashboards, alerts, and trend analysis, but they don’t explain why a specific request failed.</p><h4>Traces: the full request lifecycle</h4><p>Traces show the complete journey of a request across services and are the most powerful signal in distributed systems. A single trace might look like this:</p><pre>TraceId: abc123<br><br>API Gateway           12ms<br>  -&gt; IdentityService  45ms<br>      -&gt; Database     18ms<br>      -&gt; External IAM 320ms  &lt;- latency here</pre><p>Now the problem becomes obvious. Without traces, finding this could take hours, but with traces, it takes seconds. In the .NET ecosystem, the Activity class is the implementation of the OpenTelemetry Span concept.</p><pre>builder.Services.AddOpenTelemetry()<br>    .WithTracing(tracing =&gt;<br>    {<br>        tracing<br>            .AddAspNetCoreInstrumentation()<br>            .AddHttpClientInstrumentation()<br>            .AddSource(&quot;IdentityService&quot;);<br>    });</pre><p>This automatically captures request flow across services and dependencies. Logs tell you what happened, metrics tell you how often it happened, and traces tell you why it happened. This is why traces are the foundation of observability in modern distributed systems. Especially when running microservices, Kubernetes workloads, or external dependencies, without traces, you’re essentially debugging blind. With traces, you can see the system as it actually behaves.</p><h3>ActivitySource, Tags, and Status: creating meaningful telemetry</h3><p>Automatic instrumentation is a great starting point because, with OpenTelemetry, you can automatically track spans for incoming HTTP requests, outgoing HTTP calls, and database operations. However, it only tells part of the story: while it captures the technical side of your system, it does not provide insight into the business context behind these operations.</p><ul><li>Which user was being authenticated?</li><li>Which identity provider was used?</li><li>Was this a token validation or a token issuance?</li><li>Was this an AI inference or a cache hit?</li></ul><h4>Creating a custom Activity</h4><p>An Activity represents a unit of work within a trace.</p><p>For example, validating an access token:</p><pre>private static readonly ActivitySource ActivitySource = new(&quot;IdentityService&quot;);<br><br>public async Task&lt;TokenValidationResult&gt; ValidateTokenAsync(string token)<br>{<br>    using var activity = ActivitySource.StartActivity(&quot;ValidateAccessToken&quot;);<br><br>    try<br>    {<br>        var result = await _tokenValidator.ValidateAsync(token);<br>        activity?.SetTag(&quot;auth.operation&quot;, &quot;token_validation&quot;);<br>        activity?.SetTag(&quot;auth.result&quot;, result.IsValid ? &quot;success&quot; : &quot;failure&quot;);<br>        activity?.SetStatus(ActivityStatusCode.Ok);<br>        return result;<br>    }<br>    catch (Exception ex)<br>    {<br>        activity?.SetStatus(ActivityStatusCode.Error);<br>        activity?.SetTag(&quot;error.type&quot;, ex.GetType().Name);<br>        throw;<br>    }<br>}</pre><p>Now, instead of just seeing a generic HTTP request, you see the actual business operation, making traces significantly more useful.</p><h4>Tags provide context</h4><p>Tags add structured metadata to spans, allowing you to filter, search, and analyze behavior across the system. For example:</p><pre>activity?.SetTag(&quot;user.id&quot;, userId);<br>activity?.SetTag(&quot;auth.provider&quot;, &quot;AzureAD&quot;);<br>activity?.SetTag(&quot;auth.flow&quot;, &quot;authorization_code&quot;);</pre><p>These tags allow you to answer questions like:</p><ul><li>Are failures happening only with a specific provider?</li><li>Is latency higher for a specific model?</li><li>Which operations are slowest?</li></ul><p>Without tags, traces lack context and offer little insight. By adding tags, however, traces become meaningful and actionable, providing valuable information that can guide decisions and improvements.</p><h4>Status indicates success or failure</h4><p>Setting the Activity status correctly is critical. By using commands like:</p><pre>activity?.SetStatus(ActivityStatusCode.Ok); // or<br>activity?.SetStatus(ActivityStatusCode.Error);,</pre><p>Observability tools such as Microsoft Application Insights or Grafana Labs can automatically highlight failures. This approach is far more reliable than depending solely on logs.</p><h4>Observability should reflect business operations, not just technical ones</h4><p>One of the most valuable mindset shifts is understanding that you should not instrument only frameworks, but also your domain. By instrumenting your domain logic, you gain visibility into what really matters for the business, not just the technical infrastructure.</p><p>Instead of seeing:</p><p>HTTP POST /api/auth/token</p><p>You see:</p><pre>ValidateAccessToken<br>auth.provider = AzureAD<br>auth.result = success</pre><p>This is what makes observability truly useful in production, as it connects system behavior to real business operations and helps you understand the impact of technical events in context.</p><h3>Correlation: connecting the dots across services</h3><p>In a distributed system, a single user request can pass through multiple services, databases, and external APIs. Without proper correlation, each service generates logs and traces in isolation, making it difficult to understand what actually happened. This creates a puzzle: which log entry belongs to which request, which span represents the failed operation, and how latency propagates across services. Correlation is what brings all these pieces together.</p><h4>TraceId and SpanId</h4><p>Every trace contains a TraceId, and each operation within that trace has its own SpanId. The TraceId identifies the request across the entire system, while the SpanId identifies a specific operation within that request.</p><pre>TraceId: abc123<br>SpanId: 001 - API Gateway<br>SpanId: 002 - IdentityService<br>SpanId: 003 - Database<br>SpanId: 004 - External IAM Provider</pre><p>With this structure, you can visualize and understand the full lifecycle of a request, from entry point to completion.</p><h4>Propagating correlation</h4><p>For correlation to work across services, the trace context must be propagated using headers or middleware. This ensures that each downstream service continues the same trace instead of creating a new, disconnected one.</p><p>Example:</p><pre>builder.Services.AddOpenTelemetryTracing(tracing =&gt;<br>{<br>    tracing<br>        .AddAspNetCoreInstrumentation()<br>        .AddHttpClientInstrumentation()<br>        .AddSource(&quot;IdentityService&quot;);<br>});<br><br>// HttpClient automatically propagates trace context</pre><p>This allows all related spans to be linked together under the same trace, preserving the full request flow across service boundaries.</p><h4>Why correlation matters</h4><p>Without correlation, debugging failures across multiple services becomes slow and inefficient. It is difficult to identify the source of latency or errors, and logs and metrics remain fragmented across different systems.</p><p>With proper correlation, a single trace can show the entire request flow. This makes it possible to quickly identify failures, analyze performance bottlenecks, and understand how different services interact.</p><p>This becomes even more important when working with AI services. LLM requests often involve multiple steps, including preprocessing, tokenization, caching, external API calls, and post-processing. Each of these steps adds latency and complexity. Proper correlation allows you to see exactly where delays occur and which component is responsible.</p><p>Correlation transforms isolated logs, metrics, and traces into a coherent and meaningful story.</p><h3>Anti-patterns: what not to do with observability</h3><p>Even with the right tools, poor practices can make observability ineffective or even dangerous. Many of the most common problems in distributed systems come not from missing tools, but from incorrect usage.</p><h4>Logging sensitive data</h4><pre>_logger.LogInformation(&quot;Token received: {Token}&quot;, token);</pre><p>Sensitive information such as passwords, access tokens, refresh tokens, or personal identifiers should never be logged. Even internal logs can be exposed through security breaches, monitoring tools, or CI/CD pipelines, creating serious security risks.</p><h4>Logging entire objects blindly</h4><pre>_logger.LogInformation(&quot;{@Request}&quot;, request);</pre><p>Logging entire objects not only risks leaking PII but also creates <strong>High Cardinality</strong> issues in your backend, making queries slow and expensive, and making it harder to find meaningful events when debugging issues.</p><h4>No correlation between services</h4><p>Without trace propagation, each service behaves like an isolated silo. This makes multi-service failures difficult to debug, hides latency bottlenecks, and prevents teams from understanding the full request flow.</p><h4>Relying only on logs</h4><p>Logs represent individual events, but they do not show relationships between operations or latency across services. Metrics help identify trends, and traces show causality and request flow. Relying only on logs is a common anti-pattern in distributed systems.</p><h4>Adding observability only after incidents</h4><p>Observability should be designed as part of the system from the beginning, not added later as a reaction to incidents. Retrofitting telemetry often results in inconsistent instrumentation, missing context, and incomplete traces.</p><h4>Over-instrumentation</h4><p>Instrumenting everything without a clear purpose creates excessive noise. Too many logs or spans make it harder to identify meaningful signals and increase storage and processing costs. Effective observability focuses on signal over noise.</p><h4>Ignoring business context</h4><p>Instrumenting only technical operations, such as HTTP calls or database queries, provides technical visibility but not business insight. For example, logging “<em>POST /api/auth/token</em>” is far less useful than logging “<em>ValidateAccessToken for user X via AzureAD</em>” which clearly reflects the business operation.</p><h4>Key takeaway</h4><p>Anti-patterns can turn observability from a powerful tool into a source of confusion. A strong observability strategy focuses on meaningful spans, proper correlation, business-relevant tags, and avoiding sensitive data, while always prioritizing signal over noise.</p><p>This foundation prepares you for the next step: exporters and your observability stack, which make telemetry useful by enabling collection, processing, and visualization.</p><h3>Exporters: sending telemetry to your observability stack</h3><p>Instrumenting your services is only part of the process. The telemetry you generate, including logs, metrics, and traces, must be exported, processed, and visualized in order to provide value. This is the role of exporters and collectors.</p><h4>OpenTelemetry Exporters</h4><p>OpenTelemetry provides multiple exporters that allow telemetry data to be sent to different backends.</p><p>Common examples include:</p><ul><li>OTLP (OpenTelemetry Protocol), which can send data to most observability systems</li><li>Application Insights exporter, used with Microsoft Application Insights</li><li>Jaeger exporter, designed for distributed tracing</li><li>Tempo and Grafana, commonly used for metrics and traces visualization</li></ul><pre>builder.Services.AddOpenTelemetryTracing(tracing =&gt;<br>{<br>    tracing<br>        .AddAspNetCoreInstrumentation()<br>        .AddHttpClientInstrumentation()<br>        .AddSource(&quot;IdentityService&quot;)<br>        .AddOtlpExporter(options =&gt;<br>        {<br>            options.Endpoint = new Uri(&quot;http://otel-collector:4317&quot;);<br>        });<br>});</pre><p>These exporters allow telemetry to leave your application and become visible in monitoring platforms.</p><h4>OpenTelemetry Collector</h4><p>The OpenTelemetry Collector acts as a central hub for telemetry data. It receives telemetry from multiple services, processes and transforms it if needed, and exports it to one or more backends.</p><p>Architecture example:</p><pre>Application <br>  -&gt; OpenTelemetry SDK <br>    -&gt; OTLP Exporter <br>      -&gt; Collector <br>        -&gt; App Insights / Grafana / Jaeger / Tempo</pre><p>This architecture provides several benefits, including centralized telemetry processing, the ability to enrich or filter data, reduced load on applications, and the flexibility to send the same telemetry to multiple destinations.</p><p>You may choose to use different tools for different purposes, such as Application Insights for production monitoring, Grafana for internal dashboards, and Jaeger for deep trace debugging. The Collector makes this possible by acting as a single distribution point.</p><p>Exporters make observability actionable. Without them, telemetry exists but cannot be easily visualized, analyzed, or used to generate alerts. With exporters, you can visualize request flows, analyze latency and failures, correlate business and AI operations, and detect incidents early.</p><h3>Observability for AI: monitoring the new frontier</h3><p>AI workloads introduce new observability challenges compared to traditional systems. Latency can vary unpredictably, external services such as LLMs and vector databases may fail intermittently, and costs are directly tied to usage and token consumption. Additionally, AI errors may not always appear as technical failures, making them harder to detect.</p><p>Without proper telemetry, diagnosing issues in AI pipelines becomes extremely difficult.</p><h4>Tagging AI operations</h4><p>Just like business operations, AI calls should be instrumented with meaningful spans and tags.</p><p>Example in .NET:</p><pre>using var activity = ActivitySource.StartActivity(&quot;AICompletion&quot;);<br><br>activity?.SetTag(&quot;ai.model&quot;, &quot;gpt-4&quot;);<br>activity?.SetTag(&quot;ai.operation&quot;, &quot;completion&quot;);<br>activity?.SetTag(&quot;ai.prompt.size&quot;, prompt.Length);<br>activity?.SetTag(&quot;ai.response.size&quot;, response.Length);<br>activity?.SetTag(&quot;ai.tokens.used&quot;, tokensUsed);<br><br>try<br>{<br>    var result = await _aiClient.CompleteAsync(prompt);<br>    activity?.SetStatus(ActivityStatusCode.Ok);<br>    return result;<br>}<br>catch (Exception ex)<br>{<br>    activity?.SetStatus(ActivityStatusCode.Error);<br>    activity?.SetTag(&quot;error.message&quot;, ex.Message);<br>    throw;<br>}</pre><p>This makes it possible to answer important operational questions, such as which models are slow, which prompts are failing, how many tokens are used per request, and where latency occurs in the pipeline.</p><h4>Correlation is key</h4><p>AI pipelines often involve multiple steps and services, such as authentication, prompt preprocessing, LLM calls, post-processing, and database operations.</p><p>By propagating trace context across all these components, you can identify which requests caused high costs, where latency occurred, and how errors relate to specific user actions.</p><h4>Visualizing AI telemetry</h4><p>Using exporters and visualization tools such as Grafana, Application Insights, Jaeger, or Tempo, teams can monitor request duration, detect failures, correlate user behavior with AI performance, and configure alerts for abnormal latency or error rates.</p><p>AI observability is an extension of distributed system observability. The same principles apply: use traces to capture the full request lifecycle, use tags to provide meaningful context, propagate correlation across services, and export telemetry for visualization and analysis.</p><p>This allows teams to debug AI systems with the same confidence and effectiveness as traditional microservices.</p><h3>Security and PII: observability without compromising privacy</h3><p>Observability provides powerful insights, but it must be implemented responsibly. Logging sensitive data or exposing personal information can lead to data breaches, compliance violations, and serious legal and financial consequences.</p><p>This is especially critical in IAM and security-sensitive systems.</p><h4>What NOT to log</h4><p>Sensitive information should never be logged, including passwords, secrets, access tokens, authorization headers, or full request and response bodies containing personal data.</p><p>Instead, use internal identifiers rather than personal information, avoid logging full payloads, and focus only on relevant, non-sensitive metadata.</p><h4>Observability vs Security</h4><p>A good observability strategy balances visibility with privacy and security. You need enough information to debug and monitor systems effectively, while ensuring that sensitive data is never exposed.</p><p>Using OpenTelemetry spans and tags, it is possible to capture meaningful operational context without compromising security.</p><p>Secure observability is ultimately a mindset: you should be able to understand and operate your system effectively without exposing secrets or personal data.</p><p>This principle becomes even more important in modern architectures that combine microservices, cloud infrastructure, IAM systems, and AI workloads.</p><h3>Observability is more than logs</h3><p>Observability is not just a technical feature, but a fundamental part of system design. Whether working with microservices, IAM systems, traditional APIs, or AI workloads, the goal remains the same: to understand system behavior, diagnose problems quickly, correlate events across services, capture meaningful business context, and protect sensitive information.</p><p>Logs, metrics, and traces are the foundation, but their true value comes from how they are instrumented, correlated, and exported.</p><h4>Key principles to remember</h4><p>Instrument your system thoughtfully using meaningful tags and correct statuses. Ensure proper correlation using TraceId and SpanId so that requests can be tracked across services. Avoid common anti-patterns such as logging sensitive data, over-instrumenting, or delaying observability implementation. Use exporters and collectors to transform telemetry into actionable insight. Extend observability to business and AI operations to understand complex workflows and costs. Above all, always respect privacy and security.</p><p>Observability is not something you add after a system is built; it is something you design from the beginning.</p><p>When done well, production systems become easier to understand, maintain, and trust. When done poorly, every incident becomes harder to diagnose and resolve.</p><p>Investing in strong observability practices reduces downtime, accelerates debugging, and increases overall system reliability, safety, and confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a289b39c76b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build Your Own MCP Server in .NET for AI Tools]]></title>
            <link>https://dianper.medium.com/how-to-connect-your-apis-to-llms-a-deep-dive-into-model-context-protocol-mcp-4a596fea343c?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a596fea343c</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 00:26:23 GMT</pubDate>
            <atom:updated>2026-02-04T01:26:32.281Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Language Models are powerful, but they’re isolated from real systems by default. They can’t call your APIs, query your databases, or trigger workflows safely and reliably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGa1lBe9kZMwsvRVjYgVxg.png" /><figcaption>The Model Context Protocol (MCP) acting as a standard interface between AI Clients (Claude, VS Code) and local/remote resources (APIs, Databases, and Filesystem)</figcaption></figure><p>In this article, we’ll build a real .NET-based MCP server that connects APIs to LLMs, turning GitHub issues into actionable tasks automatically. By the end, you’ll understand how MCP works and how to apply it to your own backend systems.</p><h3>What Is Model Context Protocol (MCP)?</h3><p>Large Language Models are great at understanding language, writing code, and helping with complex tasks. But by default, they’re disconnected from real systems. They can’t call your APIs, access your databases, or trigger workflows unless you build custom integrations, and those usually don’t scale well.</p><p>MCP is an open standard that defines how LLM-powered clients (like IDEs, chat apps, or agents) can safely connect to external systems. Instead of building one-off tool integrations for every app, MCP gives us a shared contract that makes tools discoverable, reusable, and easier to maintain.</p><p>In simple terms, MCP helps turn LLMs from “smart chatbots” into real operators of software systems.</p><h3>Core Concepts in MCP</h3><p>Let’s walk through the main building blocks before jumping into the code.</p><h4><strong>Servers and Clients</strong></h4><ul><li><strong>MCP Server: </strong>A service that exposes capabilities like tools, prompts, and data. It sits between the LLM and your real systems (APIs, databases, services).</li><li><strong>MCP Client: </strong>An application that connects to MCP servers, such as VS Code, Claude Desktop, or a custom agent. The client lets the model discover and use those capabilities.</li></ul><h4>Tools, Resources, and Prompts</h4><p>To build a successful MCP server, you need to understand three pillars:</p><ul><li><strong>Tools:</strong> Executable functions the AI can call (e.g., “CreateTask”, “FetchIssues”).</li><li><strong>Prompts:</strong> Pre-defined “templates” or workflows that guide the AI through complex tasks (e.g., a “Daily Planner” workflow).</li><li><strong>Resources:</strong> Static data or files the AI can read for context (e.g., a log file or a database schema).</li></ul><h4>The Contract</h4><p>Each MCP server exposes a manifest file, usually called mcp.json that describes:</p><ul><li>Prompts</li><li>Resources</li><li>Their input and output schemas</li></ul><blockquote>This file acts as a contract between the server and the client, allowing capabilities to be discovered automatically.</blockquote><h3>Why MCP Matters?</h3><p>MCP changes how we build backend systems for the AI era.</p><p>Instead of designing APIs only for humans or frontend apps, we can now build <strong>LLM-friendly interfaces</strong>. Structured, discoverable, and safe ways for models to interact with real systems</p><h3>Project Overview</h3><p>This project uses .NET-based MCP Server that acts as a bridge between a local Task Management API and the GitHub API. The goal is to show, in a practical way, how backend systems can expose their capabilities to LLMs using MCP.</p><h4>Architecture</h4><ul><li><strong>Tasks.API: </strong>A Minimal API with CRUD endpoints, search capabilities, and a simple notification system.</li><li><strong>Tasks.McpServer: </strong>A specialized host built on top of the Model Context Protocol SDK (v0.7.0-preview) that exposes both systems to LLMs through tools and prompts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xuo3t3SYBvNwsmqOZEuXA.png" /></figure><blockquote>This setup allows the model to interact with both systems through a single, standardized interface.</blockquote><h4>Tasks API</h4><p>The Tasks API is built using .NET 9 Minimal APIs and stores data in memory for simplicity.</p><p><em>Here’s a simplified example of how a task creation endpoint looks:</em></p><pre>tasks.MapPost(&quot;/&quot;, (TaskItem input, TaskService tasks, NotificationService notifications) =&gt;<br>{<br>    /// omitted<br>    var created = tasks.Create(input);<br>    return Results.Created($&quot;/tasks/{created.Id}&quot;, created);<br>});</pre><h4>MCP Server</h4><p>The Tasks.McpServer project wraps both the Tasks API and the GitHub API and exposes their operations as MCP tools and prompts.</p><p><strong>Tools</strong></p><pre>[McpServerToolType]<br>public static class TasksTools<br>{<br>  [McpServerTool, Description(&quot;Creates a new task. The model will automatically handle Id and CreatedAt. You only need to provide Title, and optionally Description, IsDone, and DueDate.&quot;)]<br>  public static async Task&lt;string&gt; CreateTaskAsync(<br>      TasksApiClient client,<br>      [Description(&quot;The task details. Focus on Title and optionally Description or DueDate.&quot;)] TaskItem task)<br>  {<br>      var created = await client.CreateAsync(task);<br>      return $&quot;Task &#39;{created.Title}&#39; successfully created with ID {created.Id}.&quot;;<br>  }<br>}</pre><blockquote>From the model’s point of view, this is no longer “calling an API”, it’s simply invoking a tool with structured inputs.</blockquote><p><strong>Prompts</strong></p><pre>[McpServerPromptType]<br>public static class TasksPrompts<br>{<br>    [McpServerPrompt(Name = &quot;daily-planner&quot;), Description(&quot;Helps the user organize their day by analyzing all tasks and identifying priorities.&quot;)]<br>    public static string GetDailyPlannerPrompt()<br>    {<br>        /// omitted<br>        return &quot;Please..&quot;;<br>    }<br>}</pre><p><strong>Program.cs</strong></p><pre>public class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        var builder = Host.CreateApplicationBuilder(args);<br><br>        builder.Logging.AddConsole(options =&gt;<br>        {<br>            options.LogToStandardErrorThreshold = LogLevel.Trace;<br>        });<br><br>        builder.Services<br>            .AddApiClients() // adds tasks &amp; github api clients<br>            .AddMcpServer()<br>            .WithStdioServerTransport()<br>            .WithToolsFromAssembly()<br>            .WithPromptsFromAssembly();<br><br>        await builder<br>            .Build()<br>            .RunAsync();<br>    }<br>}</pre><p>One of the most interesting flows in this project is turning GitHub issues into local tasks automatically.</p><p>The workflow looks like this:</p><ol><li>The model fetches the most recent open issues from a repository (e.g., dotnet/aspnetcore)</li><li>For each issue, it creates a corresponding task in the Tasks API</li><li>It returns a summary of what was created</li></ol><blockquote>This entire flow is orchestrated through MCP tools and prompts</blockquote><h4>MCP Contract</h4><p>The MCP server exposes a manifest file (mcp.json) that describes everything the client is allowed to use: tools, prompts, and resources.</p><p><em>A simplified example:</em></p><pre>{<br>  &quot;inputs&quot;: [],<br>  &quot;servers&quot;: {<br>    &quot;TasksMcpServer&quot;: {<br>      &quot;type&quot;: &quot;stdio&quot;,<br>      &quot;command&quot;: &quot;dotnet&quot;,<br>      &quot;args&quot;: [<br>        &quot;run&quot;,<br>        &quot;--project&quot;,<br>        &quot;\\absolute-path-to-project&gt;\\Tasks.McpServer.csproj&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>This file acts as a contract between the server and any MCP-compatible client, enabling automatic discovery without hardcoding integrations.</p><h3>Running the Project Locally</h3><p>Running this project locally is straightforward if you’re using Visual Studio or VS Code. The workflow is simple: start the MCP server, run the Tasks API, load the MCP manifest, and then interact with it via GitHub Copilot Chat.</p><p><em>Here’s how to get everything up and running:</em></p><ol><li>Start the MCP Server</li><li>Start the Tasks API (different thread)</li><li>Open and start the mcp.json file in VS Code / Visual Studio</li><li>Connect to GitHub Copilot Chat</li><li>Use a prompt</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qpfj0rd503MlcAuwIpEMZw.png" /><figcaption>Load and start the mcp.json file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*oEo2Uf_boHJaF07FHnH7sQ.png" /><figcaption>Connect MCP Server to GitHub Copilot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*JnS3Ex4I2cZZ-SqUZEZcPw.png" /><figcaption>Use a prompt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*K3N_Yynt2fYab36Q9gNEAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*MswJigT5IgqK4bzyOU2Xnw.png" /></figure><p>Now, when you execute the prompt, the model will:</p><ul><li>Fetch data from GitHub</li><li>Create tasks in your local Tasks API</li><li>Return a structured summary</li></ul><p><strong>GitHub Issues</strong> (dianper/tasks-mcp-server)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*T10PVLk-iOzdgVcpR611LQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*uQHPwulQCbIZZR97eKOcyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*MZpIMSlFfkZR1Q68S683rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*LFff9v43dwt15a8eVQgWbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*gR8yxQx6ve231UylnZgPvg.png" /></figure><p>This process demonstrates the power of MCP: we’ve exposed real APIs to an LLM, orchestrated workflows, and made them immediately accessible in a chat interface.</p><h3>References &amp; Useful Links</h3><p>If you’re curious to explore the project further or dive deeper into MCP, here are some useful resources:</p><ul><li>Link to the <a href="https://github.com/dianper/tasks-mcp-server">GitHub Repo</a>.</li><li>Link to the official <a href="https://modelcontextprotocol.io/docs/getting-started/intro">Model Context Protocol</a> docs.</li><li>Link to the <a href="https://github.com/modelcontextprotocol/csharp-sdk">C# MCP SDK</a>.</li></ul><blockquote><em>Feel free to clone the repo, run it locally, and experiment with the MCP tools and prompts. This project is meant to be a hands-on demonstration of how real APIs can be exposed safely to LLMs.</em></blockquote><p>Thanks for reading, and see you in the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a596fea343c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Have you tried .NET Aspire?]]></title>
            <link>https://dianper.medium.com/have-you-tried-net-aspire-ce8bc869baeb?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8bc869baeb</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[net-9]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[net-aspire]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 16:43:08 GMT</pubDate>
            <atom:updated>2024-12-31T17:10:31.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>Have you tried .NET Aspire?</h3><p>What is .NET Aspire, and how can it be used? In this article, I will show you how I implemented a file-processing workflow application using .NET 9 and .NET Aspire with integrations with Azure Services, Databases, and Cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJ36aU0rdt_KeXaijWCtkA.png" /></figure><h3>.NET Aspire Overview</h3><h4>What is .NET Aspire?</h4><p>.NET Aspire is a comprehensive suite of tools, templates, and NuGet packages designed to streamline the development of cloud-native, production-ready, and observable applications. It facilitates the creation of microservices and integration with various services like databases, messaging, and caching, catering to the needs of modern, interconnected app architectures.</p><h4>Why .NET Aspire?</h4><p>.NET Aspire enhances the development experience for .NET cloud-native applications by offering consistent tools and patterns for building and running distributed apps. It includes features for orchestration of multi-project applications, standardized NuGet integrations for services like Redis and Postgres, and comprehensive tooling for Visual Studio, Visual Studio Code, and the .NET CLI.</p><h4>Orchestration</h4><p>.NET Aspire’s orchestration simplifies local development by managing cloud-native app configurations and interconnections. While not a replacement for production tools like Kubernetes, it provides abstractions for service discovery, environment variables, and container setups, ensuring consistent patterns and easing the management of complex applications during development.</p><h4>Integrations</h4><p>.NET Aspire integrations are NuGet packages that simplify connecting to services like Redis or PostgreSQL by handling cloud-native concerns such as health checks and telemetry. Each integration includes a hosting package for the service and a corresponding client package for the consumer, working seamlessly with Aspire’s orchestration to automatically configure communication between services based on their resource references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lAs5zYtm8CNINgJv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xjHS1ggV6_PZhZOO" /></figure><h4>Service Discovery</h4><p>.NET Aspire includes functionality for configuring service discovery at development and testing time. Service discovery functionality works by providing configuration in the format expected by the <em>configuration-based endpoint resolver</em> from the .NET Aspire AppHost project to the individual service projects added to the application model.</p><h4>Service Defaults</h4><p>The .NET Aspire Service Defaults project offers a collection of extension methods designed to integrate telemetry, health checks, and service discovery into applications. It is highly customizable and extensible, making it ideal for cloud-native applications that require robust configuration management.</p><blockquote>It should not include other shared functionality or models, which should instead be managed in a conventional shared class library project.</blockquote><h4>Dashboard</h4><p>.NET Aspire project templates include a robust dashboard for real-time app monitoring and inspection, also available in standalone mode. The dashboard offers insights into logs, traces, and environment configurations while allowing you to manage resources by stopping, starting, or restarting them, enhancing the development experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mfdxQQn8btX9aa7s" /></figure><h4>Deployments</h4><p>.NET Aspire projects are designed with cloud-agnostic principles, offering deployment flexibility across various platforms that support .NET and containers. The provided guidelines can be adapted for deployment on different cloud environments or local hosting. While manual deployment is possible, it involves complex steps that are prone to errors. Users typically prefer using CI/CD pipelines and cloud-specific tools for a more efficient and error-free deployment tailored to their chosen infrastructure.</p><ul><li><strong>Manifest:</strong> To help deployment tools from Microsoft and other cloud providers understand the structure of .NET Aspire projects, specialized targets within the AppHost project can be executed to generate a manifest file. This file describes the projects and services used by the app, along with the necessary deployment properties, such as environment variables.</li><li><strong>Azure:</strong> .NET Aspire projects are built to run in containerized environments. Azure Container Apps (ACA) is a fully managed, serverless platform that allows you to run microservices and containerized applications. The Azure Container Apps documentation provides guidance on deploying Aspire apps to ACA manually, using Bicep, or through the Azure Developer CLI (azd).</li><li><strong>Kubernetes:</strong> Kubernetes is a widely used container orchestration platform capable of running .NET Aspire projects. To deploy these projects to Kubernetes clusters, the .NET Aspire JSON manifest must be mapped to a Kubernetes YAML manifest file. This can be done either by using the <a href="https://prom3theu5.github.io/aspirational-manifests/getting-started.html">Aspir8</a> project or by manually creating the Kubernetes manifests.</li></ul><h3>Exploring the Code</h3><h4>Introduction</h4><p>In this section, we will explore the core functionality of this project, which automates a file-processing workflow based on background services.</p><p>The first background service is responsible for:</p><ul><li>Collecting files from a specified directory.</li><li>Calling an internal API to upload the file to Azure Blob Storage.</li><li>Sending a message to Azure Service Bus, and triggering a second background service.</li></ul><p>The second background service is responsible for:</p><ul><li>Reading the file and saving the data into MongoDB.</li><li>Sending a message to a third background service.</li></ul><p>The third background service is responsible for:</p><ul><li>Retrieving aggregated data from MongoDB.</li><li>Storing data in Postgres.</li><li>Caching the results in Redis.</li></ul><h4>AppHost Project</h4><p><em>Program.cs</em> is where we configure all of our application’s dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e15e6fe2f0df0530e38d0f7544e0133/href">https://medium.com/media/5e15e6fe2f0df0530e38d0f7544e0133/href</a></iframe><p>On line 74/75, we are defining all the dependencies for the API project and waiting for a “ready” state for our application to start.</p><blockquote>The AppHost must have the dependency reference of the API Project.</blockquote><p><strong>.NET Built-in packages:</strong></p><ul><li>Aspire.Hosting.Azure.Storage</li><li>Aspire.Hosting.MongoDB</li><li>Aspire.Hosting.PostgreSQL</li><li>Aspire.Hosting.Redis</li><li>Aspire.Hosting.SqlServer</li></ul><blockquote>Note, that we have built-in integrations and custom integrations. The ServiceBus emulator is a docker image that needs the SQL Server dependency and Config.json file to work.</blockquote><h4>API Project (Client integrations)</h4><p>The names of the built-in packages are quite similar:</p><ul><li>Aspire.Azure.Messaging.ServiceBus</li><li>Aspire.Azure.Storage.Blobs</li><li>Aspire.MongoDB.Driver</li><li>Aspire.Npgsql.EntityFrameworkCore.PostgreSQL</li><li>Aspire.StackExchange.Redis</li><li>Azure.Messaging.ServiceBus</li></ul><blockquote>Even using the ServiceBus simulator, we can use the built-in .NET Aspire package.</blockquote><blockquote>Ok, but how does my API know the dependencies set up on the AppHost?</blockquote><p><strong>ProgramExtensions.cs</strong></p><p>I chose to divide it into two separate methods:</p><ul><li>The first method registers the application dependencies</li><li>While the second method registers the service dependencies.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bb5b67c2e83f447dda903f292f1826f/href">https://medium.com/media/6bb5b67c2e83f447dda903f292f1826f/href</a></iframe><p><strong>Program.cs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0a4075329bf5aec83e8133a84aa9f70/href">https://medium.com/media/a0a4075329bf5aec83e8133a84aa9f70/href</a></iframe><p>I have a list of services that use client integrations, and it’s the same way we used it even before .NET Apire.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d117beffe6dc25741756dfd049ac1ae6/href">https://medium.com/media/d117beffe6dc25741756dfd049ac1ae6/href</a></iframe><h4>Running</h4><blockquote>The AppHost project should be the Startup project.</blockquote><p>The .NET Aspire dashboard should open and you can explore it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0nCIr1IfKTh1Ahz_z_pgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwf9_Ab9M2laevVgPkG4Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mD6KMTwsdzsG0WqbJhbEpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JntuQxAM5DZyzE5AxLdw1Q.png" /></figure><p>I hope you enjoyed this article! Check out the full implementation of this application on GitHub. Feel free to contribute to the project.</p><ul><li>GitHub: <a href="https://github.com/dianper/microservice-aspire">https://github.com/dianper/microservice-aspire</a></li><li>.NET Aspire Docs: <a href="https://learn.microsoft.com/en-us/dotnet/aspire/get-started/aspire-overview">https://learn.microsoft.com/en-us/dotnet/aspire/get-started/aspire-overview</a></li><li>Aspir8: <a href="https://prom3theu5.github.io/aspirational-manifests/getting-started.html">https://prom3theu5.github.io/aspirational-manifests/getting-started.html</a></li></ul><p>See you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8bc869baeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedding Superset Dashboards with ClickHouse Data into .NET Web Application: A Step-by-Step Guide]]></title>
            <link>https://dianper.medium.com/embedding-superset-dashboards-with-clickhouse-data-into-net-web-application-a-step-by-step-guide-dcc1bb1c104b?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcc1bb1c104b</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[superset]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 23:47:57 GMT</pubDate>
            <atom:updated>2024-04-15T16:48:35.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>Embedding Superset Dashboards with ClickHouse Data into .NET Web Application: A Step-by-Step Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6emp7jiPbCekxYqhBs271w.png" /></figure><h3>Introduction</h3><p>The main idea of this article is to show how you can embed your Superset dashboard using a ClickHouse dataset into a .NET web application. For those who don’t know Superset or ClickHouse, I’ll briefly explain what it is and the main objective of both tools.</p><h4>Superset</h4><p>Superset is an open-source data exploration and visualization platform designed to make data exploration and visualization easy for everyone, especially within business intelligence and analytics.</p><h4>ClickHouse</h4><p>ClickHouse is an open-source, column-oriented database management system designed for real-time analytics and processing of large volumes of data. ClickHouse is known for its high performance, scalability, and efficiency in handling analytical workloads.</p><h3>Requirements</h3><ul><li>.NET knowledge</li><li>Docker</li></ul><h3>Let’s start</h3><p>I prefer to start by pulling and configuring containers in Docker.</p><h4>Create network</h4><p>This is important because the Superset container needs access to the ClickHouse container.</p><pre>$ docker network create --driver bridge local-network </pre><h4>ClickHouse</h4><pre>$ docker run -d -p 8123:8123 -p 9000:9000 \<br>                -e &quot;CLICKHOUSE_USER=default&quot; \<br>                -e &quot;CLICKHOUSE_PASSWORD=admin&quot; \<br>                --network local-network \<br>                --name my-clickhouse-server \<br>                --ulimit nofile=262144:262144 clickhouse/clickhouse-server</pre><blockquote>The port 8123 is used for the HTTP interface and port 9000 is used for native ClickHouse client connections.</blockquote><p><strong>Start</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*Vl9h1ercqpl09rCtvAJ61g.png" /></figure><p><strong>Playground</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHdDwryeWvdb9kUzvxOwCw.png" /></figure><p><strong>Command-line client</strong></p><pre>$ docker exec -it my-clickhouse-server /bin/bash<br>$ clickhouse client</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*FXmieL6fLUPaJSRdK6hmMg.png" /></figure><p><strong>DBeaver</strong></p><p>You can use DBeaver or another client of your choice to test the ClickHouse connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*nI055SuN3qXdp6cx8RfTXA.png" /></figure><p><strong>Create and insert data</strong></p><p>Now that you’ve set up ClickHouse, you can use some datasets from the ClickHouse website.</p><ul><li><a href="https://clickhouse.com/docs/en/getting-started/example-datasets">https://clickhouse.com/docs/en/getting-started/example-datasets</a></li></ul><blockquote>I decided to use the Covid-19 dataset in this project.</blockquote><h4>Superset</h4><p><strong>Start</strong></p><pre>$ docker run -d -p 8088:8088 \<br>             -e &quot;SUPERSET_SECRET_KEY=$(openssl rand -base64 42)&quot; \<br>             -e &quot;TALISMAN_ENABLED=False&quot; \<br>             --network local-network \<br>             --name superset apache/superset:3.1.0</pre><p><strong>Create an account</strong></p><pre>$ docker exec -it superset superset fab create-admin \<br>              --username admin \<br>              --firstname Admin \<br>              --lastname Admin \<br>              --email admin@localhost \<br>              --password admin</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*PDXglTmD8yroVR8TJRsPMQ.png" /></figure><p><strong>Configure</strong></p><pre># upgrade db<br>$ docker exec -it superset superset db upgrade<br><br># optional<br>$ docker exec -it superset superset load_examples<br><br># initialize<br>$ docker exec -it superset superset init</pre><p><strong>Login</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glBKeXfyI2fv4XLPNzNuHg.png" /><figcaption>user: admin | pass: admin</figcaption></figure><p><strong>Connection ClickHouse to Superset</strong></p><p>To connect the ClickHouse database to Superset you must install a connector and it is necessary to modify/create a file within the Superset container.</p><pre># access the container<br>$ docker exec -it superset /bin/bash<br><br># write and create file<br>$ echo &quot;clickhouse-connect&gt;=0.6.8&quot; &gt;&gt; ./requirements/local.txt<br><br># check if it&#39;s right<br>$ cat requirements/local.txt<br><br># install the connector<br>$ pip install -r ./requirements/local.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gd2UdqLmDw-WiuWaIOG5Qg.png" /></figure><p><strong>Restart Superset</strong></p><pre>$ docker restart superset</pre><p><strong>Connect to the ClickHouse database</strong></p><p>Now you are supposed to see the ClickHouse option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*uBBdZsNPaQf3MA0jH5c26Q.png" /></figure><p>Fill in the blank fields with the necessary information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*uM7yRNCQcQracVilLsdhhg.png" /></figure><p>So, you are connected :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Htp7UkvgjwdhB8rUKZzpA.png" /></figure><p><strong>Dataset</strong></p><p>Menu &gt; Datasets &gt; + Dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFpY2OFIRxGHrx582Py4bQ.png" /></figure><p>Then, click on the “<em>Create Dataset And Create Chart”</em> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCmJEbLBDXuYeFdfW_PU8Q.png" /></figure><p>I created a World Map with the average number of new confirmed cases. You can create any chart you want.</p><p>Save it and let’s create a new dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOsPVW7lXY6Fn4S7ynvQlA.png" /></figure><p><strong>Embedding</strong></p><p>To embed our dashboard, we need to follow a few steps:</p><ul><li>Create a guest user and grant the necessary permissions</li><li>Modify the superset configuration file</li></ul><p><strong>Create guest user</strong></p><p><a href="http://localhost:8088/users/add">http://localhost:8088/users/add</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMEGQ8SYQXEy7NnM4ZgjFQ.png" /></figure><p><strong>Grant permissions</strong></p><pre># permissions<br>- can read on CssTemplate<br>- can read on Chart<br>- can read on Dataset<br>- can read on Dashboard<br>- can read on Database<br>- can read on AdvancedDataType<br>- can read on DashboardFilterStateRestApi<br>- can get embedded on Dashboard<br>- can read on EmbeddedDashboard<br>- can read on Explore<br>- can read on ExploreFormDataRestApi<br>- can read on ExplorePermalinkRestApi<br>- can dashboard on Superset<br>- can explore json on Superset<br>- can explore on Superset<br>- can slice on Superset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-corbXlBtPiHm0zt9VQvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5X-uYYDL67sloRZX6G0ozQ.png" /></figure><p><strong>Modify the Superset Configuration file</strong></p><p>We should modify some properties defined in the superset/config.py file to enable the embedding feature.</p><pre># access the container<br>$ docker exec -it superset /bin/bash<br><br># go to the superset directory<br>$ cd superset<br><br># use vim or other text editor<br>$ vi config.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*geYKoCcb0GvEWlpgUGAJwA.png" /></figure><p>Edit the following properties:</p><pre># properties<br>- ENABLE_PROXY_FIX = True<br>- ENABLE_TEMPLATE_PROCESSING = True<br>- EMBEDDED_SUPERSET = True<br>- DASHBOARD_RBAC = True<br>- ENABLE_ADVANCED_DATA_TYPES = True<br>- ENABLE_CORS = True<br>- CORS_OPTIONS = { &quot;allow_headers&quot;: [&quot;*&quot;], &quot;origins&quot;: [&quot;http://localhost:5240&quot;, &quot;http://localhost:8088&quot;], &quot;supports_credentials&quot;: True, &quot;resources&quot;: [&quot;*&quot;] }<br>- OVERRIDE_HTTP_HEADERS = { &quot;X-Frame-Options&quot;: &quot;ALLOWALL&quot; }<br>- TALISMAN_ENABLED = False<br>- SESSION_COOKIE_SAMESITE = None</pre><p>Save the file and restart the container.</p><pre># save and quit (vi command)<br>$ ESC + :wq!<br><br># exit container<br>$ exit<br><br>$ docker restart superset</pre><p>Go to the dashboard page</p><blockquote>Note that the Embed dashboard is enabled</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf2nnvDkuuzawR9AAfzZrg.png" /></figure><p>Click on the “Enable Embedding” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*N1uhxjPPsfDzQtiVBOhClA.png" /></figure><p>Copy the generated ID, we will use this ID later in the .NET app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*Z4EoO0mXuSXrPDxTUnUCuw.png" /></figure><h3>.NET Web application</h3><p>I created a simple .NET Web MVC application. If you want, you can follow this <a href="https://learn.microsoft.com/en-gb/aspnet/core/tutorials/first-mvc-app/start-mvc?view=aspnetcore-8.0&amp;tabs=visual-studio">tutorial</a> directly from the Microsoft website.</p><h4>Project Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*wxG_uqEqRHMwymG_YJTPMw.png" /></figure><h4>appsettings.json</h4><p>Paste the dashboard embedded ID on “<em>Superset.Dashboards.overview” </em>property<em>.</em></p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;,<br>  &quot;Superset&quot;: {<br>    &quot;BaseAddress&quot;: &quot;http://localhost:8088&quot;,<br>    &quot;UserAgent&quot;: &quot;EmbeddedSuperset/1.0&quot;,<br>    &quot;Dashboards&quot;: {<br>      &quot;overview&quot;: &quot;&lt;ID&gt;&quot; // CHANGE ME<br>    },<br>    &quot;Endpoints&quot;: {<br>      &quot;Login&quot;: &quot;/api/v1/security/login&quot;,<br>      &quot;CsrfToken&quot;: &quot;/api/v1/security/csrf_token/&quot;,<br>      &quot;GuestToken&quot;: &quot;/api/v1/security/guest_token/&quot;<br>    },<br>    &quot;Users&quot;: {<br>      &quot;Admin&quot;: {<br>        &quot;Username&quot;: &quot;admin&quot;,<br>        &quot;Password&quot;: &quot;admin&quot;,<br>        &quot;Provider&quot;: &quot;db&quot;,<br>        &quot;Refresh&quot;: true<br>      },<br>      &quot;Guest&quot;: {<br>        &quot;FirstName&quot;: &quot;Guest&quot;,<br>        &quot;LastName&quot;: &quot;User&quot;,<br>        &quot;Username&quot;: &quot;guest&quot;<br>      }<br>    }<br>  }<br>}</pre><h4>Configuration</h4><pre>namespace Presentation.Configuration<br>{<br>    public sealed record SupersetConfiguration<br>    {<br>        public const string SectionName = &quot;Superset&quot;;<br>        public string BaseAddress { get; set; }<br>        public string UserAgent { get; set; }<br>        public IDictionary&lt;string, string&gt; Dashboards { get; set; }<br>        public EndpointConfiguration Endpoints { get; set; }<br>        public UserConfiguration Users { get; set; }<br>    }<br><br>    public sealed record EndpointConfiguration<br>    {<br>        public string Login { get; set; }<br>        public string CsrfToken { get; set; }<br>        public string GuestToken { get; set; }<br>    }<br><br>    public sealed record UserConfiguration<br>    {<br>        public AdminConfiguration Admin { get; set; }<br>        public GuestConfiguration Guest { get; set; }<br>    }<br><br>    public sealed record AdminConfiguration<br>    {<br>        public string Username { get; set; }<br>        public string Password { get; set; }<br>        public string Provider { get; set; }<br>        public bool Refresh { get; set; }<br>    }<br><br>    public sealed record GuestConfiguration<br>    {<br>        public string FirstName { get; set; }<br>        public string LastName { get; set; }<br>        public string Username { get; set; }<br>    }<br>}</pre><h4>Services</h4><p>This class is responsible for communication with the Superset API.</p><blockquote>Superset API documentation: <a href="http://localhost:8088/swagger/v1">http://localhost:8088/swagger/v1</a></blockquote><pre>namespace Presentation.Services<br>{<br>    using Microsoft.Extensions.Options;<br>    using Microsoft.Net.Http.Headers;<br>    using Presentation.Configuration;<br>    using System.Net.Http.Headers;<br>    using System.Text;<br>    using System.Text.Json;<br><br>    public class SupersetService<br>    {<br>        private readonly HttpClient client;<br>        private readonly SupersetConfiguration supersetConfiguration;<br><br>        public SupersetService(<br>          HttpClient client, <br>          IOptions&lt;SupersetConfiguration&gt; supersetConfiguration)<br>        {<br>            this.supersetConfiguration = supersetConfiguration.Value;<br><br>            this.client = client;<br>            this.client.BaseAddress = new Uri(this.supersetConfiguration.BaseAddress);<br>            this.client.DefaultRequestHeaders.Add(HeaderNames.Accept, &quot;application/json&quot;);<br>            this.client.DefaultRequestHeaders.Add(HeaderNames.UserAgent, this.supersetConfiguration.UserAgent);<br>        }<br><br>        public async Task&lt;LoginResult&gt; LoginAsync()<br>        {<br>            var loginRequest = new<br>            {<br>                username = this.supersetConfiguration.Users.Admin.Username,<br>                password = this.supersetConfiguration.Users.Admin.Password,<br>                provider = this.supersetConfiguration.Users.Admin.Provider,<br>                refresh = this.supersetConfiguration.Users.Admin.Refresh<br>            };<br><br>            var response = await this.client.PostAsync(<br>                requestUri: this.supersetConfiguration.Endpoints.Login,<br>                content: new StringContent(<br>                    content: JsonSerializer.Serialize(loginRequest),<br>                    encoding: Encoding.UTF8,<br>                    mediaType: &quot;application/json&quot;));<br><br>            response.EnsureSuccessStatusCode();<br><br>            var content = await response.Content.ReadAsStringAsync();<br><br>            return JsonSerializer.Deserialize&lt;LoginResult&gt;(content);<br>        }<br><br>        public async Task&lt;CsrfTokenResult&gt; GetCsrfTokenAsync(string accessToken)<br>        {<br>            var httpRequest = new HttpRequestMessage(HttpMethod.Get, this.supersetConfiguration.Endpoints.CsrfToken);<br><br>            httpRequest.Headers.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, accessToken);<br><br>            this.client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, accessToken);<br><br>            var response = await this.client.SendAsync(httpRequest);<br><br>            response.EnsureSuccessStatusCode();<br><br>            var content = await response.Content.ReadAsStringAsync();<br><br>            return JsonSerializer.Deserialize&lt;CsrfTokenResult&gt;(content);<br>        }<br><br>        public async Task&lt;GuestTokenResult&gt; CreateGuestTokenAsync(string csrfToken)<br>        {<br>            var referer = $&quot;{this.supersetConfiguration.BaseAddress}{this.supersetConfiguration.Endpoints.CsrfToken}&quot;;<br><br>            this.client.DefaultRequestHeaders.Add(HeaderNames.Referer, referer);<br>            this.client.DefaultRequestHeaders.Add(&quot;X-CSRFToken&quot;, csrfToken);<br><br>            var guestTokenRequest = new<br>            {<br>                resources = this.supersetConfiguration.Dashboards.Select(x =&gt; new { id = x.Value, type = &quot;dashboard&quot; }),<br>                rls = Array.Empty&lt;object&gt;(),<br>                user = new<br>                {<br>                    first_name = this.supersetConfiguration.Users.Guest.FirstName,<br>                    last_name = this.supersetConfiguration.Users.Guest.LastName,<br>                    username = this.supersetConfiguration.Users.Guest.Username<br>                }<br>            };<br><br>            var response = await this.client.PostAsync(<br>                requestUri: this.supersetConfiguration.Endpoints.GuestToken,<br>                content: new StringContent(<br>                    content: JsonSerializer.Serialize(guestTokenRequest),<br>                    encoding: Encoding.UTF8,<br>                    mediaType: &quot;application/json&quot;));<br><br>            response.EnsureSuccessStatusCode();<br><br>            var content = await response.Content.ReadAsStringAsync();<br><br>            return JsonSerializer.Deserialize&lt;GuestTokenResult&gt;(content);<br>        }<br>    }<br><br>    public record LoginResult(string access_token, string refresh_token);<br><br>    public record CsrfTokenResult(string result);<br><br>    public record GuestTokenResult(string token);<br>}</pre><h4><strong>Controllers</strong></h4><p>This controller has only one method, which is responsible for returning all the information necessary to the frontend to render the dashboard.</p><pre>namespace Presentation.Controllers<br>{<br>    using Microsoft.AspNetCore.Mvc;<br>    using Microsoft.Extensions.Options;<br>    using Presentation.Configuration;<br>    using Presentation.Services;<br>    using System.Net;<br>    using System.Text.Json.Serialization;<br><br>    [ApiController]<br>    [Route(&quot;api/[controller]&quot;)]<br>    public class SupersetController : ControllerBase<br>    {<br>        private readonly SupersetService service;<br>        private readonly SupersetConfiguration supersetConfiguration;<br>        private readonly ILogger&lt;SupersetController&gt; logger;<br><br>        public SupersetController(<br>            SupersetService service,<br>            IOptions&lt;SupersetConfiguration&gt; supersetConfiguration,<br>            ILogger&lt;SupersetController&gt; logger)<br>        {<br>            this.service = service;<br>            this.supersetConfiguration = supersetConfiguration.Value;<br>            this.logger = logger;<br>        }<br><br>        [HttpGet]<br>        public async Task&lt;IActionResult&gt; GetAsync()<br>        {<br>            try<br>            {<br>                var loginResult = await this.service.LoginAsync();<br>                var csrfTokenResult = await this.service.GetCsrfTokenAsync(loginResult.access_token);<br>                var guestTokenResult = await this.service.CreateGuestTokenAsync(csrfTokenResult.result);<br><br>                var response = new SupersetResult<br>                {<br>                    GuestToken = guestTokenResult.token,<br>                    Dashboards = this.supersetConfiguration.Dashboards,<br>                    SupersetDomain = this.supersetConfiguration.BaseAddress,<br>                    Status = HttpStatusCode.OK<br>                };<br><br>                return Ok(response);<br>            }<br>            catch (Exception ex)<br>            {<br>                this.logger.LogError(ex, ex.Message);<br><br>                return StatusCode((int)HttpStatusCode.InternalServerError, new { status = HttpStatusCode.InternalServerError, message = ex.Message });<br>            }<br>        }<br>    }<br><br>    public class SupersetResult<br>    {<br>        [JsonPropertyName(&quot;status&quot;)]<br>        public HttpStatusCode Status { get; set; }<br><br>        [JsonPropertyName(&quot;domain&quot;)]<br>        public string SupersetDomain { get; set; }<br><br>        [JsonPropertyName(&quot;token&quot;)]<br>        public string GuestToken { get; set; }<br><br>        [JsonPropertyName(&quot;dashboards&quot;)]<br>        public IDictionary&lt;string, string&gt; Dashboards { get; set; }<br>    }<br>}</pre><h4>Program.cs</h4><pre>...<br><br>builder.Services.Configure&lt;SupersetConfiguration&gt;(builder.Configuration.GetSection(SupersetConfiguration.SectionName));<br>builder.Services.AddHttpClient&lt;SupersetService&gt;();<br><br>...</pre><h4>View</h4><p>Edit your <em>Views/Home/Index.cshtml</em> file to start using the Superset SDK.</p><ul><li>Source: <a href="https://unpkg.com/superset-embedded-sdk">https://unpkg.com/superset-embedded-sdk</a></li><li>Add a new div to render the superset dashboard (<em>my-superset-container</em>)</li><li>Add scripts section</li><li>Add a style</li></ul><pre>@{<br>  ViewData[&quot;Title&quot;] = &quot;Home Page&quot;;<br>}<br><br>&lt;div class=&quot;text-center&quot;&gt;<br>  &lt;h1 class=&quot;display-4&quot;&gt;Welcome to Superset Embedded Dashboard&lt;/h1&gt;<br>  &lt;p&gt;Learn about &lt;a href=&quot;https://docs.microsoft.com/aspnet/core&quot;&gt;building Web apps with ASP.NET Core&lt;/a&gt;.&lt;/p&gt;<br>  &lt;div id=&quot;my-superset-container&quot;&gt;&lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;style&gt;<br>  iframe {<br>    width: 100%;<br>    height: 700px;<br>    border: 0;<br>    overflow: hidden;<br>  }<br>&lt;/style&gt;<br><br>@section Scripts {<br>    &lt;script src=&quot;https://unpkg.com/superset-embedded-sdk&quot;&gt;&lt;/script&gt;<br>    &lt;script&gt;<br>        $(document).ready(async function () {<br>          const supersetResult = await fetchSupersetData();<br>          supersetEmbeddedSdk.embedDashboard({<br>            id: supersetResult.dashboards.overview,<br>            supersetDomain: supersetResult.domain,<br>            mountPoint: document.getElementById(&quot;my-superset-container&quot;),<br>            fetchGuestToken: () =&gt; supersetResult.token,<br>            dashboardUiConfig: {<br>              hideTitle: true,<br>              filters: {<br>                  visible: false,<br>                  expanded: false,<br>              }<br>            }<br>          });<br>        });<br>        async function fetchSupersetData() {<br>          // Call the SupersetController<br>          const response = await fetch(&quot;/api/superset&quot;, { method: &quot;GET&quot; });<br>          const supersetResult = await response.json();<br>          return supersetResult;<br>        }<br>    &lt;/script&gt;<br>}</pre><h4>Running :)</h4><p>Well done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4znkpKP4Z9BAc5lCUXCYeQ.png" /></figure><h3>References</h3><ul><li><a href="https://clickhouse.com/docs/en/getting-started/example-datasets">https://clickhouse.com/docs/en/getting-started/example-datasets</a></li><li><a href="https://clickhouse.com/docs/en/integrations/superset">https://clickhouse.com/docs/en/integrations/superset</a></li><li><a href="https://clickhouse.com/docs/en/getting-started/example-datasets/covid19">https://clickhouse.com/docs/en/getting-started/example-datasets/covid19</a></li><li><a href="https://superset.apache.org/docs/databases/clickhouse">https://superset.apache.org/docs/databases/clickhouse</a></li><li><a href="https://superset.apache.org/docs/creating-charts-dashboards/creating-your-first-dashboard">https://superset.apache.org/docs/creating-charts-dashboards/creating-your-first-dashboard</a></li><li><a href="https://superset.apache.org/docs/api/">https://superset.apache.org/docs/api/</a></li></ul><p>Thanks for taking the time to read this article! I hope you have enjoyed it :)</p><p>See you, bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcc1bb1c104b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing GraphQL API Gateway in .NET 6 + Hot Chocolate v12 + Redis]]></title>
            <link>https://dianper.medium.com/implementing-graphql-api-gateway-in-net-6-hot-chocolate-v12-redis-1a0ac12f340c?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a0ac12f340c</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 13:29:25 GMT</pubDate>
            <atom:updated>2022-10-20T07:55:27.317Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing GraphQL API Gateway in .NET 6 + Hot Chocolate v12 + Redis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seebcF8ZDE2nwL9JZ7rr5g.png" /></figure><h4>Introduction</h4><p>Another one from the GraphQL series and in this one we are going to implement a GraphQL API Gateway following the Federated Schema approach.</p><blockquote>If you are new to the world of GraphQL, you can check out my <a href="https://dianper.medium.com/building-graphql-api-in-net-core-hotchocolate-mongodb-docker-part-1-d00a20eb0ff0">previous articles</a> where I explain and implement the basics of GraphQL using .NET Core 3.1, Hot Chocolate v11, MongoDB and Docker.</blockquote><h4>Requirements</h4><ul><li><a href="https://docs.docker.com/desktop/install/windows-install/">Docker</a></li><li><a href="https://visualstudio.microsoft.com/downloads/">Visual Studio</a></li></ul><h4>Before we start</h4><p>Let’s take a look at the two common approaches we have for distributed schema.</p><h4><strong>1. Schema Stitching</strong></h4><p>In the scenario of schema stitching, the configuration of the gateway schema is on the gateway itself. The gateway pulls the schema from the domain services and can be extended with SDL.</p><h4><strong>2. Federated Schema</strong></h4><p>In the federated approach, the schema are defined on the domain service. The domain services push the schema on a cache (like <em>Redis</em>). The gateway is subscribed to changes from this cache and can hot reload the schema if the configuration of a domain service changes. See more details <a href="https://chillicream.com/docs/hotchocolate/distributed-schema">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*oJvabtcudXXHcM0v06BFlQ.png" /></figure><h4>Let’s start</h4><p>You can start developing from the Gateway or from the Domain Service, the advantage of starting with the Domain Service is that you can already see the result, that is, you can test the API and see if everything is as expected.</p><p>For these projects <em>Redis</em> is crucial, because the Domain Services are responsible for publishing their schema on <em>Redis</em> and the Gateway is responsible for getting the schemas that have been published and stitching them, exposing the complete graph in a single endpoint.</p><h4>Packages</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd09c6f3ea969cb8ba9c4e14a010fb5b/href">https://medium.com/media/bd09c6f3ea969cb8ba9c4e14a010fb5b/href</a></iframe><h4>Domain Service A</h4><p>The <strong>Catalog API</strong> is responsible for exposing the queries to list the products and brands and also publishing the schema to <em>Redis</em>.</p><h4><strong>Schema</strong></h4><p>We are using <strong>Code-first</strong> for this project, so the schema is automatically generated by Hot Chocolate when running the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a581536b02ab7fdc4cbfeaeae91469a2/href">https://medium.com/media/a581536b02ab7fdc4cbfeaeae91469a2/href</a></iframe><h4><strong>Program</strong></h4><p><em>CustomPublishSchemaDefinition</em> is a custom extension I created to publish the schema to <em>Redis</em> via a toggle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23c65c7c46c235384b1b7a07911300a0/href">https://medium.com/media/23c65c7c46c235384b1b7a07911300a0/href</a></iframe><h4><strong>Appsettings</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aad3dfbcd15b56c81f3f04898aa4140a/href">https://medium.com/media/aad3dfbcd15b56c81f3f04898aa4140a/href</a></iframe><h4><strong>Extensions</strong></h4><p>The toggle <em>Stitching.Enabled</em> can be turned off in the dev environment if you need to run without <em>Redis </em>dependency, however for this work as expected it needs to be true in the production environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de8f717337799d1b5a3271b63b562d0b/href">https://medium.com/media/de8f717337799d1b5a3271b63b562d0b/href</a></iframe><h4><strong>Queries</strong></h4><p>If you want to organize your queries into different files <em>(e.g by domain)</em> you can use an <em>ExtendedTypeObject</em> annotation like I used to create <em>QueryBrand</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/646b8f429830ccd068284401b4ee8d0e/href">https://medium.com/media/646b8f429830ccd068284401b4ee8d0e/href</a></iframe><h4>Domain Service B</h4><p>The <strong>Bag API</strong> is responsible for exposing queries to get the bag details and also exposing the mutation to add a new item to the bag.</p><h4><strong>Schema</strong></h4><p><em>AddToBagInput</em> and <em>AddToBagPayload </em>are automatically generated by Hot Chocolate because we’re enabling mutation conventions in the Program class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91ecc59b6b0c7121ae6179bb096741e7/href">https://medium.com/media/91ecc59b6b0c7121ae6179bb096741e7/href</a></iframe><blockquote>Note that we have a type with the same name (Product) in the Catalog and Bag APIs, but with different properties, by default Hot Chocolate adds a prefix with the schema name (e.g <strong>catalog_Product</strong>). We have to be careful because in some cases this may not work as expected, and a domain service may use an exposed type of another domain, causing confusion for the client who is going to consume the GraphQL API.</blockquote><h4><strong>Program</strong></h4><p>Similar to the Catalog API project, but we’re adding mutation types and conventions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2030ea0319b02aca10671f5bc1e4eb29/href">https://medium.com/media/2030ea0319b02aca10671f5bc1e4eb29/href</a></iframe><h4><strong>Appsettings</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60b8853888ea4ad92318bb861ec97bcc/href">https://medium.com/media/60b8853888ea4ad92318bb861ec97bcc/href</a></iframe><h4><strong>Queries</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c8d2706d806e58b27e2d82017c2e9dc/href">https://medium.com/media/4c8d2706d806e58b27e2d82017c2e9dc/href</a></iframe><h4><strong>Mutations</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a461f6edfad174d9d7eca37fbe9bdc01/href">https://medium.com/media/a461f6edfad174d9d7eca37fbe9bdc01/href</a></iframe><h4>🏆 Gateway API</h4><p>The Gateway API is responsible for handling stitching, merges and all the other configurations that involve all the domain services, so the Gateway gets the schemas from <em>Redis</em> and exposes the whole graph in a single endpoint.</p><h4><strong>Schema (stitched)</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58bdcca57933f9b00b9af4053851dd68/href">https://medium.com/media/58bdcca57933f9b00b9af4053851dd68/href</a></iframe><h4><strong>Appsettings</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2c74c2f03e9b989b3b03bd12da9e30f/href">https://medium.com/media/c2c74c2f03e9b989b3b03bd12da9e30f/href</a></iframe><h4><strong>Program</strong></h4><p>In order for the Gateway API to communicate with the domain services, it is necessary to register an <em>HttpClient</em> <em>(</em><strong><em>AddGraphQLServices</em></strong><em> extensions)</em> for each one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b90536dc249e92b06d831694aba36a91/href">https://medium.com/media/b90536dc249e92b06d831694aba36a91/href</a></iframe><blockquote>Note that I had to rename the Product type from the Catalog API because the automatic merge done by Hot Chocolate did not work as expected and the queries started to use the Product type defined in the Bag API.</blockquote><h4><strong>Extensions</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b402f32495c65b0f8dfdb40b6542c372/href">https://medium.com/media/b402f32495c65b0f8dfdb40b6542c372/href</a></iframe><h4>🙌 References</h4><ul><li><a href="https://github.com/dianper/graphql-api-gateway">Github Project</a></li><li><a href="https://chillicream.com/docs/hotchocolate">Hot Chocolate Docs</a></li></ul><p>👍 Thanks for reading it and I really hope it helps you in your GraphQL API Gateway development.</p><p>See you in the next article. 👌</p><p>Bye</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a0ac12f340c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building GraphQL API in .NET Core + HotChocolate + MongoDB + Docker [Part 2]]]></title>
            <link>https://dianper.medium.com/building-graphql-api-in-net-core-hotchocolate-mongodb-docker-part-2-ebfb7e7fe3e9?source=rss-8f7c73a93c7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebfb7e7fe3e9</guid>
            <category><![CDATA[hot-chocolate]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Diego Pereira]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 23:37:39 GMT</pubDate>
            <atom:updated>2021-04-06T12:40:19.435Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://dianper.medium.com/building-graphql-api-in-net-core-hotchocolate-mongodb-docker-part-1-d00a20eb0ff0?source=your_stories_page-------------------------------------">Building GraphQL API in .NET Core + HotChocolate + MongoDB + Docker [Part 2]</a></h3><p>If it is your first time here, this is the second part of this article. So, I advise you to read the <a href="https://dianper.medium.com/building-graphql-api-in-net-core-hotchocolate-mongodb-docker-part-1-d00a20eb0ff0">first part</a> before we start. In this session, as I promised, we’ll cover <strong>Mutation</strong> and <strong>Subscription</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*7cnwBBgrZXKtIDjIncSwEQ.png" /></figure><h4>What are GraphQL Mutation and Subscription?</h4><p>Basically, mutations are used to change data in your server, such as the Insert, Update and Delete operations. Subscriptions are used to send data to its clients when a certain event occurs on the server-side.</p><h4>Refactoring the first part</h4><p>To avoid repetitive code, I did a little refactoring in our repository and changed it to generic.</p><h4>1. Core.Entities</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14a209a34c409eca02225150f9f6adae/href">https://medium.com/media/14a209a34c409eca02225150f9f6adae/href</a></iframe><h4>2. Core.Repositories</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec4ae16c041d928674b1b3916b9d8d4d/href">https://medium.com/media/ec4ae16c041d928674b1b3916b9d8d4d/href</a></iframe><h4>3. Infrastructure.Data</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d55ded366e87a7bd58726f9644dc39d/href">https://medium.com/media/0d55ded366e87a7bd58726f9644dc39d/href</a></iframe><h4>4. Infrastructure.Repositories</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3673166bf32061e099a3aba17a9231a9/href">https://medium.com/media/3673166bf32061e099a3aba17a9231a9/href</a></iframe><blockquote>Great job! Now we have refactored our repository!</blockquote><h4>Mutations</h4><p>Add a new folder in <strong>GraphQL.API</strong> project called <strong>Mutations</strong> and add a new class called <strong>ProductMutation</strong>, this class will have 2 methods.</p><ol><li><em>CreateProductAsync</em></li><li><em>RemoveProductAsync</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a898e750d0032a85b45dbd947be8ebb0/href">https://medium.com/media/a898e750d0032a85b45dbd947be8ebb0/href</a></iframe><h4>Here we have 2 different approaches:</h4><ol><li><em>Create a single class to handle all mutations of different models.</em></li><li><em>Split into different classes, where each class has the responsibility to handle with only one model.</em></li></ol><h4>What is the difference between 1 or 2?</h4><p>Basically, in the first option, we can name the class as <strong>Mutation</strong> instead of <strong>ProductMutation</strong>. In the second option, we use the <strong>ExtendObjectType</strong> attribute so GraphQL understands that this class is a mutation. We will go with option 2!</p><blockquote>In the <strong>Startup</strong> class is where the magic happens.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f71004bbdc936af8daec9970f5e7422c/href">https://medium.com/media/f71004bbdc936af8daec9970f5e7422c/href</a></iframe><blockquote>Note that I split the queries into two different classes.</blockquote><h4><strong>Great, let’s see how it works in practice!</strong></h4><ol><li><em>Run the query to get the CategoryId from the product list.</em></li><li><em>Run the mutation to create a new product.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLbgyGN0omGu4QngUaTe3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xszDBahoAbl4JxdA4pjS2A.png" /></figure><h4>Subscriptions</h4><p>Add a new folder in <strong>GraphQL.API</strong> project called <strong>Subscriptions</strong> and also add a new class called <strong>ProductSubscriptions</strong>, this class will have 2 methods.</p><ol><li><em>OnCreateAsync</em></li><li><em>OnRemoveAsync</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adfc7ee890948c077dc4bb9faf20642e/href">https://medium.com/media/adfc7ee890948c077dc4bb9faf20642e/href</a></iframe><blockquote>This is a simple example, an event is dispatched when a product is created or removed. A new product is returned on OnCreateAsync, and a productId is sent on OnRemoveAsync.</blockquote><p>Now we need to update the mutations so that the events can be triggered.</p><pre>// topic = OnCreateAsync / OnRemoveAsync<br>// message = product: Product / productId: string</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df4df434ad6c0861a81e011b0be0f785/href">https://medium.com/media/df4df434ad6c0861a81e011b0be0f785/href</a></iframe><p>Okay, now we have created the subscriptions, however, we also need to register them in the <strong>Startup</strong> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7673ed1a0d47e990fcf68166960423c/href">https://medium.com/media/e7673ed1a0d47e990fcf68166960423c/href</a></iframe><blockquote>By default, subscriptions work over WebSocket, so we need to configure our pipeline to use them.</blockquote><p><strong>Well done! Now we have everything set up! Let’s take it step-by-step.</strong></p><ol><li><em>In the first tab on Banana Cake Pop, run the subscription, nothing will happen at this point.</em></li><li><em>Open a new tab and run the mutation.</em></li><li><em>Return to the first tab and see that the event has been triggered.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3r9ftwmjBxuE8c6eHiRGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VeAeyxXZV0gsIeopt2yGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shKE5Ac_oarPH3QxJz86PA.png" /></figure><blockquote>If you had the same result, congratulations!</blockquote><h4>Updating our image on Docker</h4><ol><li>Stop and remove the old container</li><li>docker-compose build</li><li>docker-compose up</li></ol><pre>docker ps -a<br>docker stop &lt;CONTAINERID&gt;<br>docker rm &lt;CONTAINERID&gt;</pre><pre>docker-compose build<br>docker-compose -f docker-componse.yml -f docker-compose.override.yml up -d</pre><ul><li><em>container endpoint: https://localhost:9006/api/graphql</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcyPlbpUH7DlW14ZZMU1ww.png" /></figure><h4>References</h4><ol><li><a href="https://dianper.medium.com/building-graphql-api-in-net-core-hotchocolate-mongodb-docker-part-1-d00a20eb0ff0">First part</a></li><li><a href="https://github.com/ChilliCream/graphql-workshop/blob/master/docs/7-subscriptions.md">GraphQL Mutations and Subscriptions</a></li><li><a href="https://github.com/dianper/graphql-netcore">Final code</a></li></ol><p>Thank you for reading it! I really hope you have enjoyed it.</p><p>See you in the next article.</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebfb7e7fe3e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>