surwren
surwren
Explore posts from servers
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
CC#
Created by surwren on 4/26/2024 in #help
What are some tools or methods for debugging microservices?
I am considering a microservices developer role and was wondering what some tools or strategies to debugging microservices are. My friends told me to 'just do monolithic', but there has to be a way right? Not everyone uses monolithic and microservices are good job experience?
13 replies
CC#
Created by surwren on 4/7/2024 in #help
✅ "Legacy Versions" of C# or .NET?
As per title, I was wondering what would be considered legacy stacks when looking up companies. I am aware of what the Java equivalent tends to be (Java 6-8, JSP, etc) but I am unfamiliar with what indicators there are for legacy C# or .NET stacks in the industry. Is anyone able to provide some insight?
17 replies
CC#
Created by surwren on 3/30/2024 in #help
Using SQL with C# or ASP.NET, without an ORM
I have a question about using SQL with C# or ASP.NET, without an ORM What are the most common ways this is done? What advantages would manual queries have over ORM generated ones
14 replies
CC#
Created by surwren on 2/6/2024 in #help
Application Architecture Question
No description
16 replies
CC#
Created by surwren on 1/12/2024 in #help
How to check bandwidth of websocket connection?
As per title. I'm currently using websocket-sharp, but I'm wondering if there is a universal way to do it. I am thinking of sending 5 * 30 fps data (so basically 150 fps) and don't know if my websocket connection can handle it.
4 replies
CC#
Created by surwren on 1/10/2024 in #help
c# versions
Does c# ever actually upgrade its versions? I keep reading about java upgrades year over year (21,22) but c# never seems to announce anything, or anything major. Am i missing something?
17 replies
CC#
Created by surwren on 5/7/2023 in #help
❔ WebASM and c#
So I'm considering an emscripten compiled learning project. I know that C# doesn't support inline assembly. Am wondering how one could manually optimize the asm output outputted from c#?
14 replies
CC#
Created by surwren on 11/14/2022 in #help
❔ The view 'GetModel1' was not found
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'GetModel1' was not found. The following locations were searched:
/Views/Home/GetModel1.cshtml
/Views/Shared/GetModel1.cshtml
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'GetModel1' was not found. The following locations were searched:
/Views/Home/GetModel1.cshtml
/Views/Shared/GetModel1.cshtml
Why is this happening? I'm trying to call an async method (GetModel1) to access an api endpoint, which should then return the desired value to the view. Code is as follows: HomeController.cs:
public IActionResult Index(string result)
{
TempData["Output"]=result;
return View();

}


[HttpGet]
public async Task<IActionResult> GetModel1(int x, int y, int z)
{
//need basic verification for non-integers

var httpClient = new HttpClient();

var url = $"http://localhost:8080/model1?x={x}&y={y}&z={z}";
var response= await httpClient.GetAsync(url);
var result= await response.Content.ReadAsStringAsync();
return Index(result);
}
public IActionResult Index(string result)
{
TempData["Output"]=result;
return View();

}


[HttpGet]
public async Task<IActionResult> GetModel1(int x, int y, int z)
{
//need basic verification for non-integers

var httpClient = new HttpClient();

var url = $"http://localhost:8080/model1?x={x}&y={y}&z={z}";
var response= await httpClient.GetAsync(url);
var result= await response.Content.ReadAsStringAsync();
return Index(result);
}
Code for razor view:

@{
string output= (string)TempData["Output"];
}
<form method="GET" action="Home\GetModel1">

<label for="x">Repayment status in September:</label><br>
<input type="text" id="x" name="x" value="-1"><br>

<label for="y">Repayment status in August:</label><br>
<input type="text" id="y" name="y" value="-1"><br>

<label for="z">Repayment status in July:</label><br>
<input type="text" id="z" name="z" value="-1"><br><br>

<input type="submit" value="Submit">
</form>

<div class="text-center" id="Model1">@output</div>

@{
string output= (string)TempData["Output"];
}
<form method="GET" action="Home\GetModel1">

<label for="x">Repayment status in September:</label><br>
<input type="text" id="x" name="x" value="-1"><br>

<label for="y">Repayment status in August:</label><br>
<input type="text" id="y" name="y" value="-1"><br>

<label for="z">Repayment status in July:</label><br>
<input type="text" id="z" name="z" value="-1"><br><br>

<input type="submit" value="Submit">
</form>

<div class="text-center" id="Model1">@output</div>
13 replies
CC#
Created by surwren on 11/4/2022 in #help
Json and Yaml formatting for ASP project
What's a good resource for json or yaml formatting? Really need some resource as it keeps throwing errors
3 replies
CC#
Created by surwren on 11/2/2022 in #help
ASP storage use cases
So I'm aware there are several places to store data, which I will list as follows: Serverside (application): Sessionstate AddSingleton AddScoped Clientside: Cookies LocalStorage SessionStorage I was wondering where specifically each of these 6 would be used, particularly for sessionstate, singletons and scoped?
13 replies
CC#
Created by surwren on 11/2/2022 in #help
Why won't the second try-catch block propagate an overflowexception?
When anything over 2.147b is entered for the first try-catch block, it successfully automatically throws (and then catches) an overflowexception. It does not need
if(int.Parse(input) < 0)
if(int.Parse(input) < 0)
But when anything over 2.147b is entered into the console for the second try-catch block, it does not automatically throw the overflowexception. Instead, it throws a formatexception. The second block needs
if(int.Parse(input) < 0)
if(int.Parse(input) < 0)
to throw overflow. WHY? Code below:
int? n = null;
string input;

while (n == null)
{

Console.WriteLine("Please enter a positive integer");
try
{

input = Console.ReadLine();
if (int.Parse(input) < 0)
{
Console.Write("Number must be a positive integer. ");
continue;
}
else if (!int.TryParse(input, out _))
{
throw new FormatException();

}
else if (int.TryParse(input, out _))
{
n = int.Parse(input);
}


}
catch (OverflowException o)
{
Console.Write("OverflowException. ");
}
catch (FormatException f)
{
Console.Write("FormatException. ");
}

}
int[] arr = new int[(int)n];

try
{
for (int i = 0; i < (int)n; i++)
{
Console.WriteLine("Enter number {0}", i + 1);
input = Console.ReadLine();

if (!int.TryParse(input, out _))
{
throw new FormatException("FormatException.");

}

else if (int.TryParse(input, out _))
{
arr[i] = int.Parse(input);
}
}

Console.WriteLine("Sum is " + Sum(arr));

}
catch (OverflowException o)
{
Console.WriteLine("OverflowException.");

}

catch (FormatException f)
{
Console.WriteLine("FormatException.");

}

//=======================================


static int Sum(int[] numbers)
{
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
return sum;
}
int? n = null;
string input;

while (n == null)
{

Console.WriteLine("Please enter a positive integer");
try
{

input = Console.ReadLine();
if (int.Parse(input) < 0)
{
Console.Write("Number must be a positive integer. ");
continue;
}
else if (!int.TryParse(input, out _))
{
throw new FormatException();

}
else if (int.TryParse(input, out _))
{
n = int.Parse(input);
}


}
catch (OverflowException o)
{
Console.Write("OverflowException. ");
}
catch (FormatException f)
{
Console.Write("FormatException. ");
}

}
int[] arr = new int[(int)n];

try
{
for (int i = 0; i < (int)n; i++)
{
Console.WriteLine("Enter number {0}", i + 1);
input = Console.ReadLine();

if (!int.TryParse(input, out _))
{
throw new FormatException("FormatException.");

}

else if (int.TryParse(input, out _))
{
arr[i] = int.Parse(input);
}
}

Console.WriteLine("Sum is " + Sum(arr));

}
catch (OverflowException o)
{
Console.WriteLine("OverflowException.");

}

catch (FormatException f)
{
Console.WriteLine("FormatException.");

}

//=======================================


static int Sum(int[] numbers)
{
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
return sum;
}
6 replies
CC#
Created by surwren on 11/1/2022 in #help
When to use Null Forgiving (!) vs Non-Nullable casts
int? n = null;
string input;

if (int.TryParse(input,out _))
{
n = int.Parse(input);
}

int[] arr = new int[(int)n];
int? n = null;
string input;

if (int.TryParse(input,out _))
{
n = int.Parse(input);
}

int[] arr = new int[(int)n];
In this example, n needs to be cast from int? to int My question is why null forgiving (!) syntax does not seem to work (new int[n!];] and where null forgiving syntax would actually be applicable.
112 replies
CC#
Created by surwren on 10/31/2022 in #help
Casting and output
So take a basic example like
double avg = ((double)num1 + num2) / 2;
double avg = ((double)num1 + num2) / 2;
If you take the (double) cast out from num1, avg won't reflect the decimal point. Is there a google keyword I can search for more information on how to ascertain that my numbers will be reflected as I would like them to be?
3 replies
CC#
Created by surwren on 10/31/2022 in #help
Where does LinQ store its IEnumerable selections?
14 replies
CC#
Created by surwren on 10/31/2022 in #help
Bubble Sort
I have two implementations of bubble sort here; one is the model answer and one is mine. I am just wondering if my implementation would cover every possibility and sort correctly, or if I had somehow misapplied.
void BubbleSortModel(int[] arr)
{
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - 1; j++)
{
if (arr[j+1] < arr[j])
{
Swap(ref arr[j+1],ref arr[j]);
}
}
}
}

void BubbleSortMine (int[] arr)
{
for(int i = 0; i < arr.Length-1; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[j] < arr[i])
{
Swap(ref arr[i], ref arr[j]);
}

}
}
}

void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
void BubbleSortModel(int[] arr)
{
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - 1; j++)
{
if (arr[j+1] < arr[j])
{
Swap(ref arr[j+1],ref arr[j]);
}
}
}
}

void BubbleSortMine (int[] arr)
{
for(int i = 0; i < arr.Length-1; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[j] < arr[i])
{
Swap(ref arr[i], ref arr[j]);
}

}
}
}

void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
40 replies