Natro
Natro
Explore posts from servers
CC#
Created by Natro on 6/29/2024 in #help
Job scheduling: Quartz vs Hangfire vs ?
Hey, I am going to be implementing a service which has multiple triggers - e.g. api, chain jobs, cron. I am currently deciding between Hangfire and Quartz. I am noticing that Quartz has a bit more boilerplate code in my opinion with JobStore, etc. compared to Hangfire. So setup is much more easier. Additionally, Hangfire has UI for monitoring. Is there something that Quartz can do and Hangfire can't? And the other way around? Which solution does the community prefer and why? (Is there maybe some other solution that I haven't looked into?)
1 replies
CC#
Created by Natro on 5/8/2024 in #help
Streaming 3D content to frontend
Hey, I started a side project where the endgoal is streaming 3D gltf object to frontend and render a 3D city in web via WebGL. I am using a dataset in so-called CityGML format which can be transformed into gltf models. This transformation should be deterministic, so I should be able to do it once and then save those objects. Any ideas or tips on what I should look into when storing and streaming this kind of data? I suppose I am just going to end up with postgres (with postgis) database that based on coordinates gets these files and then sends it to frontend. (Planning to send so-called "3d tiles" which are basically chunks of the city) But maybe there are some technologies I don't know about 🙂
1 replies
CC#
Created by Natro on 4/21/2024 in #help
Receiving 400 on production, local env works fine
Hey, I have same ASP.NET Core app running both on my localhost and on production (docker). The only difference between the two are environment variables (aspnet env - release for prod and development for localhost). When I run following powershell to call one of my endpoints:
$headers = @{
'accept' = '*/*'
'Content-Type' = 'application/json'
}
$body = @{
'nonce' = '7ba0879e-476e-4962-85b9-9d36be449d21'
'integrationType' = 'Slack'
}
Invoke-RestMethod -Uri 'https://localhost:8084/Integration' -Method 'POST' -Headers $headers -Body ($body | ConvertTo-Json)
Invoke-RestMethod -Uri 'https://{obfuscated}/Integration' -Method 'POST' -Headers $headers -Body ($body | ConvertTo-Json)
$headers = @{
'accept' = '*/*'
'Content-Type' = 'application/json'
}
$body = @{
'nonce' = '7ba0879e-476e-4962-85b9-9d36be449d21'
'integrationType' = 'Slack'
}
Invoke-RestMethod -Uri 'https://localhost:8084/Integration' -Method 'POST' -Headers $headers -Body ($body | ConvertTo-Json)
Invoke-RestMethod -Uri 'https://{obfuscated}/Integration' -Method 'POST' -Headers $headers -Body ($body | ConvertTo-Json)
The localhost goes through and production throws:
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ProblemDetails'.
Executed action {obfuscated}.IntegrationController.MatchIdentityAsync ({obfuscated}) in 26.5296ms
Executed endpoint '{obfuscated}.Controllers.IntegrationController.MatchIdentityAsync ({obfuscated})'
HTTP POST /Integration responded 400 in 37.0021 ms
Request finished HTTP/1.1 POST http://{obfuscated}/Integration - 400 null application/problem+json; charset=utf-8 37.7163ms
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ProblemDetails'.
Executed action {obfuscated}.IntegrationController.MatchIdentityAsync ({obfuscated}) in 26.5296ms
Executed endpoint '{obfuscated}.Controllers.IntegrationController.MatchIdentityAsync ({obfuscated})'
HTTP POST /Integration responded 400 in 37.0021 ms
Request finished HTTP/1.1 POST http://{obfuscated}/Integration - 400 null application/problem+json; charset=utf-8 37.7163ms
This is how my controller looks:
[ApiController]
[Route("[controller]")]
public class IntegrationController : ControllerBase
{
// ...

[HttpPost]
// [Authorize]
public async Task<IActionResult> MatchIdentityAsync([FromBody] IntegrationAuthDTO reqDTO)
{
_logger.LogInformation($"Matching identity, Nonce - {reqDTO.Nonce}, Integration - {reqDTO.IntegrationType}");
}
}

// IntegrationAuthDTO
public class IntegrationAuthDTO
{
public string Nonce { get; set; } = default!;
public string IntegrationType { get; set; } = default!;
}
[ApiController]
[Route("[controller]")]
public class IntegrationController : ControllerBase
{
// ...

[HttpPost]
// [Authorize]
public async Task<IActionResult> MatchIdentityAsync([FromBody] IntegrationAuthDTO reqDTO)
{
_logger.LogInformation($"Matching identity, Nonce - {reqDTO.Nonce}, Integration - {reqDTO.IntegrationType}");
}
}

// IntegrationAuthDTO
public class IntegrationAuthDTO
{
public string Nonce { get; set; } = default!;
public string IntegrationType { get; set; } = default!;
}
Any ideas why this is happening?
19 replies
CC#
Created by Natro on 4/13/2024 in #help
ngrok - How to listen on webhook requests locally (docker)?
Hey, I have ASP.NET app that is listening on Slack webhook requests. How can I debug this locally? I know there is this thing called tunnels which exists in Visual Studio. This is my Dockerfile: My dockerfile:
# Used for docker-compose and running of app

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["./PyriteDocs.Api.csproj", "PyriteDocs.Api/"]
COPY ["../PyriteDocs.Shared/PyriteDocs.Shared.csproj", "PyriteDocs.Shared/"]

RUN dotnet restore "./PyriteDocs.Api/PyriteDocs.Api.csproj"

COPY . .
WORKDIR "/src/PyriteDocs.Api"
RUN dotnet build "./PyriteDocs.Api.csproj" -c $BUILD_CONFIGURATION -o /app/build

FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./PyriteDocs.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "PyriteDocs.Api.dll"]
# Used for docker-compose and running of app

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["./PyriteDocs.Api.csproj", "PyriteDocs.Api/"]
COPY ["../PyriteDocs.Shared/PyriteDocs.Shared.csproj", "PyriteDocs.Shared/"]

RUN dotnet restore "./PyriteDocs.Api/PyriteDocs.Api.csproj"

COPY . .
WORKDIR "/src/PyriteDocs.Api"
RUN dotnet build "./PyriteDocs.Api.csproj" -c $BUILD_CONFIGURATION -o /app/build

FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./PyriteDocs.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "PyriteDocs.Api.dll"]
6 replies
CC#
Created by Natro on 4/1/2024 in #help
Migrating to Microsoft.IdentityModel.JsonWebTokens .net6 => .net8
Hi, I am migrating a project which uses Duende as identity server + Ocelot gateway from .NET 6 to .NET 8. In Ocelot AuthorizationMiddleware project uses JWT subclaims and tries to access them like this:
var subClaimValue = user.Claims.FirstOrDefault(x => x.Type == CommonConstants.ClaimSub)?.Value; // "sub"
roleType = user.Claims.FirstOrDefault(x => x.Type == CommonConstants.ClaimRoleType)?.Value; // "roleType"
var subClaimValue = user.Claims.FirstOrDefault(x => x.Type == CommonConstants.ClaimSub)?.Value; // "sub"
roleType = user.Claims.FirstOrDefault(x => x.Type == CommonConstants.ClaimRoleType)?.Value; // "roleType"
I noticed that after migrating I was receiving error when authenticating users regarding Signature {"IDX10500: Signature validation failed. No security keys were provided to validate the signature."}. Stack overflow hinted me to removing System.IdentityModel.Tokens.Jwt package and moving to Microsoft.IdentityModel.JsonWebTokens as there has been breaking change in aspnet core. https://github.com/dotnet/aspnetcore/issues/52075#issuecomment-1815025177 ...
2 replies
CC#
Created by Natro on 3/24/2024 in #help
How to debug webhook locally (docker)?
Hey, I have a ASP.NET Core application running through docker-compose. I am wondering if there is a way to test webhooks locally. I am trying to integrate with clerk.com webhooks. My initial idea is to add nginx into my docker-compose and sign a certificate. Is that a viable solution or is there something easier and quicker?
5 replies
CC#
Created by Natro on 1/3/2024 in #help
Repo pattern - is it okay to call one repo from multiple services?
Hi, pretty much the title summarizes it all. In one code base I am refactoring I am seeing a lot of calling from multiple services classes to one repository - most likely to bypass circular dependencies. Is it a good practice? Why yes? Why not? I usually try to keep calls between services to make sure business logic is checked at all times.
17 replies
CC#
Created by Natro on 1/1/2024 in #help
No error log - app quits (async problem?)
Hey, I am working on an app that has multiple background workers:
List<Tasks> tasks = [];
foreach (var item in items)
{
// Could be I am doing this wrong? I am learning async as I go
tasks.Add(Task
.Run(async () => await StepOne(foo))
.ContinueWith(async x => await StepTwo(boo));
}

await Task.WhenAll(tasks);
// End app
List<Tasks> tasks = [];
foreach (var item in items)
{
// Could be I am doing this wrong? I am learning async as I go
tasks.Add(Task
.Run(async () => await StepOne(foo))
.ContinueWith(async x => await StepTwo(boo));
}

await Task.WhenAll(tasks);
// End app
StepOne works correctly, in StepTwo I am calling OpenAI API via this NuGet (https://github.com/OkGoDoIt/OpenAI-API-dotnet).
// OAI is just wrapper around OpenAPI NuGet
await OAI.Service.TextToSpeech.SaveSpeechToFileAsync(new TextToSpeechRequest()
{
Input = "Lorem ipsum",
ResponseFormat = ResponseFormats.MP3,
Model = Model.TTS_HD,
Voice = Voices.Shimmer,
Speed = 1.1,
}, outputFile);
// OAI is just wrapper around OpenAPI NuGet
await OAI.Service.TextToSpeech.SaveSpeechToFileAsync(new TextToSpeechRequest()
{
Input = "Lorem ipsum",
ResponseFormat = ResponseFormats.MP3,
Model = Model.TTS_HD,
Voice = Voices.Shimmer,
Speed = 1.1,
}, outputFile);
On this line my app (Console application) just turns off - no error log, nothing. So I tried doing try-catch block - nothing. I debugged and figured out problem is here (L133): https://github.com/OkGoDoIt/OpenAI-API-dotnet/blob/5f7c23a928be39da87e89d5105a044ecb7401727/OpenAI_API/EndpointBase.cs#L133 It's being called with following:
req: {Method: POST, RequestUri: 'https://api.openai.com/v1/audio/speech', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: application/json; charset=utf-8
}}
streaming: false
req: {Method: POST, RequestUri: 'https://api.openai.com/v1/audio/speech', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: application/json; charset=utf-8
}}
streaming: false
Seems to be correct (calling other endpoint with same NuGet - e.g. chat completion works) I cloned the repo, put try-catch block around that line - still nothing. When trying to debug the HttpClient method my debugger is just jumping all around place without sense. I guess I would have to get the code of HttpClient locally and do it like that - but at that point I am wondering. Anyone has idea why this is happening? I expect it's because of how I use Tasks? I am clueless here, not getting any output or error anywhere :/
19 replies
CC#
Created by Natro on 12/19/2023 in #help
What's correct unit testing?
In codebase I am working on some devs are writing unit tests that test Controller level - tests if endpoint returns 200 for example. They mock repository/DAL layer and ignore service layer. Wouldn't the correct thing to do be just mock the service layer and then test service layer functions separately and mock repo layer in that test?
25 replies
CC#
Created by Natro on 6/13/2023 in #help
❔ Include .xml file in Nuget
Hey, I have two .NET Framework projects. One references (A) the other (B) as nuget package reference. When building A project I get B.dll in my bin/Debug folder buy noy B.xml file. Is there have .xml included as well?
7 replies
CC#
Created by Natro on 5/11/2023 in #help
❔ Parsing inconsistent PDFs
3 replies
CC#
Created by Natro on 5/5/2023 in #help
✅ EF Json column - object reference not set to an instance of an object
Hey, I am trying to get JSON columns work with EF.
Microsoft.EntityFrameworkCore - 7.0.2
Microsoft.EntityFrameworkCore.Design - 7.0.2
Microsoft.EntityFrameworkCore.Tools - 7.0.2
Pomelo.EntityFrameworkCore.MySql - 7.0.0 (Probably not relevant as I fail on first migration)
Microsoft.EntityFrameworkCore - 7.0.2
Microsoft.EntityFrameworkCore.Design - 7.0.2
Microsoft.EntityFrameworkCore.Tools - 7.0.2
Pomelo.EntityFrameworkCore.MySql - 7.0.0 (Probably not relevant as I fail on first migration)
When creating my initial migration I am met with: Object reference not set to an instance of an object
public class AppDbContext : DbContext
{
internal DbSet<Store> Stores => Set<Store>();

public AppDbContext(DbContextOptions options)
: base(options)
{ }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Store>()
.OwnsOne(store => store.Address, builder => builder.ToJson());
}
}

public class Store
{
[Key]
public int Id { get; set; }

/* Some other properties */

// When line below is commented migration is generated without fail
public AddressData Address { get; set; }
}

public class AddressData
{
public string Country { get; set; }
public string Region { get; set; }
public string Postcode { get; set; }
public string District { get; set; }
public string Place { get; set; }
public string Locality { get; set; }
public string Neighborhood { get; set; }
public string Address { get; set; }
public string Poi { get; set; }
}
public class AppDbContext : DbContext
{
internal DbSet<Store> Stores => Set<Store>();

public AppDbContext(DbContextOptions options)
: base(options)
{ }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Store>()
.OwnsOne(store => store.Address, builder => builder.ToJson());
}
}

public class Store
{
[Key]
public int Id { get; set; }

/* Some other properties */

// When line below is commented migration is generated without fail
public AddressData Address { get; set; }
}

public class AddressData
{
public string Country { get; set; }
public string Region { get; set; }
public string Postcode { get; set; }
public string District { get; set; }
public string Place { get; set; }
public string Locality { get; set; }
public string Neighborhood { get; set; }
public string Address { get; set; }
public string Poi { get; set; }
}
Migration only fails when I include Adress part of Store. Any ideas what could be the issue?
12 replies
CC#
Created by Natro on 1/12/2023 in #help
✅ .NET 7 with Visual Studio 2019
Hello, I have licenses for Visual Studio 2019 and so far I have been working on old solutions using .NET Framework. I am in need of .NET 7 - I was looking at Microsoft pages but it says that .NET 7 SDK is only for Visual Studio 2022. What now?
3 replies
CC#
Created by Natro on 12/26/2022 in #help
❔ ✅ Applying math to programming
Hi, this is not necessarily a C# question and more question towards math and programming. I am using C# as my language so I hope it's okay to ask this here. I have always been struggling with applying math equations and so on to programming and I am finally tackling this mental block I have and trying to force myself to learn more. I have a 2 dimensional array (grid) of 0 or 1 (which size is set dynamically) I would like to use x^4 + y^4 = 1 to fill it out. https://www.wolframalpha.com/input?i=x%5E4+%2B+y%5E4+%3D+1 How can I draw this shape in it? I would also like to go beyond and how could I fill it out or reverse fill it out in my grid? Just a small pointer on how to use math to achieve some different result would help help so much. Thank you. Example (With bigger size edges would be smoother):
1 1 1 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0 1 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 1 0 0 0 0 0 0 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0 1 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 1
1 1 0 0 0 0 0 0 1 1
1 1 1 1 1 1 1 1 1 1
11 replies
CC#
Created by Natro on 12/7/2022 in #help
✅ string.Join returns System.Int32[]
21 replies
CC#
Created by Natro on 11/10/2022 in #help
❔ ASP.NET Core Middleware running only once
Hello! I have a custom middleware that runs only once and isn't running on every request. When I put breakpoint into my pipeline or into my custom middleware it won't break or run. Any ideas why?
var builder = WebApplication.CreateBuilder(args);

// Other stuff

builder.Services.AddCurUserCookie();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Error");

app.UseRequestLogger();

app.UseStaticFiles();

app.UseCors();
app.UseAuthentication();
app.UseAuthorization();

// My custom middleware
app.UseCurUserCookie();

app.MapControllers();

app.Run();
var builder = WebApplication.CreateBuilder(args);

// Other stuff

builder.Services.AddCurUserCookie();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
app.UseExceptionHandler("/Error");

app.UseRequestLogger();

app.UseStaticFiles();

app.UseCors();
app.UseAuthentication();
app.UseAuthorization();

// My custom middleware
app.UseCurUserCookie();

app.MapControllers();

app.Run();
public interface ICurUserCookie
{
int CurUserId { get; set; }
}

public class CurUserCookie : ICurUserCookie
{
public int CurUserId { get; set; }
}

public static class CurUserCookieEx
{
public static void AddCurUserCookie(this IServiceCollection services)
{
services.AddScoped<ICurUserCookie, CurUserCookie>();
}

public static void UseCurUserCookie(this IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
// Do stuff here

await next();
});
}
}
public interface ICurUserCookie
{
int CurUserId { get; set; }
}

public class CurUserCookie : ICurUserCookie
{
public int CurUserId { get; set; }
}

public static class CurUserCookieEx
{
public static void AddCurUserCookie(this IServiceCollection services)
{
services.AddScoped<ICurUserCookie, CurUserCookie>();
}

public static void UseCurUserCookie(this IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
// Do stuff here

await next();
});
}
}
11 replies
CC#
Created by Natro on 9/23/2022 in #help
Cookies not being set on localhost
Hi! I am setting my cookie on my ASP.NET Core backend:
CookieOptions cookieOptions = new CookieOptions
{
HttpOnly = true,
Expires = DateTime.UtcNow.AddMinutes(60000)
};

this.Response.Cookies.Append("PT", "authtokenhere", cookieOptions);
CookieOptions cookieOptions = new CookieOptions
{
HttpOnly = true,
Expires = DateTime.UtcNow.AddMinutes(60000)
};

this.Response.Cookies.Append("PT", "authtokenhere", cookieOptions);
I am running create-react-app on my frontend and I am receiving this cookie in response in the headers. The problem is that the cookie is not being set into cookies when inspecting it in browser and is also not being sent in next API requests. Frontend: http://localhost:3001/login - where request is being sent from Backend: http://localhost:39500/account/login - API I tried several settings for the cookie, playing with SameSite and Secure but nothing seems to be working? How can I make cookies work when working on localhost?
58 replies