oe
oe
CC#
Created by oe on 3/22/2024 in #help
IIS Cold Start / State Issues After 10 Minutes
I'm having "cold start/state" issues with my IIS (& ASP.NET Core API). After around 10 minutes of idleness, if I make a request to my IIS, I get issue "curl: (6) Could not resolve host: curl. curl: (56) Recv failure: Connection was reset" OR on Fiddler "HTTP/1.1 504 Fiddler - Receive Failure". After making that request, if I make more requests, it works fine. It's just the first request that doesn't work. I have tried everything I have found: StartMode to AlwaysRunning, doAppInitAfterRestart (preload) with a non authenticated controller/endpoint, setting application pool idle timeout to 0 (and process suspended instead of terminated), disabling application pool recycling (set to 0) Extra context in case it helps: - I am using BasicAuthentication (configured in code) - https://raw.githubusercontent.com/cornflourblue/aspnet-core-basic-authentication-api/master/Helpers/BasicAuthenticationHandler.cs - I am using Entity Framework Core & SQL Server (injected into the controller from the endpoint I am calling) - I am using IIS on Win Server 2022. Jenkins for CI/CD. Don't use linux because I have unit tests with Selenium/Chrome automations, which I want to be able to see in action. Don't use Kestrel since I have found it really hard to integrate with Jenkins (for start/stop), and since I like hosting my Angular app in the same "context/program" Since using IIS I have had nothing but headaches. I have worked with Python/Flask, Gunicorn, Jenkins and its been a breeze, but I really wanted to make .NET work for my startup, so I've pushed on and on through headache and headache. I cannot for the life of me sort this last issue out. Any help would be incredibly appreciated
73 replies
CC#
Created by oe on 1/14/2024 in #help
Entity Framework Cascade Delete Issues
Hi guys, I want to be able to save this as a single operation:
DBContext:
public DbSet<ProductNode> ProductNodes { get; set; } = null!;
public DbSet<VirtualStore> VirtualStore { get; set; } = null!;
modelBuilder.Entity<ProductNode>()
.HasOne(lpn => lpn.VirtualProduct)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);

....
BackgroundService:
vphContext.VirtualStore.RemoveRange(virtualStoresInUse);
vphContext.ProductNodes.RemoveRange(nodesToRemove);
await vphContext.SaveChangesAsync(stoppingToken);

vphContext.VirtualStore.AddRange(newStores);
vphContext.ProductNodes.AddRange(newProductNodes);
await vphContext.SaveChangesAsync(stoppingToken);
DBContext:
public DbSet<ProductNode> ProductNodes { get; set; } = null!;
public DbSet<VirtualStore> VirtualStore { get; set; } = null!;
modelBuilder.Entity<ProductNode>()
.HasOne(lpn => lpn.VirtualProduct)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);

....
BackgroundService:
vphContext.VirtualStore.RemoveRange(virtualStoresInUse);
vphContext.ProductNodes.RemoveRange(nodesToRemove);
await vphContext.SaveChangesAsync(stoppingToken);

vphContext.VirtualStore.AddRange(newStores);
vphContext.ProductNodes.AddRange(newProductNodes);
await vphContext.SaveChangesAsync(stoppingToken);
However, for some reason, ProductNodes does not get re-added if I remove the first "SaveChangesAsync". The reason I want it in a single operation, is I don't want downtime where there is no VirtualStore list or ProductNode list between the both operations.
1 replies
CC#
Created by oe on 12/5/2023 in #help
Track Thread/Task Progress through SignalR/WebSockets
I have an ASP.NET Web Core API and an Angular project both connected. In the dashboard of my Angular app, I want to have a section where I can see all the tasks that are running, and what exactly they are executing. For example, if I call endpoint /CreateTask, it will fire off a webrequest every second for 60 seconds, and when the status property acquired from the http response is complete, it will save it in the database, then send an email etc (I just made this up). I want to be able to see in my dashboard: TaskName | CurrentAction CreateTask-1512 | StartRequestLoop() CreateTask-5191 | AddToDatabase() I have thought of the following: - Launch a thread at the very start of the WebAPI launch. - Within this thread, start a WebSocket/SignalR - Every X seconds, query all the open Threads (maybe there some library/.NET api for this?) and collect their ID & stacktrace, then format the stacktrace so it prints out JustMyCode (the first method call from my own code) and post it to SignalR - Connect to SignalR/WebSocket in Angular and show table I think my approach seems viable, although I wonder if I could be doing something in an easier/more efficient way? Any suggestions are greatly appreciated
2 replies
CC#
Created by oe on 11/16/2023 in #help
Refactoring Injected Singleton for Authentication and HttpClient Usage
Everytime a TestPaymentsService is created, it should be authenticated. Instead of constantly calling .Authenticate, I want to be able to do it once at the start of my app's lifetime. Instead of firing off a web request in the constructor (since it cannot be async), I decided to create a static create method that creates the instance to be able to authenticate. However, I now realised its a bad practice to recreate a HttpClient in every method inside TestPaymentsService. Although I registered a IHttpClientFactory using builder.Services.AddHttpClient(); in Program.cs, I cannot inject it since I dont have a constructor. I want to be able to create a TestPaymentsService, inject it into DI and use it wherever I want without having to call Authenticate method each time, since it was called at the very beginning. How should I approach this? Current implementation: Program.cs:
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddSingleton(await TestPaymentsService.CreateAsync());
...
builder.Services.AddHttpClient();
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddSingleton(await TestPaymentsService.CreateAsync());
...
builder.Services.AddHttpClient();
TestPaymentsService.cs:
public class TestPaymentsService
{
private string? jwtToken { get; set; }

public static async Task<TestPaymentsService> CreateAsync()
{
var client = new TestPaymentsService();
await client.Authenticate();
return client;
}
...
public async Task Authenticate()
{
using var client = new HttpClient();
...
public class TestPaymentsService
{
private string? jwtToken { get; set; }

public static async Task<TestPaymentsService> CreateAsync()
{
var client = new TestPaymentsService();
await client.Authenticate();
return client;
}
...
public async Task Authenticate()
{
using var client = new HttpClient();
...
3 replies
CC#
Created by oe on 11/5/2023 in #help
❔ Entity Framework always stuck, how can I debug?
No description
4 replies
CC#
Created by oe on 7/11/2023 in #help
Debugger Breaks to External Files and Exception Handling Issue in C# .NET 8.0 with VS 2022
I am coding my project in .NET 8.0 in the new Visual Studio 2022 Preview version. Whenever there is an exception within a try catch block, for some reason, the VS debugger breaks and brings me to files which are not from my project, such as: Exception User-Unhandled: System.Net.Sockets.SocketException HResult=0x80004005 Message=The requested name is valid, but no data of the requested type was found. Source=System.Net.Sockets StackTrace: at System.Net.Sockets.SocketAsyncEventArgs.<<DnsConnectAsync>g__Core|112_0>d.MoveNext() C:\Users\FRZ\AppData\Local\SourceServer\8a3b989d075fe5e6b812cbdd0fa766804632a4fa333c1d383a1867bd743fd652\src\libraries\System.Private.CoreLib\src\System\Runtime\CompilerServices\AsyncTaskMethodBuilderT.cs Not only is the exception not bringing me to my user code, but it is also breaking from within a try catch (handled exception). It should continue executing. What is going wrong, and how can I fix this?
73 replies
CC#
Created by oe on 6/26/2023 in #help
❔ C# Exceptions Not Caught?
Why is this code causing Visual Studio to break if it is being ran in a try catch? It takes me here and shows me this exception:
System.Net.Http.HttpRequestException: 'The proxy tunnel request to proxy '' failed with status code '502'."'

C:\Users\FRZ\AppData\Local\SourceServer\89eb5aeb9b5e4245c273d7fede24aa2abe75483baa9ebc06da5a3ca0b1aba702\src\libraries\System.Private.CoreLib\src\System\Threading\Tasks\ValueTask.cs

[DebuggerBrowsable(DebuggerBrowsableState.Never)] // prevent debugger evaluation from invalidating an underling IValueTaskSource<T>
public TResult Result
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
object? obj = _obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);

if (obj == null)
{
return _result!;
}

if (obj is Task<TResult> t)
{
TaskAwaiter.ValidateEnd(t);
return t.ResultOnSuccess;
}

return Unsafe.As<IValueTaskSource<TResult>>(obj).GetResult(_token);
}
}
System.Net.Http.HttpRequestException: 'The proxy tunnel request to proxy '' failed with status code '502'."'

C:\Users\FRZ\AppData\Local\SourceServer\89eb5aeb9b5e4245c273d7fede24aa2abe75483baa9ebc06da5a3ca0b1aba702\src\libraries\System.Private.CoreLib\src\System\Threading\Tasks\ValueTask.cs

[DebuggerBrowsable(DebuggerBrowsableState.Never)] // prevent debugger evaluation from invalidating an underling IValueTaskSource<T>
public TResult Result
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
object? obj = _obj;
Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>);

if (obj == null)
{
return _result!;
}

if (obj is Task<TResult> t)
{
TaskAwaiter.ValidateEnd(t);
return t.ResultOnSuccess;
}

return Unsafe.As<IValueTaskSource<TResult>>(obj).GetResult(_token);
}
}
The issue is occuring here: HttpResponseMessage httpResp = await Client.SendAsync(httpReq);
public static async Task<string?> GetShopHtml(string shopUrl)
{
using var httpReq = new HttpRequestMessage(HttpMethod.Get, shopUrl);

HttpResponseMessage httpResp = await Client.SendAsync(httpReq);
public static async Task<string?> GetShopHtml(string shopUrl)
{
using var httpReq = new HttpRequestMessage(HttpMethod.Get, shopUrl);

HttpResponseMessage httpResp = await Client.SendAsync(httpReq);
{
string shopHtml = await TestRequests.GetShopHtml(shopUrl);
collection = _scanner.ExtractNodes(shopHtml!);
}
catch (Exception ex)
{
_logger.LogError($"Error while scraping {shopUrl}, added to errors json file.");
await File.AppendAllTextAsync("Errors.json", ex.ToString());
}
{
string shopHtml = await TestRequests.GetShopHtml(shopUrl);
collection = _scanner.ExtractNodes(shopHtml!);
}
catch (Exception ex)
{
_logger.LogError($"Error while scraping {shopUrl}, added to errors json file.");
await File.AppendAllTextAsync("Errors.json", ex.ToString());
}
Regardless of the exception type, it should not be breaking in Visual Studio? I am running Visual Studio 2022 preview version
8 replies
CC#
Created by oe on 5/15/2023 in #help
✅ Client needs filtering logic - what's the best way to implement?
I have two classes like so:
public class VirtualStore
{
public string StoreName { get; set; }

public List<VirtualProduct> Products { get; set; } = new();
}
public class VirtualStore
{
public string StoreName { get; set; }

public List<VirtualProduct> Products { get; set; } = new();
}
public class VirtualProduct
{
public string Image { get; set; }
public string StockNumber { get; set; }
public string Description { get; set; }
public string URL { get; set; }
public string Category { get; set; }
public string Price { get; set; }
public string Currency { get; set; }
}
public class VirtualProduct
{
public string Image { get; set; }
public string StockNumber { get; set; }
public string Description { get; set; }
public string URL { get; set; }
public string Category { get; set; }
public string Price { get; set; }
public string Currency { get; set; }
}
After my program runs, the List<VirtualProduct> Products variable is filled with objects and a JSON of it is returned to the client. I want my client who knows nothing about coding to be able to filter products by writing in some language or query what objects he wants to keep in that list, based on certain conditions, like: "CONTAINS toy", "EQUALS Best Toy In America", "NOT {{StoreName}}" Should I implement this logic on my own, or use some sort of existing query language that C# can interpret / solution for this? Thanks!
44 replies
CC#
Created by oe on 4/12/2023 in #help
GIT Question for company
Sorry if this is a really noob question, but I don't want to bother my manager and also I've never worked as a team on a Git project and never ran into this issue... I have coded a branch1 on my company GIT repository. After I have finished coding it, it is pending work review, so they haven't integrated it into master yet. Now I have been told to code a new branch2. However, now there are updates on main that are not in the branch1, and updates in the branch1 that are not in main. I need both of these changes to update what I am doing in branch2. What solution do I have apart from asking them to finish the pending work review and integrate branch1 to main and then pulling the new main from my side?
7 replies
CC#
Created by oe on 3/26/2023 in #help
✅ Calculate statistics on server or on frontend? Help me decide please! :)
28 replies
CC#
Created by oe on 2/7/2023 in #help
❔ What unit tests should I create for my ASP.NET API Controller / project?
I am new to Unit Testing. I have watched a video on XUnit and FluidAssertions, but I am unsure as to what the "industry standards" of creating unit tests is like. Should you create one unit test per controller method? In my case, what unit tests would you create? API Project: https://github.com/OEvans117/RequestConverter/tree/master/RequestConverterAP API Controller: https://github.com/OEvans117/RequestConverter/blob/master/RequestConverterAPI/Controllers/RequestController.cs XUnit Project: https://github.com/OEvans117/RequestConverter/tree/master/RequestConverterAPI.Tests Thank you! 🙂
2 replies
CC#
Created by oe on 1/25/2023 in #help
Any way to create another instance of a List<Tuple> with the same setter?
I have this within an abstract class:
private List<Tuple<string, string>> _Headers;
public List<Tuple<string, string>> Headers
{
get { return this._Headers; }
set
{
foreach (Tuple<string, string> kvp in value)
this._Headers.Add(new Tuple<string, string>(kvp.Item1.Replace("\"", "\\\"")
, kvp.Item2.Replace("\"", "\\\"")));
}
}

private List<Tuple<string, string>> _Cookies;
public List<Tuple<string, string>> Cookies
{
get { return this._Cookies; }
set
{
foreach (Tuple<string, string> kvp in value)
this._Cookies.Add(new Tuple<string, string>(kvp.Item1.Replace("\"", "\\\"")
, kvp.Item2.Replace("\"", "\\\"")));
}
}
private List<Tuple<string, string>> _Headers;
public List<Tuple<string, string>> Headers
{
get { return this._Headers; }
set
{
foreach (Tuple<string, string> kvp in value)
this._Headers.Add(new Tuple<string, string>(kvp.Item1.Replace("\"", "\\\"")
, kvp.Item2.Replace("\"", "\\\"")));
}
}

private List<Tuple<string, string>> _Cookies;
public List<Tuple<string, string>> Cookies
{
get { return this._Cookies; }
set
{
foreach (Tuple<string, string> kvp in value)
this._Cookies.Add(new Tuple<string, string>(kvp.Item1.Replace("\"", "\\\"")
, kvp.Item2.Replace("\"", "\\\"")));
}
}
Is there any way to simplify it? I am basically writing the exact same logic for 2 tuples, just with different names. Thanks!
61 replies
CC#
Created by oe on 1/23/2023 in #help
Brotli compression for JSON producing newlines - any work around?
I am running ASP.NET 7.0 and I don't want to use Newtonsoft because I would have to downgrade. Can I minify a JSON string without it?
61 replies
CC#
Created by oe on 1/23/2023 in #help
Compressing JSON data for SQL server, best way?
Hi, What's a good way to approach compressing big JSON data and storing it in SQL server? (libraries etc)
18 replies
CC#
Created by oe on 1/19/2023 in #help
❔ best design practice for this?
Hi everyone. I have a ConvertedRequest class that acts as an Entity Framework model for the database. Inside the class, there is an ID of type string (I want it to be alphanumeric 6 digits, not GUID). I have a method to generate this below. My question is what's the best design practice to reference this method? I am technically not gonna make more "Random" value methods, so was thinking static singleton, but the purpose of this project is to learn how to write with good design patterns
readonly Random random = new();
string RandomString(int length = 6)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray()).ToLower();
}
readonly Random random = new();
string RandomString(int length = 6)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray()).ToLower();
}
Including it in the Controller for the API just seems ugly and out of place
5 replies
CC#
Created by oe on 1/17/2023 in #help
Is this the right way to save state of my ASP.NET/Angular app as a URL?
I have an ASP.NET Core + Angular project. Once a file is uploaded to my ASP.NET API, a JSON is returned which is used by the Angular frontend. I want to be able to click a SAVE button in frontend, and save that exact state of the APP to a URL (ie: example.com/r/wrhwrthj). I thought of a way to do this. 1) When the save button is clicked, the JSON is sent to an API: POST URL: /SaveState/ BODY: jsonString 2) The API uses entity framework to save the current state to a MySQL table of { StateID, StateValue } 3) If Angular detects a route of /r/{x}, it requests the JSON from /GetState?id={x} Is this a good approach to the problem I'm trying to solve? Will appreciate all feedback. Thank you!
5 replies
CC#
Created by oe on 1/16/2023 in #help
✅ Best way to return Tuple<string, string> as an Array?
I have an interface called IRequest, with Tuple lists called:
public List<Tuple<string, string>> Headers { get; set; } = new List<Tuple<string, string>>();
public List<Tuple<string, string>> Cookies { get; set; } = new List<Tuple<string, string>>();
public List<Tuple<string, string>> Headers { get; set; } = new List<Tuple<string, string>>();
public List<Tuple<string, string>> Cookies { get; set; } = new List<Tuple<string, string>>();
Unfortunately, when I export a class that inherits IRequest as JSON, it's then hard to iterate through Headers and Cookies, because Tuples in C# are treated like classes outside of it. (I'm using Angular to read the JSON). What's the best solution to export that Tuple as an Array of strings in the JSON? Take into account I will have multiple classes that inherit IRequest, so a global solution that affects all classes would be perfect in that sense.
61 replies
CC#
Created by oe on 1/13/2023 in #help
❔ Implement Angular in existing ASP.NET Core MVC project?
Hi, I have an ASP.NET MVC web app that takes a file upload in and produces an output. It uses Razor, HTML and some simple javascript in a <script> tag. I would like to recreate the project in Angular, React, Vue and lastly Blazor (instead of js) to test each framework out and see which one I like the best. I am currently trying to implement Angular, but I believe my web app uses server side rendering (SSR) as it uses ASP.NET Core MVC pattern.
My question is: how do I implement Angular in my existing ASP.NET MVC project ?
26 replies
CC#
Created by oe on 12/17/2022 in #help
Installing Docker and running ASP.NET project on Ubuntu Droplet led to ERR_CONNECTION_TIMED_OUT site
Anyone know what issue I had with Docker/NGINX when trying to run an ASP.NET site? I must say before starting this was a production server for my site that was hosting a laravel API + vuejs webapp. It uses NGINX to do so. Before I installed Docker I figured there might be issues with the server when doing so, so I saved all the /nginx/ folder data and I made a droplet snapshot (none of which helped to restore old state). Then I installed docker, pulled my repository and ran the image using docker run. I then visited my website, and it was completely crashed. Nothing would load. Everything would end up in ERR_CONNECTION_TIMED_OUT So I uninstalled docker, that didn't help. I tried replacing NGINX sites-enabled, .conf (every file) with the old version, didn't help. Lastly, I restored the droplet snapshot using my hosting company, but that didn't help. Anyone have any ideas why this might've happened?
2 replies
CC#
Created by oe on 12/4/2022 in #help
❔ Why can't I host my ASP.NET WebAPI on Ubuntu ?
19 replies