今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

标签:#dotnet

找到 51 篇相关文章

AI 资讯

Build a Local RAG Chatbot in 30 Minutes with .NET 8, Ollama, and React

I uploaded a 40-page PDF of an internal API spec, asked "what's the rate limit for the search endpoint?", and got back: "100 requests per minute per API key, with bursts up to 200. See section 4.2 of the document." With citations. In about three seconds. The whole stack runs on my laptop. It cost me $0 in LLM credits during development because Ollama is free and local, and the embedder I used is also free and local. The repo is here — issues and PRs welcome. This is the build log. Not a tutorial where every step works the first time — a build log where I tell you which decisions held up and which ones I redid. The problem most "chat with your PDF" demos have Every "chat with your PDF" tutorial I read in early 2025 had the same shape: open OpenAI, paste your API key, call gpt-4 with a 50-page PDF stuffed into the context window, get an answer, pay $0.03 per question, repeat. That works for a demo. It does not work for a tool you'd actually use at work, because: The PDF might contain customer data, internal pricing, or unreleased features. You do not want that going to OpenAI's training pipeline or anyone's logs. The cost adds up. If your team uses it 50 times a day, that's $45/month per seat. The model hallucinates on long PDFs anyway. Stuff 100 pages into a 128k context window and the model starts forgetting the middle. The fix is RAG (Retrieval-Augmented Generation) — don't send the whole PDF, send only the 3-5 chunks that are actually relevant to the question. The rest of the work is the same: embed the chunks, embed the question, find the closest matches, send those to the LLM with the question. But the cost and the privacy story both improve by 100x. The actual ask: Upload a PDF. Ask questions. Get answers from the document with citations, in under 5 seconds, with no data leaving my laptop and no monthly bill. The architecture One .NET 8 solution, one React app, one Ollama process, zero cloud dependencies. [ PDF Upload ] | v +-------------------+ chunks +-------

2026-06-22 原文 →
AI 资讯

From Stack Trace to Suggested Fix in 4 Seconds: Building a Self-Healing .NET API Gateway.

Last Tuesday my API gateway caught a NullReferenceException , streamed it to a dashboard in real-time, and pushed a draft code fix to the browser tab of the on-call engineer — before I finished reading the error myself. That sentence used to be vendor marketing. Now it's just my Program.cs . This is the architecture post-mortem. I built it on weekends. It runs in Docker. It cost me exactly $0 in LLM credits during development because Groq's free tier is generous and Ollama works as a swap-in. The repo is here — issues and PRs welcome. The problem most .NET teams have Production errors are caught, logged to a file, and forgotten. Engineers find out from a Slack ping twenty minutes later, if at all. By the time someone looks, the original request context is gone, the user's session has expired, and the stack trace is buried four layers deep in System.* calls. "Self-healing" is a word vendors use to mean "auto-restart the pod." I wanted something better. The actual ask: When an exception is thrown in service A, give the engineer (a) a clear root cause, (b) a suggested fix, and (c) a draft code patch — in under 30 seconds. Not a magic black box. Not an auto-applied patch. Just: catch the error, give the model the right context, push the analysis to a human in real-time, and let the human close the loop. The architecture One .NET solution, four projects, four NuGet packages, no new infrastructure beyond what you probably already have. [ HTTP request ] | v +-------------------+ enqueue +---------------------+ | SmartLogAnalyzer. | ---------------------> | Hangfire (Redis) | | Api | +----------+----------+ | (ErrorHandling | | | Middleware) | v +-------------------+ +---------------------+ | SmartLogAnalyzer. | | Worker | | (ErrorProcessingWorker) +-----+-------+-------+ | | AI call | | persist v v +-----------+ +-----------+ | Semantic | | MSSQL | | Kernel + | | (ErrorLog | | Groq LLM | | table) | +-----+-----+ +-----------+ | v +---------------------+ | SignalR Hub | | (

2026-06-22 原文 →
AI 资讯

HelmSharp: render Helm charts from .NET without shelling out to helm

TL;DR: I built a .NET library that renders Helm charts and drives Kubernetes releases without shelling out to the helm CLI. 129/129 templates across ingress-nginx, cert-manager, external-dns, podinfo, and metrics-server now render successfully. The main entry point is HelmSharp.Action, with lower-level packages available for chart loading, rendering, Kubernetes operations, and release storage. MIT licensed, looking for feedback and early adopters. Why I Built This At work, our .NET services deploy to Kubernetes through Helm. Every Docker image had to bundle the helm binary — another dependency to manage, another layer in the image, another surface for CVEs. I wanted to cut that out entirely and do Helm-style rendering directly in-process. The .NET ecosystem doesn't really have this. There are YAML libraries. There are Kubernetes client libraries. There are template engines. But nothing ties them together the way helm template does — values merging, named templates, include , range , toYaml , the whole Sprig function set, all wired into a single render pipeline. So I started building one. (This is also my first real open source project — I'd spent years consuming OSS without contributing back, and HelmSharp is what came out of deciding to change that.) What HelmSharp Does HelmSharp is a multi-package .NET SDK (net8.0 / net9.0 / net10.0) that covers: Package What it does HelmSharp.Action High-level Helm client — TemplateAsync , UpgradeInstallAsync , RollbackAsync HelmSharp.Chart Chart loading from directories and .tgz , values merging, --set / --set-json style overrides HelmSharp.Engine Helm-style template rendering — 100+ Sprig/Helm functions HelmSharp.Kube Kubernetes apply, delete, and wait (no kubectl needed) HelmSharp.Release Release history stored in Kubernetes Secrets (Helm-compatible) HelmSharp.Repo Chart repository index, pull, and search Plus Registry , Storage , PostRenderer extension points Here's the lower-level rendering API — no result objects, no stdout

2026-06-22 原文 →
AI 资讯

Meet AppPipe: The Lightweight, On-Premises Alternative to .NET Aspire

Modern cloud-native developer environments are fantastic. Frameworks like .NET Aspire have revolutionized local development by providing a unified developer dashboard, automatic service discovery, and OTLP telemetry collection. But what happens when it's time to deploy your microservice topology on-premises? If your target is IIS on Windows Server or a systemd service on Linux , you've likely realized that deploying the standard .NET Aspire stack on-prem is a complex puzzle. There is no native hosting model for IIS, gRPC telemetry port mapping is fragile, and the dashboard's constant WebSocket connections can consume excessive resources on on-premises virtual machines. Enter AppPipe.Hosting —a lightweight, developer-friendly NuGet package designed specifically to bring the best features of .NET Aspire to your on-premises environments. The Problem: On-Premises Microservice Orchestration is Hard While cloud platforms have native orchestration (like Kubernetes or ECS), traditional Windows and Linux environments still host a massive volume of enterprise applications. When running microservices on IIS or Linux servers, developers face three major friction points: Port Conflicts & Service Discovery : Dynamically assigning ports to multiple microservices in IIS or systemd and injecting them into dependent services is tedious. Telemetry Aggregation : Running an OpenTelemetry Collector just to aggregate traces, logs, and metrics for a small on-prem cluster is heavy and complex to configure. Resource Exhaustion : Standard Blazor Interactive Server dashboards maintain constant WebSockets and high memory usage, which quickly drains limited hosting environments. The Solution: AppPipe AppPipe is a lightweight alternative that integrates a routing gateway, an in-memory telemetry store, and a visual dashboard directly into a single library. graph TD Client(Browser/Client) -->|HTTP| Gateway subgraph User's Application Space Backend1[Backend Microservice A] Backend2[Backend Microserv

2026-06-22 原文 →
AI 资讯

Already using LaunchDarkly or Flagsmith? Here's how to try FtrIO on a single flag

Thinking about trying FtrIO? The new CLI makes it easy to start with just one feature flag If you've been curious about FtrIO (the .NET feature toggle library that replaces if (featureFlags.IsEnabled(...)) with a [Toggle] attribute woven directly into your compiled IL) but weren't sure where to start, the experimental release of FtrIO.onetwo just made that first step a lot smaller. You don't need to commit to a full migration. You don't need to rip out your existing flag library. You just need one method and 20 minutes. What FtrIO.onetwo does FtrIO.onetwo is a .NET CLI audit tool. Its default mode scans your source tree, finds every FtrIO toggle reference, and tells you exactly what's live right now: dotnet tool install --global FtrIO.onetwo --version 1.1.1-experimental ftrio.onetwo --source C: \P rojects \M yApp But in this experimental release it does two new things: ftrio.onetwo import : pulls your current flag state from LaunchDarkly, Flagsmith, flagd, environment variables, or an HTTP endpoint directly into appsettings.json . Your existing flag library keeps working unchanged. ftrio.onetwo migrate : scans your .cs files for LaunchDarkly or Flagsmith SDK call patterns using Roslyn, cross-references them against your live flag state, and generates a report showing exactly what each flag would look like in FtrIO and how to migrate it. The "try it on one flag" workflow The migrate report categorises every flag it finds: ✅ Ready to migrate : boolean flag, no targeting rules, straightforward [Toggle] replacement ⚠️ Needs review : targeting rules, number flags, needs a decision ❌ Cannot migrate : JSON flags, recommend moving to IConfiguration For every ready flag it shows the suggested refactor. Something like: new - checkout - flow → NewCheckoutFlow File : Services \ OrderService . cs : 42 Current code : if ( client . BoolVariation ( "new-checkout-flow" , user , false )) { ValidateCart (); ApplyDiscounts (); ProcessPayment (); } Suggested action : Extract the if bloc

2026-06-22 原文 →
AI 资讯

This week in Cursor + .NET — 7 rules (week ending June 21, 2026)

Every weekday a single, opinionated rule for senior C#/.NET engineers using Cursor. Here's the full week in one read — canonical posts live on the Agentic Architect blog . 7 daily senior rules Rule 14: Sealed By Default Sun 21 Jun Mark every class sealed unless inheritance is explicitly planned. Stops Cursor inventing accidental inheritance hierarchies "for flexibility." Small but measurable virtual-call perf wins too. → Permalink on the blog Rule 13: Strongly-Typed IDs Sat 20 Jun OrderId as record struct OrderId(Guid Value) beats raw Guid everywhere. Stops the AI passing a CustomerId where an OrderId was expected — a bug the compiler can't catch with primitive obsession but catches instantly with domain primitives. → Permalink on the blog Rule 12: IOptionsSnapshot Over Raw Config Fri 19 Jun Business code should never call IConfiguration directly. Strongly-typed IOptions or IOptionsSnapshot bindings only. The AI loves to "just grab the config value" — refuse it and force a settings class with validation attributes. → Permalink on the blog Rule 11: Rethrow, Don't throw ex Thu 18 Jun throw ex resets the stack trace. throw preserves it. Cursor gets this wrong about 40 percent of the time when generating catch blocks. Rewrite any naked throw ex to throw unless the exception has been explicitly wrapped. → Permalink on the blog Rule 10: AsNoTracking for Reads Wed 17 Jun Every read-only EF Core query should call AsNoTracking. Add a rule that recognises query methods returning DTOs (not entities) and inserts the call. Cursor never does this by default and your read perf degrades silently across releases. → Permalink on the blog Rule 9: Scoped Capture in Singleton Tue 16 Jun The single most expensive .NET runtime bug: a Singleton holding a Scoped service. Cursor cheerfully writes this without warning. Audit constructor parameters of any class registered as Singleton — if any are typically Scoped (DbContext, repositories, MediatR sender), flag it before merge. → Permalink on

2026-06-21 原文 →
AI 资讯

Generics in C# (List , Dictionary )

Originally published at https://allcoderthings.com/en/article/csharp-generics-list-t-dictionary-tkey-tvalue In C#, generics are used to increase type safety and flexibility. Generic classes and collections eliminate the need for runtime type casting and avoid unnecessary boxing and unboxing operations, improving performance and reducing the risk of errors. Before generics were introduced, collections such as ArrayList stored elements as object . When a value type like int was added to an ArrayList , it had to be boxed (converted to object ), and later unboxed when retrieved. This boxing/unboxing process caused additional memory allocations and performance overhead. With generic collections like List<T> and Dictionary<TKey,TValue> , elements are stored in their actual types, eliminating these costs and making the code both safer and faster. List List<T> is a generic collection that dynamically stores elements of a specific type. T specifies the type of elements the list will contain. using System ; using System.Collections.Generic ; var numbers = new List < int >(); numbers . Add ( 10 ); numbers . Add ( 20 ); numbers . Add ( 30 ); foreach ( int n in numbers ) Console . WriteLine ( n ); // Output: // 10 // 20 // 30 Note: Unlike arrays, List<T> can grow and shrink dynamically. Dictionary Dictionary is a generic key–value collection. TKey specifies the type of the key, and TValue specifies the type of the value. using System ; using System.Collections.Generic ; var students = new Dictionary < int , string >(); students [ 101 ] = "John" ; students [ 102 ] = "Mary" ; students [ 103 ] = "Michael" ; foreach ( var kv in students ) Console . WriteLine ( $" { kv . Key } → { kv . Value } " ); // Output: // 101 → John // 102 → Mary // 103 → Michael Note: Each Key in a dictionary must be unique. Attempting to add the same key again will cause an error. Creating Your Own Generic Classes You can also define your own generic types, not just use built-in collections. This allows you

2026-06-19 原文 →
AI 资讯

Agent Framework RAG for Agents: Giving Your Agent the Right Context

This is Part 13 of my series on the Microsoft Agent Framework. You can read the original post over on lukaswalter.dev . In the previous article , we looked at workflows. Workflows make sense when the process itself needs structure: state, checkpoints, events, human approvals, and resumable execution. This post is the bridge from Agent Framework into RAG. I plan on doing a full RAG deep dive sometime later. The practical question for now is smaller: How do I connect an Agent Framework agent to private application knowledge without stuffing every document into the prompt? For agents, RAG is less about adding more text and more about giving the agent a controlled retrieval path. The agent should fetch the right context at the point where it needs it. Agents do not know your private data Your company documents, product catalog, tickets, rules, policies, runbooks, and internal knowledge base live outside the model. The model has generic knowledge. Your application has private knowledge. Treat those as separate systems. You can paste some private data into the prompt, and for a demo that may be enough. But this falls apart quickly: full documents are expensive to send repeatedly long prompts are fragile stale documents may sit next to current ones users may not be allowed to see every source long context still needs selection The last point is easy to underestimate. A larger context window lets you send more text. It does not decide which text is correct, current, relevant, or permitted. Do not give the agent all knowledge. Give it the right context at the moment it needs it. Retrieval owns that job. The minimal RAG shape The basic RAG loop is small: user question -> retrieve relevant chunks -> pass chunks to the agent -> agent answers using that context For documents, the longer pipeline usually looks like this: documents -> chunks -> embeddings -> vector store -> search -> retrieved context -> agent response Documents are split into smaller chunks. Those chunks are embe

2026-06-18 原文 →
AI 资讯

.NET Doesn't Suck in Neovim Anymore

I use Neovim btw... Unfortunately, I'm also a C# developer. Anyone who has used .NET in Neovim knows that the language support is tenuous. I've spent hours tweaking my configuration to get the roslyn LSP to interact with my code editor, and I could never get the limited feature set that I wanted to feel smooth and native the way other LSPs do in Neovim... especially razor. That is... until now. A few weeks ago with this commit , the developers of the roslyn.nvim plugin made it so much easier to get up and running with the roslyn server that's officially distributed by Microsoft. Early this year, Microsoft put out a prerelease of a new dotnet CLI tool roslyn-language-server . Before this release, developers got access to the server by downloading the binaries from an obscure azure feed and pointing the Neovim plugin to the proper dll . Some adventurous and patient developers even got razor support in this method, but I was not one of them. With an officially (pre-) released tool from Microsoft, downloading roslyn is now as easy as running: dotnet tool install -g roslyn-language-server --prerelease After a month or two, the developers of roslyn.nvim updated the plugin to support the new roslyn-language-server command to setup the plugin. They even set the plugin to search for it on a fallback by default, so no configuration changes are required. My configuration for roslyn.nvim used to be about 20 lines of Lua. Here it is now: { 'seblyng/roslyn.nvim' , ---@module 'roslyn.config' ---@type RoslynNvimConfig opts = {}, }, It's Simple. It works. Large projects initialize relatively quickly, and all of the standard language server operations, like semantic highlighting, renaming, jump to definition/implementation, in-editor diagnostics, etc. are available out of the box. I'm not exactly sure what magic the developers pulled here, but as I've mentioned, I've never gotten razor syntax support. With the recent updates, razor is supported! I've been using this setup for about a

2026-06-18 原文 →
AI 资讯

Class, Record and Struct in C#

Class, Record, and Struct serve as blueprints for creating new objects. Classes Classes are the foundational building blocks of Object-Oriented Programming (OOP). Blueprint and instance // blueprint public class Person { public int ID { get ; set ; } public string Name { get ; set ; } } // instance var p = new Person { ID = 1 , Name = "Mirza" } Inspection Printing the class instance in the console will just display it's name: var p1 = new Person { ID = 1 , Name = "Mirza" }; Console . WriteLine ( p1 ); // Person To print the actual, we'd need print each property explicitly: Console . WriteLine ( p1 . ID ); // 1 Console . WriteLine ( p1 . Name ); // "Mirza" Mutation C# classes are mutable, meaning the originally set values can be altered: var p1 = new Person { ID = 1 , Name = "Mirza" }; Console . WriteLine ( p1 . Name ); // "Mirza" p1 . Name = "Armin" ; Console . WriteLine ( p1 . Name ); // "Armin" That said, this can be tweaked by changing the accessor the class property. public class Person { public int ID { get ; set ; } public string Name { get ; init ; } // <-- } This time around if we try to change the value of the Name property after initialization, the C# compiler will start to complain. var p1 = new Person { ID = 1 , Name = "Mirza" }; p1 . Name = "Edis" ; // ❌ The init accessor allows you to create properties that can only be assigned a value during object initialization. Memory location Classes are reference types and are allocated on the heap. If we create two distinct class objects and assign one to the other, both objects will point to the exact same reference in memory: var p1 = new Person { ID = 1 , Name = "Mirza" }; var p2 = new Person { ID = 2 , Name = "Mirza" }; p1 = p2 ; p1 . Name = "Sead" ; Console . WriteLine ( p1 . Name ); // Sead Console . WriteLine ( p2 . Name ); // Sead If we change a value in one of the objects, it will be reflected in both. Equality Two class instances (objects) aren't equal even if they share the same values: var p1 = new P

2026-06-16 原文 →
AI 资讯

Your Hand-Rolled Two-Phase Commit Between Two Databases Isn't Atomic

I had a write that spanned two physically separate databases. A rename that had to propagate across several tables in one database and a couple of tables in another, and the two had to stay consistent. No distributed transaction coordinator was available to me. So I did the obvious thing: opened a transaction on each, did the work, and committed them one after the other inside a try/catch with rollbacks on both sides. It felt safe. It compiled. It passed tests. Then I drew the failure on a whiteboard, and the safety evaporated. The window that ruins everything Here's the structure, simplified: await using var txA = await dbA . Database . BeginTransactionAsync (); await using var txB = await dbB . Database . BeginTransactionAsync (); await DoWorkOnA ( dbA ); await DoWorkOnB ( dbB ); await txA . CommitAsync (); // <-- succeeds await txB . CommitAsync (); // <-- what if this throws? Two transactions do not make one atomic operation. CommitAsync is a point of no return, and there are two of them. Between the first commit returning and the second one starting, there is a window. If txB fails in that window — the connection drops, the process is killed, the database hiccups — then A is permanently committed and B never happens. Your rollback in the catch block is useless: you can't roll back txA , it's already durable. The two databases now disagree, and nothing in your code will heal that on its own. This is the dual-write problem , and it's not a bug you can fix by being more careful with try/catch. The atomicity you want simply isn't available from two independent commits. Ordering them, nesting them, wrapping them — none of it closes the window, because the window is inherent to having two commit points. Why "it's never failed" isn't reassurance The seductive thing about this pattern is that the window is small, so in practice it almost never triggers. You can run it for a year and never see an inconsistency. That's exactly what makes it dangerous: it trains you to tr

2026-06-15 原文 →
AI 资讯

Dynamic Column Updates in EF Core Without Hand-Rolling SQL Injection

Sometimes you genuinely need the set of columns to update to be data, not code. An operator maps configuration fields to database columns, and you want to honor that mapping without redeploying every time it changes. The naive solution — build an UPDATE string from those column names — is also one of the easiest ways to hand-write a SQL injection vulnerability. This is how to get the flexibility without the hole. We'll build it up in three layers: make it work, make it safe, then count the cost. Layer 1: The dynamic update, the wrong way The tempting version concatenates column names into SQL: // DO NOT do this. var sql = $"UPDATE products SET { columnName } = { value } WHERE id = { id } " ; If columnName comes from configuration that an operator can edit, you've just made your schema writable by whoever controls that config. A value of name = 'x'; DROP TABLE products; -- is now your problem. Even "trusted" config is an injection surface the moment it flows into a SQL string. Layer 2: The same feature with EF.Property EF Core's ExecuteUpdateAsync lets you set a property by name without ever building SQL yourself. EF.Property<T> takes the property name as a string, and EF parameterizes the value and validates the property against the model: await db . Products . Where ( p => p . Id == id ) . ExecuteUpdateAsync ( setters => setters . SetProperty ( p => EF . Property < float ?>( p , columnName ), value )); This is already a different security posture: the value is a parameter, not interpolated text, and EF will throw rather than emit SQL if columnName isn't a real mapped property. But "EF will throw" is a runtime backstop, not a policy. We want to reject bad names before they reach the database, fail closed, and control exactly which columns are writable. Layer 3: Reflection as a whitelist The guard is to validate every incoming column name against the entity's actual properties, using reflection, and to keep an explicit blacklist of fields that must never be touched d

2026-06-15 原文 →
AI 资讯

Blazor SSR Gets Client-Side Validation in .NET 11 Preview 5 — No More Round-Trips Just to Show a Red Border

Blazor SSR Gets Client-Side Validation in .NET 11 Preview 5 If you've built Blazor Server-Side Rendering (SSR) forms, you know the pain: a user fills out a form, hits submit, the form posts to the server, the server runs validation, and only then does the user see the "This field is required" message next to the empty email field. That round-trip latency adds up. It breaks the immediacy users expect from modern web apps. .NET 11 Preview 5 fixes this. Blazor SSR forms now get instant, in-browser validation feedback — no server required. The server renders your validation rules as metadata, and Blazor's JavaScript enforces them client-side. Same DataAnnotationsValidator component you already use. Zero code changes needed. Let's break down how it works. Before .NET 11: The SSR Validation Gap In .NET 8 and 9, Blazor SSR rendered HTML on the server and sent it down. Validation only ran server-side — on form submission. If a field was invalid, the whole form posted to the server, came back with validation messages, and re-rendered. Interactive Blazor modes (Server, WebAssembly, Auto) had instant client-side validation because an active SignalR circuit or WASM runtime ran the validation logic locally. But SSR mode — the simplest, most performant option — was left out. The result? Developers who chose SSR Blazor for its simplicity had to choose between: Accepting the laggy validation UX Adding a second JavaScript validation library (and maintaining two validation rulesets) Re-architecting to use an interactive render mode None of these are great options. What Changed in .NET 11 Preview 5 The .NET team shipped two PRs ( #66441 and #66420 ) that bring unobtrusive client-side validation to Blazor SSR forms. The key insight: The .NET model stays the single source of truth. On form render, the server serializes your DataAnnotations validation rules into HTML metadata attributes. Blazor's JavaScript reads those attributes and applies them client-side — the same approach ASP.NET M

2026-06-13 原文 →
AI 资讯

How I Built an AI-Powered Adult (Porn) Content Scanner for Windows (And the Engineering Challenges I Didn't Expect)

Building an AI-Powered Content Scanner for Windows: Performance, Multithreading and GPU Acceleration in .NET Building software always looks straightforward from the outside. You load a machine learning model, point it at some images, and display the results. At least that's what I thought when I started building DetectNix Vision , a Windows desktop application that performs local AI-powered image analysis without uploading user data to the cloud. In reality, the project became a deep dive into performance optimization, memory management, multithreading, GPU acceleration, and user experience. This article covers the engineering challenges I encountered and the architectural decisions I made while building the software from the perspective of a senior developer. The Original Goal The initial goal was simple: Scan images stored on a Windows PC Detect potentially explicit or sensitive content Keep all processing local Support both CPU and GPU execution Process large image collections efficiently Remain responsive while scanning Privacy was a major requirement. I didn't want users uploading personal files to third-party services. Everything needed to run locally on the user's machine. That decision immediately influenced every technical choice that followed. Challenge #1: Model Loading Performance One of the first mistakes I made was loading the AI model too frequently. A modern computer vision model can be hundreds of megabytes in size. Loading it repeatedly creates significant startup overhead and quickly destroys performance. My initial implementation worked perfectly during testing because I was only processing a handful of images. Once I started testing larger image collections, the bottleneck became obvious. The Solution I moved to a singleton-style architecture where the model is loaded once during application startup and remains resident in memory. private readonly InferenceSession _session ; public VisionEngine () { _session = CreateSession (); } This reduced in

2026-06-12 原文 →
开发者

C# 14: The `field` Keyword — Cleaner Properties, Zero Boilerplate

C# 14: The field Keyword — Cleaner Properties, Zero Boilerplate Every C# developer has been there. You start with a clean auto-property, then requirements change and you need to add a tiny bit of validation. Suddenly that one-liner explodes into six lines of boilerplate — a private backing field, a getter that just returns it, a setter that assigns it. The logic is two words. The ceremony is everything else. C# 14 fixes this with the field keyword: a contextual keyword that refers to the compiler-synthesized backing field of a property, letting you write custom accessor logic without ever declaring an explicit field. The Problem: Boilerplate Tax on Simple Properties Auto-properties are one of C#'s best quality-of-life features. This is clean: public string Username { get ; set ; } But the moment you need to trim whitespace on assignment, that cleanness evaporates: private string _username = string . Empty ; public string Username { get => _username ; set => _username = value . Trim (); } You now have six lines — and four of them exist only to hold the shape of the pattern together. The backing field _username is not carrying any meaningful design weight. Its only job is to be a storage slot that Username uses privately. You already know the compiler creates one for auto-properties. You are just forced to make it visible so you can reference it. This is the boilerplate tax. You pay it every time you add even the smallest piece of logic to a property. Why field Exists The C# language team has discussed this friction for years. The challenge was finding syntax that is: Unambiguous — no conflict with existing identifiers Familiar — consistent with how value works in setters Scoped — only meaningful inside a property accessor The solution landed in C# 14: the contextual keyword field . Just like value refers to the incoming assignment in a setter, field refers to the hidden backing storage the compiler manages for the property. It is contextual, which means it only acts

2026-06-11 原文 →
AI 资讯

The AI-generated C# that passes review and breaks in production

TL;DR — AI assistants are producing C# that looks correct and passes review, but reintroduces production regressions we spent years training out of teams. I'm trying to find out whether other .NET teams see the same patterns — and what's actually catching them before merge. More AI-generated C# is landing in pull requests. Most of it is fine. But a specific category keeps slipping through — and it's the dangerous one, because it compiles, tests pass, and a human skim says "looks good." The pattern The code compiles. Tests pass. Review approves. Production finds out. These aren't syntax errors. They're architectural intent violations — the kind of thing a senior dev would have caught in review before PR volume tripled. Five regressions I keep seeing 1. EF Core read paths without AsNoTracking() Fine in dev. Expensive on a hot read path in prod. // ❌ Looks reasonable. Tracks entities you never mutate. var orders = await _db . Orders . Where ( o => o . CustomerId == id ) . ToListAsync ( cancellationToken ); Fix direction: AsNoTracking() on read-only queries, or a team convention documented in CLAUDE.md / Copilot instructions. 2. Captive dependency (scoped service in a singleton) Compiles. Runs. Wrong state across requests. // ❌ Singleton lives forever; scoped dependency does not. services . AddScoped < IOrderRepository , OrderRepository >(); services . AddSingleton < ReportCache >(); // ctor takes IOrderRepository Fix direction: align lifetimes, or inject IServiceScopeFactory instead of capturing scoped services. 3. Dropped CancellationToken The method accepts cancellation. The downstream call ignores it. // ❌ Signature honours cancellation; body doesn't. public async Task RunAsync ( CancellationToken cancellationToken ) { await Task . Delay ( 500 ); // overload with token exists } Fix direction: forward cancellationToken to every downstream async call that accepts one. 4. Swallowed exception Failure disappears. Monitoring stays green. // ❌ "Handle errors gracefully" —

2026-06-10 原文 →
AI 资讯

AI agentic workflows on large codebases

The first post went over some of its capabilities. Over the past week Edict went v1.0, adding cursors for reading projections after command dispatch (to close some eventual-consistency gaps), a new type of projection that holds state inside the Orleans grain directly instead of a table, saga timeouts, schedules, an improved skills package and MCP server that ships with Edict, and more. Edict has now grown to over 75,000 lines of code and more than 1000 tests, and contains several deep mechanisms that have been fixed, broken, and fixed again. It is well past the point where I can hold all of Edict in my head. This post is about working with AI on large codebases, which I expect to be the first problem most software engineers have to solve. The context problem Years ago I was talking to a PhD candidate whose area of research was Natural Language Processing (NLP). He explained to me that one of the most difficult NLP problems was context. If a colleague says they need to pop out to pick their kids up from school, a scene can form in your head: one with a school, the layout of the road, people waiting, walking, driving, the environs. You may never have seen the school your colleague mentioned, but you can form a rich scene from your accumulated experience and use it to drive the rest of the conversation with a shared understanding. LLMs ingeniously dodge this entire issue by making it your problem. Just a word-probability machine Strip away the chat window and a Large Language Model (LLM) is doing one thing: predicting the next token. Give it a run of text and it returns a probability distribution over what comes next, samples one, appends it, and repeats. Companies like OpenAI and Anthropic then beat it into shape using techniques like supervised fine-tuning and reinforcement learning, which tune those probabilities in meaningful ways. That is why Claude is always telling me "Good framing" or "You've spotted...". It even called me "Bold" on one occasion. The probabilit

2026-06-09 原文 →
AI 资讯

What I Learned Building a Product Review Platform Using ASP.NET Core and SQL Server

When I started building OpinioZone , my goal was simple: create a platform where users could compare products, read reviews, and make informed buying decisions. At first, it seemed like a straightforward web application. Store products, display specifications, and allow users to browse information. However, as the platform grew, I quickly discovered that building a review and comparison website involves many technical and architectural challenges. Choosing the Technology Stack I selected ASP.NET Core as the primary framework because of its performance, flexibility, and long-term support. For data storage, I chose SQL Server since it provides strong reliability and works well with complex relationships between products, categories, reviews, ratings, and specifications. This combination allowed me to build a scalable foundation while keeping development manageable. Designing the Database One of the biggest challenges was designing a database structure that could support multiple product categories. A smartphone and a car have very different specifications, but the platform needed to handle both efficiently. Instead of creating completely separate systems, I designed a flexible structure that could store category-specific attributes while maintaining a consistent user experience. This decision made it easier to add new product categories without major database changes. Building Product Comparisons The comparison feature became one of the most important parts of the platform. Users expect side-by-side comparisons to load quickly and display meaningful differences between products. To achieve this, I had to optimize queries and carefully structure specification data. Performance became increasingly important as the number of products grew. SEO Challenges For a content-driven website, SEO is critical. Every product page requires: Unique titles Descriptions Structured content Internal linking Fast page loading One lesson I learned early was that technical SEO and content q

2026-06-08 原文 →
AI 资讯

How to Install Tailwind CSS v4 in a .NET Blazor App (The Easy Way)

A step-by-step, beginner-friendly guide to stripping out Bootstrap and setting up the blazing-fast Tailwind CSS v4 compiler in your .NET Blazor Hybrid or Web app. Tailwind CSS v4 is officially here, and it is a complete game-changer! It scraps the old, bulky JavaScript configuration files ( tailwind.config.js ) and moves your theme settings directly into standard CSS. Plus, its new native compiler is faster than ever. If you are building a .NET Blazor app (whether it's Blazor WebAssembly, Server, or a MAUI Blazor Hybrid app) and want to swap out the default Bootstrap styles for utility-first Tailwind bliss, you can do it all without ever leaving your IDE. Let's get this configured step-by-step using Visual Studio 2022 ! Prerequisites Before we start, make sure you have: Node.js installed on your development machine. A Blazor project opened in Visual Studio 2022 . Step 1: Say Goodbye to Bootstrap in Solution Explorer Blazor templates ship with Bootstrap by default. Let's use Visual Studio's Solution Explorer to clean that out so our styles don't conflict. In the Solution Explorer window, expand your wwwroot folder. Expand the css subfolder. Right-click the bootstrap folder and select Delete . Now, open your main HTML entry file inside wwwroot (this will be index.html for Blazor Hybrid/WASM or App.razor inside the Components folder for Blazor Web). Locate the <head> section and delete the line linking the Bootstrap stylesheet: <link rel= "stylesheet" href= "css/bootstrap/bootstrap.min.css" /> powershell Step 2: Open the Developer PowerShell & Install Tailwind v4 Tailwind v4 splits the design library from the command-line build tool, so we need to install both. We can use Visual Studio's built-in terminal for this. In the top menu of Visual Studio 2022, go to Tools > Command Line > Developer PowerShell . A terminal window will open at the bottom of your IDE, already navigated to your project folder. Paste and run the following commands: i. Initialize a package.json fil

2026-06-08 原文 →
AI 资讯

How to Install Tailwind CSS v4 in a .NET Blazor App (The Easy Way)

A step-by-step, beginner-friendly guide to stripping out Bootstrap and setting up the blazing-fast Tailwind CSS v4 compiler in your .NET Blazor Hybrid or Web app. Tailwind CSS v4 is officially here, and it is a complete game-changer! It scraps the old, bulky JavaScript configuration files ( tailwind.config.js ) and moves your theme settings directly into standard CSS. Plus, its new native compiler is faster than ever. If you are building a .NET Blazor app (whether it's Blazor WebAssembly, Server, or a MAUI Blazor Hybrid app) and want to swap out the default Bootstrap styles for utility-first Tailwind bliss, you can do it all without ever leaving your IDE. Let's get this configured step-by-step using Visual Studio 2022 ! Prerequisites Before we start, make sure you have: Node.js installed on your development machine. A Blazor project opened in Visual Studio 2022 . Step 1: Say Goodbye to Bootstrap in Solution Explorer Blazor templates ship with Bootstrap by default. Let's use Visual Studio's Solution Explorer to clean that out so our styles don't conflict. In the Solution Explorer window, expand your wwwroot folder. Expand the css subfolder. Right-click the bootstrap folder and select Delete . Now, open your main HTML entry file inside wwwroot (this will be index.html for Blazor Hybrid/WASM or App.razor inside the Components folder for Blazor Web). Locate the <head> section and delete the line linking the Bootstrap stylesheet: <link rel= "stylesheet" href= "css/bootstrap/bootstrap.min.css" /> powershell Step 2: Open the Developer PowerShell & Install Tailwind v4 Tailwind v4 splits the design library from the command-line build tool, so we need to install both. We can use Visual Studio's built-in terminal for this. In the top menu of Visual Studio 2022, go to Tools > Command Line > Developer PowerShell . A terminal window will open at the bottom of your IDE, already navigated to your project folder. Paste and run the following commands: i. Initialize a package.json fil

2026-06-08 原文 →