hutonahill
hutonahill
CC#
Created by hutonahill on 9/6/2024 in #help
✅ IIS?
Soooo.. i tried to run my ASP.NET project and rider threw an error i had never seen before. It said i had to set up IIS. i though what the heck, you didn't need this 20 min ago. but I clicked the link to the settings and followed the instructions. I think i installed iis, then i wanted me to install ASP.NET Core module. I clicked the doc page and, found the Microsoft link for the install, rebooted and i am done. but i am not. still doesn't work. While rider filled in the IIS express root folder on its own it did not fill in the ASP.NET core module file location. 1) what on earth is IIS? 2) why didn't i need it 20 min ago? only major change i made to the code was adding a hosted service 3) Where is the file location for ASP.NET Core module? (going to sleep, then oral surgery, then more sleep, so i am going to be delayed getting back to this.)
104 replies
CC#
Created by hutonahill on 9/6/2024 in #help
✅ using Logging with ASP.NET
No description
137 replies
CC#
Created by hutonahill on 9/5/2024 in #help
Live Templates: Jetbrains Rider
No description
17 replies
CC#
Created by hutonahill on 9/3/2024 in #help
✅ using using to clear up ambiguous references.
I've to two method called index: Microsoft.EntityFrameworkCore.Index System.ComponentModel.DataAnnotations.Schema.Index i don't use the 2nd one. I want every mention of index to be interpreted as the first one. I've tried adding one of these using's to fix the problem, but nether works, it just says it Cannot resolve symbol 'Index'
using Index = Microsoft.EntityFrameworkCore.Index;
using IndexCB = System.ComponentModel.DataAnnotations.Schema.Index;
using Index = Microsoft.EntityFrameworkCore.Index;
using IndexCB = System.ComponentModel.DataAnnotations.Schema.Index;
36 replies
CC#
Created by hutonahill on 9/2/2024 in #help
Trying to scaffold a MySQL database with Rider
I am trying to scaffold a MySQL database. I am using Rider. I found this article on the MySQL website: https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-scaffold-example.html but the commands it uses seems to require Visual Studio which i am not using. then i found this article from Jetbrains themselves: https://blog.jetbrains.com/dotnet/2022/01/31/entity-framework-core-inside-rider-ui-way/#alternatives
58 replies
CC#
Created by hutonahill on 8/30/2024 in #help
Temporary Pause
I am using .NET 8 I've got an ASP.NET API that i would like to pause. The goal of this is to prevent any endpoints from being called for a short amount of time. I could do this procedurally with a constant variable that's checked, but I would rather not send nothing. Is there some kind of HTML code i could return that would indicate that the API is offline but like on purpose? Instead of just returning nothing. I also need a way to return this response to the user when they try to access the API while its paused. Is there a way for be to disable all the endpoints and run a default endpoint?
10 replies
CC#
Created by hutonahill on 8/29/2024 in #help
Storing types as strings
I need to store a Type as a string, then convert it back to a type. How do i do this? I've tried Type.Name then doing Type.GetType(typeName) but this returns null
27 replies
CC#
Created by hutonahill on 8/28/2024 in #help
✅ whats up with this console output
Value
yellowThresholdWidth == 195.42857142857144
redThresholdWidth == 684
barWidth == 760
Value
yellowThresholdWidth == 195.42857142857144
redThresholdWidth == 684
barWidth == 760
Console.WriteLine($"Value " +
$"\nyellowThresholdWidth == {yellowThresholdWidth} " +
$"\nredThresholdWidth == {redThresholdWidth}" +
$"\nbarWidth == {barWidth}");
Console.WriteLine($"Value " +
$"\nyellowThresholdWidth == {yellowThresholdWidth} " +
$"\nredThresholdWidth == {redThresholdWidth}" +
$"\nbarWidth == {barWidth}");
144 replies
CC#
Created by hutonahill on 8/27/2024 in #help
✅ Windows Audio Capture
Building an XAML application. The eventual goal is to capture an audio source and stream it to another application using webhooks. This is my first time doing: 1) XAML 2) Audio anything 3) Webhooks i detect audio sources with this method:
private void PopulateMicrophones() {
List<String> waveInDevices = Enumerable.Range(0, WaveIn.DeviceCount)
.Select(i => WaveIn.GetCapabilities(i).ProductName)
.ToList();

waveInDevices.Insert(0, "Select Mic");

MicrophoneDropdown.ItemsSource = waveInDevices;
if (waveInDevices.Count > 0)
{
MicrophoneDropdown.SelectedIndex = 0; // Set the first microphone as default selected
}
}
private void PopulateMicrophones() {
List<String> waveInDevices = Enumerable.Range(0, WaveIn.DeviceCount)
.Select(i => WaveIn.GetCapabilities(i).ProductName)
.ToList();

waveInDevices.Insert(0, "Select Mic");

MicrophoneDropdown.ItemsSource = waveInDevices;
if (waveInDevices.Count > 0)
{
MicrophoneDropdown.SelectedIndex = 0; // Set the first microphone as default selected
}
}
Then i use these methods to start and stop recording
private void StartMicrophoneCapture(int deviceNumber) {
waveIn?.StopRecording();
waveIn?.Dispose(); // Dispose of the old instance if necessary

waveIn = new WaveInEvent { DeviceNumber = deviceNumber };

// Add logging for debugging
Console.WriteLine($"Starting microphone capture on device {deviceNumber}: {WaveIn.GetCapabilities(deviceNumber).ProductName}");

waveIn.DataAvailable += OnDataAvailable;
waveIn.StartRecording();
}

private void StopMicrophoneCapture()
{
waveIn?.StopRecording();
waveIn?.Dispose();
waveIn = null;
currentVolume = 0; // Reset volume
VolumeBar.Width = 1; // Reset volume bar width
VolumeBar.Fill = new SolidColorBrush(Colors.Gray); // Set to neutral color
}
private void StartMicrophoneCapture(int deviceNumber) {
waveIn?.StopRecording();
waveIn?.Dispose(); // Dispose of the old instance if necessary

waveIn = new WaveInEvent { DeviceNumber = deviceNumber };

// Add logging for debugging
Console.WriteLine($"Starting microphone capture on device {deviceNumber}: {WaveIn.GetCapabilities(deviceNumber).ProductName}");

waveIn.DataAvailable += OnDataAvailable;
waveIn.StartRecording();
}

private void StopMicrophoneCapture()
{
waveIn?.StopRecording();
waveIn?.Dispose();
waveIn = null;
currentVolume = 0; // Reset volume
VolumeBar.Width = 1; // Reset volume bar width
VolumeBar.Fill = new SolidColorBrush(Colors.Gray); // Set to neutral color
}
I added a volume bar so i could see the audio being captured and the audio bar gets set to 0 when i pick an audio source (its one if the mic is null). I think this means i am not capturing audio. but i don't actually know. How do i even debug this?
2 replies
CC#
Created by hutonahill on 8/25/2024 in #help
Where can i put files so they will be in the same folder as the exe?
I've tried /bin, but this doesn't work.
114 replies
CC#
Created by hutonahill on 8/23/2024 in #help
✅ using
I keep seeing variables defined within a using, like
using(var connection = new SQLiteConnection()){
...
using(var connection = new SQLiteConnection()){
...
what is using? why do people use it? what are the risks of not using it? I think this just disposes of the connection variable (for sure) after its done, but i see it used mostly when dealing with databases. is there a reason for this. If my variables are within a method they get disposed at the end of the method right? How concerned should i be about this?
16 replies
CC#
Created by hutonahill on 8/22/2024 in #help
What's up with SQLite and Jetbrains Rider
No description
262 replies
CC#
Created by hutonahill on 8/5/2024 in #help
How does signInManager return tokens?
I am modifying the standard login endpoint provided by MapIdentityApi<IdentityUser>(). at the bottem of the login endpoint: // The signInManager already produced the needed response in the form of a cookie or bearer token. i assume this means that somehow signinManager returns its tokens to the users. I need the login endpoint to return some other data depending on the roles the user has. I've implemented this logic, but i cant figure out how to return the sign tokens as well as my data. it also looks like that even when my users don't have this role the method is not returning tokens, its just returning an empty success. How does signInManager return tokens to the user and how can i get it to return that data to my method so i can control how its returned to the user?
6 replies
CC#
Created by hutonahill on 8/3/2024 in #help
✅ BuildServiceProvider does not exist
private static IServiceProvider _services;
...
IServiceCollection temp = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
_services = temp.BuildServiceProvider();
private static IServiceProvider _services;
...
IServiceCollection temp = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
_services = temp.BuildServiceProvider();
everyone i can find online says this is how to get an instance of IServiceProvider, but it does not work. i found one person with my issue, but they had the wrong useing declaration.
15 replies
CC#
Created by hutonahill on 8/3/2024 in #help
API does not deploy in debug mode
when i try to test my API in debug mode it tries to open the swagger page but i get an unable to connect. the most confusing part is this doesn't happen every time, most of the time i can restart the api (still in debug mode) and it now works, but its getting more and more frequent and i am starting to be concerned.
21 replies
CC#
Created by hutonahill on 8/2/2024 in #help
✅ .NET Identity can't require 2FA
on registration i set up 2fa and require it to log in:
await userManager.SetTwoFactorEnabledAsync(user, true);

// get the newly defined key
string? key = await userManager.GetAuthenticatorKeyAsync(user);

// make sure we get the key.
if (string.IsNullOrEmpty(key)) {
await userManager.ResetAuthenticatorKeyAsync(user);
key = await userManager.GetAuthenticatorKeyAsync(user);

if (string.IsNullOrEmpty(key)) {
throw new NotSupportedException("The user manager must produce an authenticator key.");
}
}

// Return the shared key and indicate successful registration
return TypedResults.Ok(new RegistrationResponse(key));
await userManager.SetTwoFactorEnabledAsync(user, true);

// get the newly defined key
string? key = await userManager.GetAuthenticatorKeyAsync(user);

// make sure we get the key.
if (string.IsNullOrEmpty(key)) {
await userManager.ResetAuthenticatorKeyAsync(user);
key = await userManager.GetAuthenticatorKeyAsync(user);

if (string.IsNullOrEmpty(key)) {
throw new NotSupportedException("The user manager must produce an authenticator key.");
}
}

// Return the shared key and indicate successful registration
return TypedResults.Ok(new RegistrationResponse(key));
however when i go to login:
var result = await signInManager.PasswordSignInAsync(login.Email, login.Password, isPersistent, lockoutOnFailure: true);

if (result.RequiresTwoFactor) {
if (!string.IsNullOrEmpty(login.TwoFactorCode))
{
...

var result = await signInManager.PasswordSignInAsync(login.Email, login.Password, isPersistent, lockoutOnFailure: true);

if (result.RequiresTwoFactor) {
if (!string.IsNullOrEmpty(login.TwoFactorCode))
{
...

the initial sign in fails (as expected) and result.RequiresTwoFactor is false. what am i doing wrong?
9 replies
CC#
Created by hutonahill on 8/2/2024 in #help
✅ Print to Debug page
How do i print to the debug page? i need to add prints so i can debug some stuff (break points don't take). ive treid Console.WriteLine and Debug.Print but nether work:
public static IEndpointConventionBuilder CustomMapIdentityApi<TUser>(this IEndpointRouteBuilder endpoints,
string verify2faRoleName) where TUser : class, new()
{
...

routeGroup.MapPost("/login", async Task<Results<Ok<AccessTokenResponse>, EmptyHttpResult, ProblemHttpResult>>
([FromBody] LoginRequest login, [FromQuery] bool? useCookies, [FromQuery] bool? useSessionCookies, [FromServices] IServiceProvider sp) =>
{
...
Console.WriteLine($"\n\tRequitesTwoFactor: {result.RequiresTwoFactor}");
Console.WriteLine($"\tIsLockedOut: {result.IsLockedOut}");
Console.WriteLine($"\tSucceeded: {result.Succeeded}\n");
Debug.Print($"\n\tRequitesTwoFactor: {result.RequiresTwoFactor}");
Debug.Print($"\tIsLockedOut: {result.IsLockedOut}");
Debug.Print($"\tSucceeded: {result.Succeeded}\n");
public static IEndpointConventionBuilder CustomMapIdentityApi<TUser>(this IEndpointRouteBuilder endpoints,
string verify2faRoleName) where TUser : class, new()
{
...

routeGroup.MapPost("/login", async Task<Results<Ok<AccessTokenResponse>, EmptyHttpResult, ProblemHttpResult>>
([FromBody] LoginRequest login, [FromQuery] bool? useCookies, [FromQuery] bool? useSessionCookies, [FromServices] IServiceProvider sp) =>
{
...
Console.WriteLine($"\n\tRequitesTwoFactor: {result.RequiresTwoFactor}");
Console.WriteLine($"\tIsLockedOut: {result.IsLockedOut}");
Console.WriteLine($"\tSucceeded: {result.Succeeded}\n");
Debug.Print($"\n\tRequitesTwoFactor: {result.RequiresTwoFactor}");
Debug.Print($"\tIsLockedOut: {result.IsLockedOut}");
Debug.Print($"\tSucceeded: {result.Succeeded}\n");
6 replies
CC#
Created by hutonahill on 7/29/2024 in #help
Identity 2FA wont enable
working in implementing my own login procedures. I've got a /register endpoint. this is mostly like the default, but it enables/resets 2FA.
...
// turn on 2FA and get the key
await userManager.SetTwoFactorEnabledAsync(user, true);

// get the newly defined key
string? key = await userManager.GetAuthenticatorKeyAsync(user);

// make sure we get the key.
if (string.IsNullOrEmpty(key)) {
await userManager.ResetAuthenticatorKeyAsync(user);
key = await userManager.GetAuthenticatorKeyAsync(user);

if (string.IsNullOrEmpty(key)) {
throw new NotSupportedException("The user manager must produce an authenticator key.");
}
}

// Return the shared key and indicate successful registration
return TypedResults.Ok(new RegistrationResponse(key));
...
// turn on 2FA and get the key
await userManager.SetTwoFactorEnabledAsync(user, true);

// get the newly defined key
string? key = await userManager.GetAuthenticatorKeyAsync(user);

// make sure we get the key.
if (string.IsNullOrEmpty(key)) {
await userManager.ResetAuthenticatorKeyAsync(user);
key = await userManager.GetAuthenticatorKeyAsync(user);

if (string.IsNullOrEmpty(key)) {
throw new NotSupportedException("The user manager must produce an authenticator key.");
}
}

// Return the shared key and indicate successful registration
return TypedResults.Ok(new RegistrationResponse(key));
The issue is when i try to log in it says 2FA is not enabled for the user.
var result = await signInManager.PasswordSignInAsync(login.Email, login.Password, isPersistent, lockoutOnFailure: true);

if (result.RequiresTwoFactor) { // this is false
var result = await signInManager.PasswordSignInAsync(login.Email, login.Password, isPersistent, lockoutOnFailure: true);

if (result.RequiresTwoFactor) { // this is false
as far as i can tell await userManager.SetTwoFactorEnabledAsync(user, true); should flip that switch that requires 2FA but its not? is this something i have to change in set up? some option to change when i add identity?
4 replies
CC#
Created by hutonahill on 7/28/2024 in #help
program wont build in debug
program builds in normal mode, but not debug. found this error in the debug output:
Started Thread 50644
Loaded Assembly 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\System.Runtime.InteropServices.dll'
Loading module C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\System.Runtime.InteropServices.dll in application domain 1:clrhost
Pdb file for assembly C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\System.Runtime.InteropServices.dll was not found or failed to read
Exited Thread 39836
Started Thread 50644
Loaded Assembly 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\System.Runtime.InteropServices.dll'
Loading module C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\System.Runtime.InteropServices.dll in application domain 1:clrhost
Pdb file for assembly C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\System.Runtime.InteropServices.dll was not found or failed to read
Exited Thread 39836
no idea how to approch an eror like this. did i mess up my .NET install? do i just reinstall .NET?
10 replies
CC#
Created by hutonahill on 7/27/2024 in #help
✅ Identity Services Registration not working
I declare a class to handle 'email':
public class MyEmailServices<TUser> : IEmailSender {
private readonly string _logFilePath = "fakeMail.txt";

public MyEmailServices() {

}

public async Task SendEmailAsync(string email, string subject, string message)
{
// Format the log entry
string logEntry = $"[{DateTime.Now}] To: {email}\nSubject: {subject}\nMessage: {message}\n\n";

// Append the log entry to the file
await File.AppendAllTextAsync(_logFilePath, logEntry);
}
}
public class MyEmailServices<TUser> : IEmailSender {
private readonly string _logFilePath = "fakeMail.txt";

public MyEmailServices() {

}

public async Task SendEmailAsync(string email, string subject, string message)
{
// Format the log entry
string logEntry = $"[{DateTime.Now}] To: {email}\nSubject: {subject}\nMessage: {message}\n\n";

// Append the log entry to the file
await File.AppendAllTextAsync(_logFilePath, logEntry);
}
}
Then in Program.cs I register the service:
builder.Services.AddTransient<IEmailSender, MyEmailServices<IdentityUser>>();
builder.Services.AddTransient<IEmailSender, MyEmailServices<IdentityUser>>();
Finally i try and grab the service and it throws an error
var emailSender = endpoints.ServiceProvider.GetRequiredService<IEmailSender<TUser>>();
var emailSender = endpoints.ServiceProvider.GetRequiredService<IEmailSender<TUser>>();
System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.IEmailSender`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.IEmailSender`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
Everywhere i look it people use this same method to register the emailsender, so i am not sure what i am doing wrong.
14 replies