surwren
surwren
Explore posts from servers
CC#
Created by surwren on 1/22/2025 in #help
Nuget Package Manager does not seem to be updating (How to Troubleshoot?)
No description
39 replies
CC#
Created by surwren on 1/21/2025 in #help
✅ Structuring Unit Tests
No description
15 replies
CC#
Created by surwren on 1/20/2025 in #help
✅ Mocking DB operations
Say I have a function and I need to verify that the saved UserFollow object will: 1. Cause the user objects to be retrieved if UserFollow retrieves them eagerly 2. Cause the userFollow to be retrieved if a User is retrieved with said fields eagerly public async Task<bool> AddFollowerByPrivateIdAsync(int userPrivateId, int followerPrivateId) { var user = await _context.Users.FirstOrDefaultAsync(u => u.PrivateId == userPrivateId);
var follower = await _context.Users.FirstOrDefaultAsync(u => u.PrivateId == followerPrivateId);
if (user == null || follower == null) {
return false;
}
var userFollow = new UserFollow {
FollowedId = [user.Id]
FollowerId = [follower.Id] Type = FollowType.Requested,
Followed = user,
Follower = follower
};
_context.UserFollows.Add(userFollow);
await _context.SaveChangesAsync();
return true; } How would I test this? I have looked at XUnit and MockItEasy but it doesn't look like they are dealing with the Database, but rather dependencies for abstracted code.
134 replies
CC#
Created by surwren on 1/8/2025 in #help
Data Retrieval in a SignalR Hub/Service?
I am used to repo -> service -> controller MVC models, and I do not have much experience with in-memory retrieval beyond using LinQ. Say I have a class which could have multiple queryable fields:
public string SignalRId { get; set; }
public int UserId { get; set; }
public string Nickname { get; set; }
public string Region { get; set; }
public string RoomName { get; set; }
public string SignalRId { get; set; }
public int UserId { get; set; }
public string Nickname { get; set; }
public string Region { get; set; }
public string RoomName { get; set; }
In a normal appcontextdb access scenario, I would just pull out the values using EFCore LinQ using something like
var user = await _context.Users.FirstOrDefaultAsync(u => u.UserId == UserId)
var user = await _context.Users.FirstOrDefaultAsync(u => u.UserId == UserId)
In my SignalR Hub, I am using an in-memory method and not SQL to store my data since I don't expect users to have long-lasting data (unlikely they will maintain a connection for >5minutes per session). Therefore I inject a ConnectedClientsService and don't have a DB table. - Is using FirstOrDefaultAsync with regular IQueryable is more standard practice in this case (for example, searching for strings matching region, etc)? - Is it standard practice to use 2 concurrent dictionaries with a lock to enable O(1) access?
9 replies
CC#
Created by surwren on 1/7/2025 in #help
Bottlenecks in a SignalR Implementation for Managing Room Data?
I am using SignalR to manage real-time room data in a small practice app that I may have plans to scale up in the future. The current implementation involves an in-memory dictionary where each room is mapped to a HashSet<userId> to track users in the room. So far, this does not seem like a bottleneck. However, I suspect the number of persistent connections (SignalR maintaining a connection for each user) might become a scalability issue if I scale up. I am running it via dockerized .NET server on a cloud CVM with 4GB ram Are there other common bottlenecks or pitfalls I should be aware of when scaling SignalR for this purpose? Any advice or best practices for optimizing SignalR are appreciated
34 replies
CC#
Created by surwren on 12/22/2024 in #help
Can .NET controllers accept binary data? Should they?
I have already done EFcore mapping for - user - post - media Currently the client posts to server and COS separately. I was wondering if there was a way to streamline post creation, such that the client sends the media together with the db update (to the server), and then the server can do both the db upload and cos upload in a transaction of some sort? Is this possible or advised?
8 replies
CC#
Created by surwren on 12/20/2024 in #help
Controller methods that rely on JWT authentication using another service
Is there a way to handle these methods without writing so much duplicated code? For example CRUD methods like this:
[HttpPut("OnaAuth")]
public async Task<ActionResult<UpMediaDto>> UpdateUpMediaByOnaToken([FromBody] UpMediaDto upMediaDto)
{
if (upMediaDto == null)
{
throw new InvalidOperationException("UpMediaDto is required.");
}

if (!Request.Headers.TryGetValue("Authorization", out var authorizationHeader))
{
throw new InvalidOperationException("Authorization header is required.");
}

var token = authorizationHeader.ToString().Replace("Bearer ", string.Empty);
if (string.IsNullOrEmpty(token))
{
throw new InvalidOperationException("Token is required.");
}

var userInfoUri = new Uri(new Uri(_apiSettings.BaseUrl), _apiSettings.UserInfoRoute);
var client = _httpClientFactory.CreateClient();

int OnaId = await HttpHandler.GetOnaIdAsync(client, userInfoUri, token);
var user = await _userService.GetUserByOnaIdAsync(OnaId);
... other logic
}
[HttpPut("OnaAuth")]
public async Task<ActionResult<UpMediaDto>> UpdateUpMediaByOnaToken([FromBody] UpMediaDto upMediaDto)
{
if (upMediaDto == null)
{
throw new InvalidOperationException("UpMediaDto is required.");
}

if (!Request.Headers.TryGetValue("Authorization", out var authorizationHeader))
{
throw new InvalidOperationException("Authorization header is required.");
}

var token = authorizationHeader.ToString().Replace("Bearer ", string.Empty);
if (string.IsNullOrEmpty(token))
{
throw new InvalidOperationException("Token is required.");
}

var userInfoUri = new Uri(new Uri(_apiSettings.BaseUrl), _apiSettings.UserInfoRoute);
var client = _httpClientFactory.CreateClient();

int OnaId = await HttpHandler.GetOnaIdAsync(client, userInfoUri, token);
var user = await _userService.GetUserByOnaIdAsync(OnaId);
... other logic
}
I need to repeat this chunk over and over in every method that relies on the JWT:
if (!Request.Headers.TryGetValue("Authorization", out var authorizationHeader))
{
throw new InvalidOperationException("Authorization header is required.");
}

var token = authorizationHeader.ToString().Replace("Bearer ", string.Empty);
if (string.IsNullOrEmpty(token))
{
throw new InvalidOperationException("Token is required.");
}

var userInfoUri = new Uri(new Uri(_apiSettings.BaseUrl), _apiSettings.UserInfoRoute);
var client = _httpClientFactory.CreateClient();

int OnaId = await HttpHandler.GetOnaIdAsync(client, userInfoUri, token);
if (!Request.Headers.TryGetValue("Authorization", out var authorizationHeader))
{
throw new InvalidOperationException("Authorization header is required.");
}

var token = authorizationHeader.ToString().Replace("Bearer ", string.Empty);
if (string.IsNullOrEmpty(token))
{
throw new InvalidOperationException("Token is required.");
}

var userInfoUri = new Uri(new Uri(_apiSettings.BaseUrl), _apiSettings.UserInfoRoute);
var client = _httpClientFactory.CreateClient();

int OnaId = await HttpHandler.GetOnaIdAsync(client, userInfoUri, token);
What other ways are there?
10 replies
CC#
Created by surwren on 12/19/2024 in #help
Proper way to deploy application?
So right now I scp my entire project to the CVM, build and then docker compose up The scp parts takes absolutely forever it's outrageous (project is about 117+mb) Am I stupid and just doing this wrong? Am I missing something? I haven't explored CICD pipelines yet
17 replies
CC#
Created by surwren on 12/18/2024 in #help
My constructor sets the attribute, so why is EFcore complaining?
why is EFCore complaining? Required member 'UpMedia.OwnerId' must be set in the object initializer or attribute constructor. Required member 'UpMedia.Owner' must be set in the object initializer or attribute constructor. Here: var upMedia = new UpMedia(upMediaDto.Type, user, upMediaDto.Bucket, upMediaDto.Path); My code is
try
{
int OnaId = await HttpHandler.GetOnaIdAsync(client, userInfoUri, token);
var user = await _userService.GetUserByOnaIdAsync(OnaId);
if (user == null)
{
user = await _userService.CreateUserByOnaIdAsync(OnaId);
//return NotFound("User not found. Call the \"Ona/Token\" Get/Put methods in api/Users first");
}
var upMedia = new UpMedia(upMediaDto.Type, user, upMediaDto.Bucket, upMediaDto.Path);
var createdUpMedia = await _upMediaService.CreateUpMediaAsync(upMedia);
return Ok(UpMediaMapper.ToUpMediaDto(createdUpMedia));
...
try
{
int OnaId = await HttpHandler.GetOnaIdAsync(client, userInfoUri, token);
var user = await _userService.GetUserByOnaIdAsync(OnaId);
if (user == null)
{
user = await _userService.CreateUserByOnaIdAsync(OnaId);
//return NotFound("User not found. Call the \"Ona/Token\" Get/Put methods in api/Users first");
}
var upMedia = new UpMedia(upMediaDto.Type, user, upMediaDto.Bucket, upMediaDto.Path);
var createdUpMedia = await _upMediaService.CreateUpMediaAsync(upMedia);
return Ok(UpMediaMapper.ToUpMediaDto(createdUpMedia));
...
public class UpMedia : BaseUpload
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public MediaType Type { get; set; } // Metadata

// Navigation property
public required Guid OwnerId { get; set; }
public required User Owner { get; set; } // must always be present

public ICollection<Post> Posts { get; set; }

public UpMedia() : base()
{
Posts = new HashSet<Post>();
}
public UpMedia(MediaType Type, User Owner, string Bucket, string Path) : base(Bucket, Path)
{
this.Type = Type;
this.OwnerId = Owner.Id;
this.Owner = Owner;
this.Posts = new HashSet<Post>();
}

}
public class UpMedia : BaseUpload
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public MediaType Type { get; set; } // Metadata

// Navigation property
public required Guid OwnerId { get; set; }
public required User Owner { get; set; } // must always be present

public ICollection<Post> Posts { get; set; }

public UpMedia() : base()
{
Posts = new HashSet<Post>();
}
public UpMedia(MediaType Type, User Owner, string Bucket, string Path) : base(Bucket, Path)
{
this.Type = Type;
this.OwnerId = Owner.Id;
this.Owner = Owner;
this.Posts = new HashSet<Post>();
}

}
???????
47 replies
CC#
Created by surwren on 12/17/2024 in #help
Puzzled about Nullability in EFCore
No description
48 replies
CC#
Created by surwren on 12/16/2024 in #help
EFCore is incapable of connecting to DB despite everything else being able to
Mystifying me because - SSMS connects fine - Migration commands like Add-Migration "Add_Table" and Update-Database work fine
PM> Add-Migration "Update02"
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> Update-Database
Build started...
Build succeeded.
Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Applying migration '20241216052859_Update02'.
Done.
PM> Add-Migration "Update02"
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> Update-Database
Build started...
Build succeeded.
Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
Applying migration '20241216052859_Update02'.
Done.
can also be viewed from DB side. I am always encountering this error from EFCore when I run the application:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)'
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)'
Code will be in responses
10 replies
CC#
Created by surwren on 12/13/2024 in #help
Entity Framework Core: How to build without Package Manager Commands?
I am looking at this sample project : https://github.com/Nedal-Esrar/Travel-and-Accommodation-Booking-Platform I notice that it automatically creates the TABP table as long as the connection string goes through, which is not the same for other EFCore projects I have created in the past in .NET 8.0. I have always needed to manually do Add-Migration "Add_Tables" and Update-Database but it seems this project does not? I did ctrl + shift + f but I do not see any scripts for the aforementioned commands. What dark magic is this project doing that bypasses the migrations step?
6 replies
CC#
Created by surwren on 12/12/2024 in #help
Recommended flow for writing + deploying a basic Microservice Application (with DB)?
No description
24 replies
CC#
Created by surwren on 11/8/2024 in #help
Refactoring Similar Network Requests
I have 3 async methods with a great deal of similarities but some differences (some use Authorization token, some have Json payload, some return Task<bool>, others Task) but all make network requests in a similar flow. What is an approach I could use to refactor them?
93 replies
CC#
Created by surwren on 11/8/2024 in #help
Making Concurrent API calls Asynchronously (Is this Correct?)
Apologies for the long code, need to split it up into 2 posts because it's really long:
async Task SendUserInfoRequestAsync() {
if (string.IsNullOrEmpty(sessionCache.loginToken)) {
Debug.LogError("No login token found.....");
return;
}
Uri userInfoUri = new Uri(new Uri(baseUrl), userInfoRoute);
Uri getUserInfoUri = new Uri(new Uri(baseUrl), getUserInfoRoute);

using (HttpClient client = new HttpClient()) {
try {
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", sessionCache.loginToken);

Task<HttpResponseMessage> task1 = client.PostAsync(userInfoUri, null);
Task<HttpResponseMessage> task2 = client.PostAsync(getUserInfoUri, null);

HttpResponseMessage response1 = await task1;
HttpResponseMessage response2 = await task2;

if (!response1.IsSuccessStatusCode || !response2.IsSuccessStatusCode) {
string errorMessage = "Request from SendUserInfoRequestAsync() failed. ";
if (!response1.IsSuccessStatusCode) {
lastHttpResponseError = response1;
errorMessage += $"First request failed";
}
if (!response2.IsSuccessStatusCode) {
lastHttpResponseError = response2;
errorMessage += $"Second request failed.";
}
Debug.LogError(errorMessage);
}
async Task SendUserInfoRequestAsync() {
if (string.IsNullOrEmpty(sessionCache.loginToken)) {
Debug.LogError("No login token found.....");
return;
}
Uri userInfoUri = new Uri(new Uri(baseUrl), userInfoRoute);
Uri getUserInfoUri = new Uri(new Uri(baseUrl), getUserInfoRoute);

using (HttpClient client = new HttpClient()) {
try {
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", sessionCache.loginToken);

Task<HttpResponseMessage> task1 = client.PostAsync(userInfoUri, null);
Task<HttpResponseMessage> task2 = client.PostAsync(getUserInfoUri, null);

HttpResponseMessage response1 = await task1;
HttpResponseMessage response2 = await task2;

if (!response1.IsSuccessStatusCode || !response2.IsSuccessStatusCode) {
string errorMessage = "Request from SendUserInfoRequestAsync() failed. ";
if (!response1.IsSuccessStatusCode) {
lastHttpResponseError = response1;
errorMessage += $"First request failed";
}
if (!response2.IsSuccessStatusCode) {
lastHttpResponseError = response2;
errorMessage += $"Second request failed.";
}
Debug.LogError(errorMessage);
}
12 replies
CC#
Created by surwren on 11/8/2024 in #help
What is the quickest way to copy API structures (headers, payload, response) from browser inspector?
No description
9 replies
CC#
Created by surwren on 11/7/2024 in #help
Can't Refactor Or Save this Class File (Lazily Loaded Singleton)
using System;

public sealed class SessionCache {
private static readonly Lazy<SessionCache> lazy =
new Lazy<SessionCache>(() => new SessionCache());

public static SessionCache Instance { get { return lazy.Value; } }
public UserData userData { get; set; }

private SessionCache() {
}
}
using System;

public sealed class SessionCache {
private static readonly Lazy<SessionCache> lazy =
new Lazy<SessionCache>(() => new SessionCache());

public static SessionCache Instance { get { return lazy.Value; } }
public UserData userData { get; set; }

private SessionCache() {
}
}
Am I doing something wrong in the syntax? .NET CORE 2.1
4 replies
CC#
Created by surwren on 5/15/2024 in #help
Deployment vs production environments
I am preparing for a .NET role and am wondering what some configurations/setups/tools I can look up or prepare for? For context: The company is using .NET and Azure. Development is done via login to a VMware portal (IDE and environment are setup inside said VM) and there are a series of CICD tools facilitating any code pushes within said VMware portal. What deployment/production configurations or tools should I look into?
3 replies