/r/dotnet

Photograph via snooOG

.NET Community, if you are using C#, VB.NET, F#, or anything running with .NET... you are at the right place!

/r/dotnet

195,506 Subscribers

2

Avalonia Browser project with development time environment variables

I'm asking here (instead of r/Avalonia) because i think it'll get more response. Please be nice to me, as I'm new to Avalonia, and know less about web development.

My remote test environment is using an ASP hosting site. (Not Azure.)

My app needs to read an Environment Variable using Environment.SetEnvironmentVariable(). I can create a simple new ASP.NET Core MVC Web App, publish to the hosting site, read the variable and display it. Meanwhile, while developing using localhost, I add the environment variable to launchSettings.json, and like magic, it all works. Took a few minutes of my life to test this scenario works.

But with Avalonia.....agggh. Pulling my hair out. Tried back and forth with Co-Pilot and ChatGPT to get something to work. Finally, after hours of this, ChatGPT finally told me that "No, launchSettings.json does not work with Avalonia apps. Silly me for thinking it would, I guess. (And I still don't understand why the Browser project doesn't!)

Following lots of advice (AI. google searches, reddit posts, docs, etc.) that works for .net programming for not Avalonia, I tried ConfigurationBuilder() to load launchSettings.json, or appsettings.development.json, but that apparently won't work on Avalonia, as apparently files must be served over http.

So, I'm off to just loading appsettings.development.json over http, but that doesn't work either, because there's no way to address that url unless I put it on the same level as wwwroot. (Cross-origin requests are blocked, so I'm told.) Obviously, putting something like a connection string in appsettings.json already sparks enough debate, and now ChatGPT is telling me, well, just put it in wwwroot. Um, no.

OKAY, so two questions here for you experienced gurus:

(1) What's the better way to do this? I'm not really wanting to go the Azure route, as I know people like Azure Key Vault. (I just know zero about Azure and previous attempts to dabble were off-putting at my level. I'm not a web developer. I'm a WinForms developer, actually, trying to do Avalonia so I can run in a browser and just focus on business logic and UI without having to be a web expert.)

(2) Even if it's not the right approach, I still want to know how to use environment variables in Avaloina. I'm assuming, but maybe wrong, that they work on the hosted server environment, so how do I use them when developing on localhost?

2 Comments
2025/02/05
05:06 UTC

0

Application Insights - is it possible to create a heat map from collected user data?

Hi all, I’ve got Application Insights properly configured along with the click analytics plugin and I’m trying to tease out a way to build a heatmap similar what hotjar offers. Can anyone point me to any resources that can help me solve this or do I need to look at an additional user analytics platform?

2 Comments
2025/02/05
03:51 UTC

0

Hiring top freelance talents for backend upgrade

Hi all

I have a large monolithic saas application in my maintenance. It's still asp.net 4.8 and AngularJS. A few 1000 userbase.

The project/product is about 10 years old. About 10 devs have worked on it. It's decently maintained and i was able to iron out a lot of performance issues.

Of course, i wasn't in the company yet when a lot of bad decisions were made. And it's time to get with the times if we want to be attractive to be able to hire any devs in the future.

As you can imagine we're still on jQuery 1.10 and bootstrap 3. Entity framework 6.4.4.

But the main focus for now is the backend. Which is REST with some OData here and there. Some old-school OWIN for bearer tokens etc. It's not bad, it could be a lot worse.

Instead of contacting local consultancy agencies, or god forbid, a recruiter, i was thinking of looking for the best of the best.

I expect a technical upgrade of just the back end wouldn't take longer than 1 month for someone talented. After that they may even have a look on cleaning our solution and general upkeep and advice to our devs.

Sometimes I'd see a GitHub profile and I'd think they could really help me out.

Where and how do i find the .NET ninjas that would work on a freelance basis? Is local talent just as good?

I am located in Belgium

Thank you for any opinions or advice

Tldr: looking for freelance dotnet architect/full stack advice and expertise. Where to find these.

7 Comments
2025/02/05
03:27 UTC

70

.NET 9 CRUD with Best Practices [Detailed]

Last week, I ran a poll on all of my social handles to see which article you'd like to see as part of the .NET Zero to Hero course.

With over 1,000 votes cast, more than 40% of you voted for .NET 9 WebAPI CRUD with EFCore – and I’m thrilled to announce that the detailed article is finally LIVE! πŸš€

So, what can you expect from this article?

  • 😊 Project Setup from Scratch
  • ✨ Configuring OpenAPI & Scalar
  • πŸ’‘ Domain Driven Design Basics
  • πŸ”§ Adding EFCore & Registering the DbContext
  • πŸ“Š Code First Migrations
  • πŸ” IEntityTypeConfiguration
  • 🐳 Running PostgreSQL on Docker
  • 🌱 Data Seeding – Best Practices
  • πŸ”’ DTOs and ViewModels
  • πŸ–₯️ CRUD Implementations
  • ⚑ Minimal API Endpoints

Read: https://codewithmukesh.com/blog/aspnet-core-webapi-crud-with-entity-framework-core-full-course?utm_source=reddit

Happy coding! πŸ˜„

7 Comments
2025/02/05
00:40 UTC

0

Programming question from a non programmer

Hello! I'm in a pickle and looking for some advice!

I'm looking at purchasing a company that's currently in .net 3.1 core. How hard is it to update to .net 7 or 8 or 9? How many hours am I looking at paying people in general? How much work is actually involved? What more information do I need to add to this post to get a better answer??? I'm limited on what I can say do to an NDA.

Any help would be great or even resources specifically in this matter. Thank you kind strangers πŸ™

43 Comments
2025/02/04
22:59 UTC

0

Website Images Do Not Update in All Browsers

I'm having a really hard time getting part of my web page to update. It is written in .NET 8 using ASP.NET Core and the MVC pattern. The site is served by IIS Express on my laptop, on my home Intranet. The site itself serves fine at the http://[localaddress]/[project].

When I started programming it three weeks ago, I included two image links. The are to "~/images/mtg_card_back.png" and "~/images/chaos-orb.jpg". I have since changed second link to "~/images/mtg-mirror-universe.jpg". However, when I run the app (either in Visual Studio 2022 or through IIS after publishing it), the old image URLs are still used. Moreover, I changed the alt test on the Chaos Orb to read "Mirror Universe", but it still says "Chaos Orb". When I use Developer Tools, I can see the old URLs are still there.

As a test, I bunged up the URL on the card back: still there. I deleted the image: okay, now it can't find it. Progress!. Then I added it back as "mtg-card-back.png", replacing the underscore with a dash, to match the other filename. Now, it can't find it, and the URL in the page still has the older reference. Restoring the name restores the image.

When I Iook in sources on Dev Tools, only the card back and the chaos orb are there. Interestingly, in the Console there is no error that any of the other images failed to load. It's like they just don't exist.

I have verified the image files are in the correct place, both the repo and the published folder. I have cleared caches on three browsers and downloaded a fourth that I never used, to no avail. I deleted my Solution, made a new one, and imported everything, to no avail. Note that I always Add an external resource from within Visual Studio.

I'm honestly not sure what to do at this point. Why is it serving a 3-week old web page? Why does the text and everything else update, but not the image (not even the alt text)? I've checked the filenames dozens of times, and even used copy paste--to no avail.

I set the permissions to Everyone on each file. I thought it might be the browser blocking a local file--I'm running this on my laptop--but it still happens. I thought running on IIS would fix that. I disabled Safe Mode in Chrome, but it still didn't work.

I've been developing for 3 years, and I've never seen anything like this.

7 Comments
2025/02/04
17:35 UTC

0

Tool to create API Messages

I am working with some legacy code and I need to create a significant number of json messages for api testing. I need them to be have accdurate ID's of items in a DB. Is there a tool that can connect to my DB and my code that can auto-generate valid messages? A long time ago I think I used a tool called SOAP UI on a project.

6 Comments
2025/02/04
16:08 UTC

0

.NET API Backend for AI Chat - Azure.AI.OpenAI vs Microsoft.Extensions.AI?

What are the differences between these two nuget packages: Azure.AI.OpenAI vs Microsoft.Extensions.AI? I'm building an API for the backend of an AI chat application. It will need to implement Bring Your Own Data and RAG.

4 Comments
2025/02/04
15:45 UTC

0

Best Approach for Scanning PDF Files for Viruses in an Azure Cloud Application

Hello, tech folks!

I’m currently working on an issue where I’m stuck choosing the right approach for scanning PDF files for viruses. Our application is hosted in Azure Cloud, so installing any software or tool is not an option. Additionally, the customer does not allow the use of external APIs.

Azure’s built-in scanning could be an option, but our uploaded files are stored in a database rather than on a server. Given these constraints, what would be the best approach to implement antivirus scanning for uploaded PDF files?

Looking forward to your suggestions!

16 Comments
2025/02/04
14:03 UTC

0

Is there a way to import/convert existing FastReport.Net reports into the Telerik.Net reporting tool??

My company is ditching Fast Reports as our clients don't want a Russian owned product integrated with our software so we are moving to Telerik, we have 1000's of Fast Reports that I've been told all need to be redone in Telerik. Surely there is a way to repurpose the existing Fast Reports and not have to redo them all from scratch???

4 Comments
2025/02/04
13:58 UTC

0

I'm learning microservices, and I'm a little confused.

I'm following this course:
https://www.youtube.com/watch?v=Nw4AZs1kLAs

Where he uses a Frontend, Gateway, Integration, Services folder structure.

But in the Frontend folder he uses a Web app, which is a frontend and backend project, he does some work on the backend of the web app project.

I want to use React instead of the web app frontend, and the question is..
Should I make a separate Asp.net api backend for the React project? And if yes, in what folder should I add it, in the Gateway, Frontend or microservices folder? xD
Which will then communicate with the Gateway to redirect the requests to the right microservice?
Is this the correct approach with React instead of Asp.net Web app, to still make a backend for the React application?
I've only built MVC Web apps until now, with Razor pages, and now I'm trying to level up my skills and learn React, microservices and JWT tokens, and I'm confused if my logic is right, and the React + Asp.net web api backend is the correct approach, or you should do something else when using React.

11 Comments
2025/02/04
10:43 UTC

0

Looking for a Complete ASP.NET Core Web API Course for E-Commerce System

I'm looking for a comprehensive course that uses ASP.NET Core Web API to build a complete e-commerce system. Do you have any recommendations for a course or any useful resources to help with this?

3 Comments
2025/02/04
08:33 UTC

0

.NET 8 Blazor Server with SignalR Client Question

Has anyone built a .NET 8 Blazor server that accesses a SignalR hub from a .NET web api?
I've been searching for the answer to this for a little while but I'm falling at the first hurdle. As soon as I add the Microsoft.AspNetCore.SignalR.Client to the Blazor project, none of the buttons that interact with Blazor server work any more. This is even the case on a brand new Blazor project, adding the package breaks the sample counter page button.
Does anyone know the solution to this?

2 Comments
2025/02/04
07:48 UTC

29

Best HTML to PDF Library for C# (.NET Core)?

I need to convert invoices with dynamic tables and complex CSS (flexbox, grid) to PDF in C# .NET Core. wkhtmtopdf struggles with modern layouts, and DinkToPDF fails with high DPI images. Considering IronPDF or Syncfusion or Aspose - any better options? What works best for accurate rendering and performance?

29 Comments
2025/02/04
06:51 UTC

0

Does anyone have experience creating native mobile apps with .net IOS and .net Android (not MAUI)

I have a desktop app written in C# (using Avalonia) and now need to build a companion mobile app. I have a LOT of business code and a custom websocket framework in a shared c# library.

After much evaluation I have decided that MAUI is completely out, not an option. Too many issues and poor performance. MAUI Blazor is also likely not an option, although its much better of a choice than regular MAUI. UNO as well is not an option. Android performance too poor. I am currently in between creating native apps with .net IOS and .net Android templates, or going with flutter and using AI to help me transfer the business logic over to Dart.

There doesn't seem to be a lot of documentation on .net IOS and Android, as it replaced Xamarin, but Microsoft just went full steam ahead with MAUI. I do not mind writing the view layer twice in android xml and ios storyboards if I save time vs re-writing all my business logic in Dart (Flutter).

My app needs to be able to handle files and photo uploads, send notifications, as well as integrate with the share system on the device. Has anyone made a good sized app using pure native with C#?

7 Comments
2025/02/04
05:39 UTC

22

think using stored procedures for complex queries combined with Dapper is a good implementation (opinions)

I think using stored procedures for complex queries combined with Dapper is a good implementation since it takes advantage of the query execution plan of SQL Server, but I would like to hear your opinions. Thank you very much, how would you approach it?

109 Comments
2025/02/04
04:31 UTC

183

How many .NET devs wish there were more Blazor jobs?

I've been using Blazor in a small dotnet shop for about 3 years and I love it. I'm so disappointed at how rarely it shows up in keyword searches.

Anyone else?

112 Comments
2025/02/04
02:39 UTC

0

Odd nuget error

Removed a JsonConverter (string β†’ enum) from a specific enum, and now a private dependency in another project in our repo failsβ€”but only when building our prod Docker image. Works fine locally.

Putting the converter back fixes it, even though the projects seem unrelated.

Anyone seen this before?

2 Comments
2025/02/04
01:26 UTC

3

ServiceProvider.GetServices with Open Types

So I am trying to retrieve all instances of a registered service that implements an interface<T> where T is a base class so I can read all the implementations of T being handled.

So far I have tried:

var registeredInstances = _serviceProvider.GetServices(typeof(IMyInterface<MyBaseClass>)).ToList();

var registeredInstances = _serviceProvider.GetServices(typeof(IMyInteface<>)).ToList();

First one returns no results, second one errors as GetServices cannot use open types. What am I missing here?

9 Comments
2025/02/04
00:18 UTC

0

Xunit Dependency Injection framework - .NET 9.0

Build Status Nuget Nuget

Xunit Dependency Injection framework - .NET 9.0

Xunit does not support any built-in dependency injection features, therefore developers have to come up with a solution to recruit their favourite dependency injection framework in their tests.

This library brings in Microsoft's dependency injection container to Xunit by leveraging Xunit's fixture.

Getting started

Nuget package

First add the following nuget package to your Xunit project:

Install-Package Xunit.Microsoft.DependencyInjection

Setup your fixture

The abstract class of Xunit.Microsoft.DependencyInjection.Abstracts.TestBedFixture contains the necessary functionalities to add services and configurations to Microsoft's dependency injection container. Your concrete test fixture class must derive from this abstract class and implement the following two abstract methods:

protected abstract void AddServices(IServiceCollection services, IConfiguration? configuration);
protected abstract IEnumerable<TestAppSettings> GetTestAppSettings();
protected abstract ValueTask DisposeAsyncCore();

GetConfigurationFiles(...) method returns a collection of the configuration files in your Xunit test project to the framework. AddServices(...) method must be used to wire up the implemented services.

Secret manager

Secret manage is a great tool to store credentials, api keys and other secret information for development purpose. This library has started supporting user secrets from version 8.2.0 onwards. To utilize user secrets in your tests, simply override the virtual method below from TestBedFixture class:

protected override void AddUserSecrets(IConfigurationBuilder configurationBuilder); 

Access the wired up services

There are two method that you can use to access the wired up service depending on your context:

public T GetScopedService<T>(ITestOutputHelper testOutputHelper);
public T GetService<T>(ITestOutputHelper testOutputHelper);

To access async scopes simply call the following method in the abstract fixture class:

public AsyncServiceScope GetAsyncScope<T>(ITestOutputHelper testOutputHelper)

Accessing the keyed wired up services in .NET 9.0

You can call the following method to access the keyed already-wired up services:

T? GetKeyedService<T>([DisallowNull] string key, ITestOutputHelper testOutputHelper);

Adding custom logging provider

Test developers can add their own desired logger provider by overriding AddLoggingProvider(...) virtual method defined in TestBedFixture class.

Preparing Xunit test classes

Your Xunit test class must be derived from Xunit.Microsoft.DependencyInjection.Abstracts.TestBed<T> class where T should be your fixture class derived from TestBedFixture.

Also, the test class should be decorated by the following attribute:

[CollectionDefinition("Dependency Injection")]

Clearing managed resources

To have managed resources cleaned up, simply override the virtual method of Clear(). This is an optional step.

Clearing managed resourced asynchronously

Simply override the virtual method of DisposeAsyncCore() for this purpose. This is also an optional step.

Running tests in order

The library also has a bonus feature that simplifies running tests in order. The test class does not have to be derived from TestBed<T> class though and it can apply to all Xunit classes.

Decorate your Xunit test class with the following attribute and associate TestOrder(...) with Fact and Theory:

[TestCaseOrderer("Xunit.Microsoft.DependencyInjection.TestsOrder.TestPriorityOrderer", "Xunit.Microsoft.DependencyInjection")]

Supporting configuration from UserSecrets

This library's TestBedFixture abstract class exposes an instance of IConfigurationBuilder that can be used to support UserSecrets when configuring the test projects:

public IConfigurationBuilder ConfigurationBuilder { get; private set; }

Examples

  • Please follow this link to view a couple of examples on utilizing this library.
  • Digital Silo's unit tests and integration tests are using this library.

One more thing

Do not forget to include the following nuget packages to your Xunit project:

  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Options
  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.Logging
  • Microsoft.Extensions.Configuration.EnvironmentVariables
5 Comments
2025/02/04
00:11 UTC

329

In .NET 10, the compiler team aim to reduce abstraction overhead

Seen this interesting issue on GH about the abstraction penalty, it might be interesting to devs here.

In .NET 10, the compiler team are aiming to further reduce abstraction related overhead from our code
Currently iterating an array via IEnumerable is a lot slower than iterating the array directly.

Issue on GH -> https://github.com/dotnet/runtime/issues/108913

https://preview.redd.it/dype2p6i30he1.png?width=803&format=png&auto=webp&s=c859df0225f9569bdc1726361106bc311da10efb

This benchmark I took showed the gap when using the interface has come down a lot since v 6.

https://preview.redd.it/pxm4jcwx30he1.png?width=1166&format=png&auto=webp&s=cd357b3764ab2c1034487d2dfa33fe124cea1472

32 Comments
2025/02/03
22:35 UTC

0

Receiving Error Requiring Primary Key for ClientOptions which is Not One of My Models

I'm really new to using Postgresql with my Api.Net Core.

I am getting an error when trying to retrieve data from my database:

Error: InvalidOperationException: The entity type 'ClientOptions' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'.

I do not have a model called ClientOptions and looking online it's some internal file.

If I am not framing this in the right way, please let me know. And if there is any other logic that would

DbContext:
public class DmkInfoContext : DbContext

{

public DmkInfoContext (DbContextOptions<DmkInfoContext> options)

: base(options)

{

}

public DbSet<Characters> Characters { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<Characters>()

.HasKey(e => e.Id);

// entity.Property(e => e.Name).IsRequired();

}

}

Model:

public class Characters:BaseModel

{

[Key]

public int Id { get; set; }

[Column("character_name")]

public required string Name { get; set; }

Index:

public class IndexModel : PageModel

{

private readonly DmkInfoContext _context;

public IndexModel(DmkInfoContext context)

{

_context = context;

}

public IList<Characters> Characters { get;set; }

public async Task OnGetAsync()

{

try

{

Characters = await _context.Characters.ToListAsync();

}

catch (Exception ex)

{

Console.WriteLine(ex.ToString());

}

}

}

3 Comments
2025/02/03
21:27 UTC

15

Without lines between class members

I am currently working with someone who likes to not add any new lines between class members.

For example:

public class MyClass
{
    private const string Foo = "";
    private readonly string _myfield;
    public MyClass()
    {

    }
    // This is method 1
    public void Method1()
    {

    }
    private void InternalMethod1()
    {

    }
}

I work with someone who does this and it drives me nuts. I cannot find a formatter with inserts new lines in between.

Do I just give up the fight and live with this?

28 Comments
2025/02/03
21:26 UTC

0

Keycloak template

I am looking for an implementation of keycloak that has multitenancy in .net.

4 Comments
2025/02/03
19:41 UTC

0

.net api implementing oauth 2.0

i am trying to implement oauth in my .net api with ef , i already done my custom local authentication with jwt tokens and refresh tokens . i got a little bit confused to how i would approach it .

let me show you my implementation for the google oauth system (i also use facebook oauth but it's kinda the same thing) :

\``csharp`

[HttpGet("google-login")]

[AllowAnonymous]

public IActionResult GoogleLogin([FromQuery] string returnUrl)

{

var redirectUrl = Url.Action(nameof(GoogleResponse), "Auth", new { returnUrl }, Request.Scheme);

var properties = new AuthenticationProperties { RedirectUri = redirectUrl };

return Challenge(properties, GoogleDefaults.AuthenticationScheme);

}

[HttpGet("signin-google")]

[AllowAnonymous]

public async Task<IActionResult> GoogleResponse([FromQuery] string returnUrl)

{

var authenticateResult = await HttpContext.AuthenticateAsync(GoogleDefaults.AuthenticationScheme);

if (!authenticateResult.Succeeded)

return BadRequest("Google authentication failed.");

var claims = authenticateResult.Principal.Identities.FirstOrDefault()?.Claims;

var email = claims?.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;

var name = claims?.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

var key = claims?.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;

var ipAddress = HttpContext.Connection.RemoteIpAddress?.MapToIPv6().ToString();

if (string.IsNullOrEmpty(email))

return BadRequest("Email not found");

var result = await authService.SignInWithProviderAsync(email, key, ipAddress, "google");

return result.Match<IActionResult, OauthResponse>(success =>

{

var result = success.Data;

SetAccessTokenInResponse(result.Jwt);

SetRefreshTokenInResponse(result.RefreshToken);

var redirectUri = $"{returnUrl}?access_token={result.Jwt}&refresh_token={result.RefreshToken}";

return Redirect(redirectUri);

}, BadRequest);

}

\```

and this is the program.cs setting for oauth

```

builder.Services.AddAuthentication(options =>

{

options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

})

.AddJwtBearer(options =>

{

options.TokenValidationParameters = new TokenValidationParameters

{

ValidateIssuer = true,

ValidateAudience = true,

ValidateLifetime = true,

ValidateIssuerSigningKey = true,

ValidIssuer = builder.Configuration["JwtConfig:Issuer"],

ValidAudience = builder.Configuration["JwtConfig:Audience"],

IssuerSigningKey = new SymmetricSecurityKey(

Encoding.UTF8.GetBytes(builder.Configuration["JwtConfig:Key"]))

};

options.Events = new JwtBearerEvents

{

OnMessageReceived = context =>

{

context.Token = context.Request.Cookies["tmy209w1"];

return Task.CompletedTask;

}

};

})

.AddGoogle(options =>

{

options.ClientId = builder.Configuration["Authentication:Google:ClientId"];

options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];

options.CallbackPath = "/signin-google";

options.SaveTokens = false;

})

.AddFacebook(options =>

{

options.ClientId = builder.Configuration["Authentication:Facebook:AppId"];

options.ClientSecret = builder.Configuration["Authentication:Facebook:AppSecret"];

i am not sure if this is how it's supposed to go so correct me if anything is wrong with the implementation , anyway

i dont want to use the token / cookie that the o auth middleware issues because i already have a custom token that i want to issue to the user , but i keep finding this persistent cookie name identity.external and i dont know why it's persisting.

so please help me get this to work properly the way it's meant to work

6 Comments
2025/02/03
19:35 UTC

0

How can I find freelancing work from outside India ?

1 Comment
2025/02/03
18:05 UTC

Back To Top