r/csharp

▲ 3 r/csharp+1 crossposts

Would you introduce additional abstraction layer just to make the code more understandable ?

I have a database that currently contains 20 tables.

In my application, there are 10 classes that I should refactor, to make them more readable, for my future self and others who will read my code, by refactoring, I mean changing the code it self - the logic- and also changing the methods and classes names.

Let's only consider one specific case; changing the name of one class.

When my friend so the following code that I wrote:

/// <summary>
///  Abstracts the destination to which data is written, regardless of  whether the destination is a file, database, or any other kind of storage.
/// </summary>
public interface IWriter
{
//...
}

public class SqlServerWriter : IWriter {//code.....}

he thought that the responsibility of the above class is to write data to any number of tables in the the Sql Server database, i.e., that it can use it to write data to only one table, two or more tables, or all of the tables.

Unfortunately, that was not what the class is actually responsible for; it is meant to write a specific data across all the tables in the database, it does not give the caller an option to write a generic data to a specific tables in the database.

He was mad at me and said that I should introduce an additional layer of abstraction:

/// <summary>
/// Abstracts the destination tables in the Sql Server; may write to all tables in the database or some of them;
/// </summary>
public interface ISqlServerWriter:IWriter
{
}

/// <summary>
/// Intended to write some data to all the tables in the database.
/// </summary>
public class AllTablesWriter : ISqlServerWriter {//code.....}

Do you consider that an overkill/overengineering ?

EDIT:

If you wonder why the class write data to all the tables in the database, it because it has the job of synchronizing the content of the database with external data source, specifically, an Excel file.

reddit.com
u/kaatarina_zed_talon — 9 days ago
▲ 15 r/csharp

Has anyone moved from Crystal reports to a .net reporting solution?

We have about 400 reports writen in Crystal Reports. We want to move away from this to something that is .net native and will run in Linux.

Has anyone done this, and what was the outcome?
Related question; what reporting solutions have people used and what were they like?

reddit.com
u/IntnlManOfCode — 10 days ago
▲ 41 r/csharp+1 crossposts

Hypa - A terminal multiplexer built in C#

I want to share a little project I've been working on for a few weeks now, an entirely C# .NET 10 AOT compiled terminal multiplexer, currently only Linux and MacOS but I do intent to add Windows as a fully supported platformat eventually.

Hypa v1.0

https://github.com/Hypabolic/Hypa

I actually started building this just as proof it could be done and be high performance in .NET as a sort of way of kicking back against basically every tool these days being built in Rust (including Microsoft recently porting Copilot itself to Rust).

My inital aim was to build a simple herdr type mux clone but as I built it I've ended up going beyond that scope and building things not available in herdr.

One feature I really wanted for a start were 'background panes' essentially a normal terminal pane doing whatever you (or an agent) wants it to do but it never appears in the TUI until you ask for it (or the agent running inside it requests it)

The next feature I wanted was remote machines built in natively, which herdr does do, but I wanted to totally avoid things like SSH and managing keys, in Hypa we call these remote machines cubes (hypa cubes...). Hypa uses the QUIC protocol to connect to remote machines and certificate management is handled for you behind the scenes. All you need is the join code and some type of network access to the remote machine.

I've really enjoyed building this as a hobby project, and I hope some of you will give it a go and offer me some feedback.

I look forward to seeing what you all think and getting some feedback, but most of all I'm just happy I can show that these sort of highly performant terminal experiences CAN and SHOULD be built in C# .NET and native AOT is mature enough to support them.

u/Hephaestite — 11 days ago
▲ 15 r/csharp

Is it even possible to do this on WebAapp. Barcode scan → qty → print price labels —

We want a simple page in our web app since the current one we use got alot of steps and bad UX.

So this is what i'm thinking the workflow for printing a label will be

  1. Staff opens a “Labels” page on our webapp.
  2. Scans a product barcode with a handheld USB scanner
  3. App asks for quantity (while looking up product data async)
  4. They type qty + press Enter
  5. N labels are sent to a label/thermal printer
  6. Optionally choose between a few predefined label designs

Questions for people who’ve done this. Is it even possible? I just know only how to build simple CRUD app but not with those a scanner/hardware

  1. For USB handheld scanners: is treating them as a keyboard wedge (focused <input> + Enter) still the standard approach in browser apps, or is there something better today
  2. What’s the most reliable way to print labels from a web app (not WinForms/WPF)?
    • window.print() / PDF in browser?
    • Zebra Browser Print / ZPL?
    • Some local print agent/service?
    • Something else?
  3. Any hard limitations we should know about?

---

u/YouAreMyFire00 — 11 days ago
▲ 5 r/csharp+1 crossposts

GRPC server-side assets with state/persistent data

I am writing my first gRPC application and I am totally lost:

I have to provide gRPC server access to persistent data. The persistent data resides outside the application (it is a hardware device). Reading the persistent data is an expensive operation and it is not an option to ask the device for data every time a gRPC request arrives. Figuring out if the persistent data changed between calls is cheap.

Thus, I want to pull the persistent data into memory upon startup and if the persistent data changed, creating a copy of the data. For each gRPC request, I can ask the device if an update is necessary. If not, I service the request using the (shadow) data kept in memory.

I follow the Microsoft "gRPC services with C#" route and I end up with a server side asset, similar to the tutorial:

public class GreeterService : Greeter.GreeterBase
{
    private readonly ILogger<GreeterService> _logger;
    public GreeterService(ILogger<GreeterService> logger)
    {
        _logger = logger;
    }

    public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply
        {
            Message = "Hello " + request.Name
        });
    }
}

This is the default template Visual Studio creates for a gRPC server. I do not know how the Microsoft gRPC server works and I do not think it should be required to reverse engineer it. The documentation states that I have to edit the .proto file to suit my needs (done) and to implement the server-side asset (i.e. the code that generates the response to the request). The rest is handled by the auto generated framework.

I learnt the painful way that this is a stateless approach, i.e. each gRPC transaction creates a new instance of this class and destroys it after it is finished. This is great for a stateless service, but I need some persistent information stored long term in memory. This clearly does not work with this approach as I have to keep my data in scope.

What is the civilized way? So far I considered:

  • A pure static class that is doing the business logic. Well. Works, but goes against modern principles.
  • Some singleton dynamic class doing the business logic. The problem here is that I do not want to learn how the gRPC framework works and I am afraid that the GC decides to kill my business logic class. Sure, I can create a static/global instance somewhere, but that is probably even uglier. I do not know how to nicely keep my object in scope.

So what is the proper way to handle this? To give you an idea: How to have a persistent integer value with a gRPC, implementing a setter and a separate getter? Where do I "store" this value? The integer must be a "long lifetime" variable, i.e. stay alive between gRPC requests.

reddit.com
u/szgyula — 11 days ago
▲ 87 r/csharp

WPF trading terminal, just for fun

Saw a few screenshots of trading terminals on Reddit, thought they looked cool, and building a UI full of charts sounded like a fun thing to try. So I gave it a shot.

It's .NET 8 + WPF, with HandyControl and ScottPlot for the charts. Heatmap, screener, candles, options chain, crypto, a few other panels. Data is from free public APIs.

Last month I was hooked on Path of Exile 2 too, so I used the same look for a little app around the game's economy inspired by poe2scout and Sidekick. Last screenshot is that one.

u/Smokando — 13 days ago
▲ 14 r/csharp+1 crossposts

Respire - A .NET Redis Client

Hey all!

Redis is a great technology, and something that exists in a lot of tech stacks. It has the ability to really help solve complex problems involving distribution across multiple instances of an app. Whether that be caching, locks, rate limits, etc.

Surprisingly, StackExchange.Redis is the only real big main redis client library for .NET.

I'm adding a new client library into the mix - Respire.

Respire aims to be a fast client library for Redis, that also has the ability to utilise Redis' client-side server assisted cache, avoiding network hops for frequently accessed keys, meaning better performance for your apps.

It also has a lot of helpers in it to more easily use distributed locks, rate limits, queues, pub/sub, etc.

I want it to be a client library that handles all the hard bits for you, keeping your code clean and easy to reason about.

It's still pre-release, so I'd like to gather feedback. Are people happy with the performance? The API? Any missing features? Any bugs?

Please try it out and let me know!

More info on why Respire: https://thomhurst.github.io/Respire/docs/#why-respire-exists

Benchmarks: https://thomhurst.github.io/Respire/docs/benchmarks

Stress comparisons: https://thomhurst.github.io/Respire/docs/stress-tests

Thanks all!

reddit.com
u/thomhurst — 11 days ago
▲ 1 r/csharp+1 crossposts

How to move the responsibility of executing some logic to the Sql Server instead of executing that logic inside the application?

I have Excel file that contains many columns like this :

SKU BarCode EnglishName ArabicName Category SubCategory

There are other columns, but there is no need to show them to convey the problem behind this post. The Excel file is sent from the client to the server which will read it using C# .

The problem : The data of the above Excel file should be persisted to the appropriate tables in the Sql Server database which does not merely contain a single table, so, a specific data from the Excel file should be consumed by a specific table in the database, the problem is not simple as send the data of the Excel file to only one destination table; the source is only one, which is the Excel file, but there are many destination tables. Database contains parent and child tables; parent tables do not contain foreign keys, child tables contain one or more foreign keys. The data for the child tables cannot be persisted to the database unless the data for the parent tables is persisted first.

I have the following C# domain classes/models:

public interface IEntity{

}

public  interface IParent:IEntity{

}

public interface IChild : IEntity{


}
public interface INonJunctionChild:IChild{

}

public interface IJunctionChild:IChild{

}

public class Product:IParent
{
    public string? SKU { get; set; }     // SKU column in Excel
    public  string? Barcode{ get; set; } // BarCode column in Excel
    public string? EnglishName {get;set;} // EnglishName column in in Excel
    public string? ArabicName { get; set; } // ArabicName column in Excel
    public IEnumerable<ProductCategory> ProductCategories { get; } = new List<ProductCategory>();  
    
    // Alot of other navigaton properties.....

}

public class Category:IParent{
  public string EnglishName {get;set;} // Category column in Excel
  public IEnumerable<ProductCategory> ProductCategories { get; } = new List<ProductCategory>();
  public IEnumerable<SubCategory> SubCategories { get; }=new List<SubCategory>();    


  // alot of other  navigation properties....
}

public class SubCategory:IChild{
  public string EnglishName {get;set;} // SubCategory column in Excel
  public string CategoryId {get;set;} // Foreign key; populated using lookup operation.
   
}
public ProductCategory{
  public int ProductID {get;set;} Foreign key; populated using lookup operation.
  public int CategoryId {get;set;} Foreign key; populated using lookup operation.
  public Product Product { get; set; } = null!;
  public Category Category { get; set; } = null!;
}

My old approach to solve the problem -which worked, but I want to change it- has the following steps:

1-Read the whole excel sheet into the application.

2- Inside the application, populate the specific properties of each parent domain model by assigning specific Excel column values to to them.

3-persist the parent models to the database.

4- Populate the child tables using lookup operations.

5- Persist the child tables to the database.

Instead of the above, I would like to know if the following is possible:

1- Get `DbDataReader` using `Sylvan.Data.Excel and pass it to `SqlBulkCopy` class.

2- The Whole Excel file will be persisted into a staging table or view, and then some trigger will be fired, as a result, some stored procedure or function will be executed, the responsibility of that function or procedure is to persist the data of the parent tables first, then to persist the data of the child tables, which means.

So, In the old approach, can the responsibility for transforming the Excel data, resolving the required relationships, and persisting the parent and child records (steps 2 through 5) be moved from the application layer to SQL Server?

u/kaatarina_zed_talon — 11 days ago
▲ 2 r/csharp+2 crossposts

🚀 Un pequeño logro que me motiva a seguir creando para .NET

Hoy quiero compartir un avance de mis proyectos.

📦 MyCrypto.GiqhDev
🔐 Librería .NET para cifrado autenticado, hashing seguro de contraseñas y utilidades criptográficas.
➡️ 625 descargas

🔑 MySerialKey.GiqhDev
🛡️ Librería para generación y validación de claves de licencia/serial para aplicaciones .NET.
➡️ 338 descargas

📊 963 descargas entre ambas librerías.

Puede parecer un número pequeño frente a proyectos con miles o millones de usuarios, pero para mí representa algo importante: hay desarrolladores que están encontrando utilidad en código que nació como proyectos personales.

Lo más interesante del proceso no ha sido solamente publicar los paquetes, sino aprender sobre:

  • Desarrollo de librerías reutilizables para .NET
  • Compatibilidad entre diferentes versiones de .NET
  • Publicación y versionado de paquetes NuGet
  • Seguridad y criptografía
  • Diseño de APIs reutilizables
  • Mantenimiento y evolución de proyectos open source

Y esto recién comienza. 🚀

Mi objetivo es seguir construyendo herramientas para el ecosistema .NET / C#, mejorar las existentes y continuar compartiendo lo que voy aprendiendo en el camino.

963 descargas hoy → muchas más cosas por construir mañana. 💙

#DotNet #CSharp #NuGet #OpenSource #SoftwareDevelopment #Programming #GiqhDev #Developer #Backend #DotNetDeveloper

u/Giqh — 11 days ago
▲ 2 r/csharp

Voice skill interviews in .NET, and why the model can't keep time

I built a Blazor voice interviewer: pick a skill from JSON, talk, get a score. OpenAI via Microsoft.Extensions.AI, Azure Speech, audio on its own WebSocket.

One thing that surprised me: the model has no sense of time. It only sees the text in the conversation, so it would end the interview early. I had to send the remaining time in every interaction.

full article: Building a Skill Interview with AI

GitHub code: hugoj0s3/SkillsValidator

reddit.com
u/West_Ad6277 — 12 days ago
▲ 0 r/csharp

Relatude.DB b209

We are making progress with our native open source (MIT) C# database engine: https://db.relatude.com

(I've posted earlier about the engine, and thanks for the feedback so far!)

Have a look at this graphical UI for faceted searches: https://demo.db.relatude.com/graphql

(In the admin UI, you get more functionality, but it requires you clone the project and run locally )

This is just a quick example of some of the functionality that comes with the Relatude.DB nuget.

What do you think?

Any feedback is welcome! ( It is still early alpha .... )

https://preview.redd.it/krcxuup90gth1.png?width=2969&format=png&auto=webp&s=265b2cd7d4a980e8300e74ea0fc4545b16f54fd9

reddit.com
u/Remarkable_Art_6958 — 11 days ago
▲ 3 r/csharp+2 crossposts

Frames Compression problem

It's been two weeks since I learn how to get the frames straight from the gpu as a direct 3D surface .

now I ran into the problem of how to compress this frame and send it via UDP server to officially compelete my streaming project.

I tried to scale the frame and then send it , it worked , but it looks super ugly and yet the process is not as fast as I want (it is a remote computer control, it must be a smooth picture in the end).

I used LZ4codec , believe me nothing reach up to my expectations 😔.

does any one have the optimal solution in which it will straight compress the frame to be less than 65kb so I can send it properly, and don't forget get to be ultra fast approation 🙂.

reddit.com
u/Emotional_Talk7137 — 12 days ago
▲ 1 r/csharp

Equal precedence

I was wondering how would one properly implement equal precedence in an if-else statement, for logical AND and OR, when building an interpreter?

I have made my expression parser but i only store the next logical operator on the right most side and store the current being parsed on the left.

Repo

reddit.com
u/Excellent-Cow-9046 — 11 days ago
▲ 0 r/csharp

ifIsEvenGenerator

reddit handles code pasting weirdly and I don't know if it highlights code so here is pastebin to my ifIsEven generator.

have fun looking into this poorly but at least man-made code, that generates even worse code.

(previous 2 versions on pastebin named exactly the same are older and weren't fully working and were not formatted as I wanted them to be.)

pastebin.com
u/Efficient-Mix-2822 — 12 days ago
▲ 11 r/csharp

What actually triggers "Windows protected your PC" on a signed C# app (and how to check before release)

I spent a while digging into why signed desktop apps still hit SmartScreen, and a few things surprised me:

  • SmartScreen only checks files that carry Mark-of-the-Web. Anything downloaded through a browser gets a Zone.Identifier stream (ZoneId=3). Run the same installer from a build folder and you'll never see the warning, which is why devs rarely catch it themselves.
  • Reputation is per file hash and per signing certificate. Every new release is a new hash. Renewing the certificate can reset you too.
  • A valid signature isn't the question SmartScreen asks. It asks whether Microsoft has seen this exact file from enough machines without incident. And since 2024 an EV certificate no longer buys that reputation instantly.
  • Signing hygiene still matters: no timestamp means the signature stops validating when the cert expires; SHA-1 signatures are treated close to unsigned.

To see what a first-time user sees, I ended up building a probe that downloads the installer onto a clean Windows 11 VM with Mark-of-the-Web and runs it: https://signalscreen.dev/probe (free while in beta). The homepage has a free signing check too; the grader is open source.

Curious what others have run into: have you seen a release get flagged right after a cert renewal?

u/mnaza_andrey — 13 days ago