BigggMoustache
BigggMoustache
CC#
Created by BigggMoustache on 8/26/2023 in #help
❔ JWT Authentication: Name goes to claims not identity.Name
48 replies
CC#
Created by BigggMoustache on 8/13/2023 in #help
❔ Registered Services ArMissing
This is in a Hosted Blazor WASM Client project in case that matters. The Index page injecting dependency for UserAuthenticationStateProvider and UserService, which give missing type or namespace error. ) There's no typos lol
@page "/"
@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@inject UserAuthenticationStateProvider UserAuthenticationStateProvider
@inject UserService UserService

<PageTitle>Index</PageTitle>

<div>Full name: @UserAuthenticationStateProvider.CurrentUser.FullName</div>
<div>Username: @UserAuthenticationStateProvider.CurrentUser.Username</div>
<div>Token: @UserService._authenticationDataMemoryStorage.Token</div>
@page "/"
@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@inject UserAuthenticationStateProvider UserAuthenticationStateProvider
@inject UserService UserService

<PageTitle>Index</PageTitle>

<div>Full name: @UserAuthenticationStateProvider.CurrentUser.FullName</div>
<div>Username: @UserAuthenticationStateProvider.CurrentUser.Username</div>
<div>Token: @UserService._authenticationDataMemoryStorage.Token</div>
here's the program.cs builder stuff
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<AuthenticationDataMemoryStorage>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<UserAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<UserAuthenticationStateProvider>());
builder.Services.AddAuthorizationCore();

await builder.Build().RunAsync();
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<AuthenticationDataMemoryStorage>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<UserAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<UserAuthenticationStateProvider>());
builder.Services.AddAuthorizationCore();

await builder.Build().RunAsync();
3 replies
CC#
Created by BigggMoustache on 3/30/2023 in #help
❔ VS SQL Server Object Explorer Default Click Behavior
Is there an option for changing the on click behavior of items in the SQL Server Object Explorer like you can the objects in Solution Explorer window pane? I'd like the default to be 'View Data' on click, the same way Solution Explorer on click shows file content by default.
2 replies
CC#
Created by BigggMoustache on 3/26/2023 in #help
✅ IEnum and IQueryable usage.
My Controller action is here.
public async Task<IActionResult> Index(IndexViewModel model, string? filter, SortOption? sort, int? pageIndex)
{
var decks = _mtgDbContext.Decks.AsEnumerable();
var decksIQ = _mtgDbContext.Decks.AsQueryable();


if (!string.IsNullOrEmpty(filter))
{
decks = decks.Where(t => t.Name.Contains(filter, StringComparison.OrdinalIgnoreCase));
}

if (sort is { } s)
{
decks = s switch
{
SortOption.NameDesc => decks.OrderByDescending(t => t.Name),
SortOption.NameAsc => decks.OrderBy(t => t.Name),
_ => decks.OrderBy(t => t.Name)
};
}

var deckIQ = decks.AsQueryable();
var pageSize = _configuration.GetValue("PageSize", 3);
var paginatedList = await PaginatedList<Deck>.CreateAsync(decksIQ, pageIndex ?? 1, pageSize);

model.Decks = paginatedList;
model.Filter = filter;
model.Sort = sort;
return View(model);
}
public async Task<IActionResult> Index(IndexViewModel model, string? filter, SortOption? sort, int? pageIndex)
{
var decks = _mtgDbContext.Decks.AsEnumerable();
var decksIQ = _mtgDbContext.Decks.AsQueryable();


if (!string.IsNullOrEmpty(filter))
{
decks = decks.Where(t => t.Name.Contains(filter, StringComparison.OrdinalIgnoreCase));
}

if (sort is { } s)
{
decks = s switch
{
SortOption.NameDesc => decks.OrderByDescending(t => t.Name),
SortOption.NameAsc => decks.OrderBy(t => t.Name),
_ => decks.OrderBy(t => t.Name)
};
}

var deckIQ = decks.AsQueryable();
var pageSize = _configuration.GetValue("PageSize", 3);
var paginatedList = await PaginatedList<Deck>.CreateAsync(decksIQ, pageIndex ?? 1, pageSize);

model.Decks = paginatedList;
model.Filter = filter;
model.Sort = sort;
return View(model);
}
The pagination example from docs uses IQueryable so I was doing this to get the IEnum from the sorting part above to work with it.
var deckIQ = decks.AsQueryable();
var pageSize = _configuration.GetValue("PageSize", 3);
var paginatedList = await PaginatedList<Deck>.CreateAsync(decksIQ, pageIndex ?? 1, pageSize);
var deckIQ = decks.AsQueryable();
var pageSize = _configuration.GetValue("PageSize", 3);
var paginatedList = await PaginatedList<Deck>.CreateAsync(decksIQ, pageIndex ?? 1, pageSize);
It says decksIQ is equal to the filtered down decks Enum after processing the first line, but the third line when passing decksIQ in the parameter says it's the full unfiltered list again. Why would this happen?
17 replies
CC#
Created by BigggMoustache on 1/31/2023 in #help
❔ Callback Url Always Null
Here's the two functions involved
public IActionResult ExternalLogin(string provider, string returnurl = null)
{
var redirect = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnurl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirect);
return Challenge(properties, provider);
}

public async Task<IActionResult> ExternalLoginCallback(string returnurl = null, string remoteError = null)
{
if(remoteError != null)
{
ModelState.AddModelError(string.Empty, "Error from external provider");
return View("Login");
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if(info == null)
{
return RedirectToAction("Login");
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
return LocalRedirect(returnurl);
}
else
{
ViewData["ReturnUrl"] = returnurl;
ViewData["ProviderDisplayName"] = info.ProviderDisplayName;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginViewModel { Email = email });
}
}
public IActionResult ExternalLogin(string provider, string returnurl = null)
{
var redirect = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnurl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirect);
return Challenge(properties, provider);
}

public async Task<IActionResult> ExternalLoginCallback(string returnurl = null, string remoteError = null)
{
if(remoteError != null)
{
ModelState.AddModelError(string.Empty, "Error from external provider");
return View("Login");
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if(info == null)
{
return RedirectToAction("Login");
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
return LocalRedirect(returnurl);
}
else
{
ViewData["ReturnUrl"] = returnurl;
ViewData["ProviderDisplayName"] = info.ProviderDisplayName;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginViewModel { Email = email });
}
}
I don't know why but the returnurl is always null.
15 replies
CC#
Created by BigggMoustache on 1/20/2023 in #help
❔ External Login Callback (Facebook works, Google doesn't)
This is copied from a youtube tutorial and I've been trying to step through and figure out the problem but I can't get the google part sorted. I added the redirecturi in the return Challenge(properties, provider); to my redirect uri's because I figure that's what's passed to the ExternalLoginCallback. That's the only thing I could think of doing tbh. Here's the code. https://paste.mod.gg/cqujalvdtsac/1
6 replies
CC#
Created by BigggMoustache on 1/2/2023 in #help
✅ Token present on Get but missing on Post using Identity
6 replies
CC#
Created by BigggMoustache on 11/18/2022 in #help
❔ Viewing List from ViewBag
I'm not sure what to cast to make the result in ViewBag.CardsReturned usable in the view. (Sorry if this was a load of unnecessary information) Method creating the ViewBag:
public async Task<IActionResult> Search(string searchString)
{
ICardService service = serviceProvider.GetCardService();
var result = await service.Where(x => x.Name, searchString).AllAsync();
ViewBag.CardsReturned = result;
return View();
}
public async Task<IActionResult> Search(string searchString)
{
ICardService service = serviceProvider.GetCardService();
var result = await service.Where(x => x.Name, searchString).AllAsync();
ViewBag.CardsReturned = result;
return View();
}
What ICardService and AllSync are:
public interface ICardService : IMtgQueryable<ICardService, CardQueryParameter>
{
//
// Summary:
// Gets all the MtgApiManager.Lib.Model.Card defined by the query parameters.
//
// Returns:
// A MtgApiManager.Lib.Core.IOperationResult`1 representing the result containing
// all the items.
Task<IOperationResult<List<ICard>>> AllAsync();

//
// Summary:
// Find a specific card by its multi verse identifier.
//
// Parameters:
// multiverseId:
// The multi verse identifier to query for.
//
// Returns:
// A MtgApiManager.Lib.Core.IOperationResult`1 representing the result containing
// a MtgApiManager.Lib.Model.Card or an exception.
public interface ICardService : IMtgQueryable<ICardService, CardQueryParameter>
{
//
// Summary:
// Gets all the MtgApiManager.Lib.Model.Card defined by the query parameters.
//
// Returns:
// A MtgApiManager.Lib.Core.IOperationResult`1 representing the result containing
// all the items.
Task<IOperationResult<List<ICard>>> AllAsync();

//
// Summary:
// Find a specific card by its multi verse identifier.
//
// Parameters:
// multiverseId:
// The multi verse identifier to query for.
//
// Returns:
// A MtgApiManager.Lib.Core.IOperationResult`1 representing the result containing
// a MtgApiManager.Lib.Model.Card or an exception.
55 replies
CC#
Created by BigggMoustache on 10/5/2022 in #help
Scaffolding Error - Requires a primary key to be defined
59 replies
CC#
Created by BigggMoustache on 9/24/2022 in #help
GetStreamAsync() Stream Always Null [Answered]
118 replies
CC#
Created by BigggMoustache on 9/22/2022 in #help
Download from URI in model error
Other problem was solved, now I've this one xD. Trying to do the following:
public static async Task DownloadFunction(List<Card> cards)
{
foreach (var card in cards)
{
byte[] fileBytes = await client.GetByteArrayAsync(card.ImageUris.Small);
File.WriteAllBytes($@"C:\Users\samue\Desktop\MTGImages\{card.Root.name}", fileBytes);
}
}
public static async Task DownloadFunction(List<Card> cards)
{
foreach (var card in cards)
{
byte[] fileBytes = await client.GetByteArrayAsync(card.ImageUris.Small);
File.WriteAllBytes($@"C:\Users\samue\Desktop\MTGImages\{card.Root.name}", fileBytes);
}
}
and getting errors
Error CS0120 An object reference is required for the non-static field, method, or property 'Card.ImageUris.Small'
Error CS0120 An object reference is required for the non-static field, method, or property 'Card.ImageUris.Small'
Error CS0572 'ImageUris': cannot reference a type through an expression; try 'Card.ImageUris' instead
Error CS0572 'ImageUris': cannot reference a type through an expression; try 'Card.ImageUris' instead
184 replies
CC#
Created by BigggMoustache on 9/20/2022 in #help
I can't JSON to List ;_; [Answered]
The JSON value could not be converted to System.Collections.Generic.List`1[Card]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'
The JSON value could not be converted to System.Collections.Generic.List`1[Card]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'
That's my error Here's my attempt to just call and dump it into a List.
private static async Task ProcessRepositories()
{
var stringTask = client.GetStringAsync("https://api.magicthegathering.io/v1/cards/");
var msg = await stringTask;
var cards = JsonSerializer.Deserialize<List<Card>>(msg);
}
private static async Task ProcessRepositories()
{
var stringTask = client.GetStringAsync("https://api.magicthegathering.io/v1/cards/");
var msg = await stringTask;
var cards = JsonSerializer.Deserialize<List<Card>>(msg);
}
190 replies
CC#
Created by BigggMoustache on 9/7/2022 in #help
ReadKey() input question [Answered]
5 replies
CC#
Created by BigggMoustache on 8/29/2022 in #help
How to subscribe an EventHandler? [Answered]
I don't understand how to subscribe this. I don't get it. I honestly don't even know why I used an EventHandler instead of an Action or something.
CharberryTree tree = new CharberryTree();
while (true)
tree.MaybeGrow();

public class CharberryTree
{
public event EventHandler<RipenedEventArgs>? Ripened;

public CharberryTree()
{

}
private Random _random = new Random();
public bool Ripe { get; set; }
public void MaybeGrow()
{
// Only a tiny chance of ripening each time, but we try a lot!
if (_random.NextDouble() < 0.00000001 && !Ripe)
{
Ripe = true;
Ripened?.Invoke(this, new RipenedEventArgs(Ripe));
}
}
}

public class Notifier
{
public Notifier(CharberryTree tree)
{
tree.Ripened += OnRipened();
}
public void OnRipened()
{

}
}

public class Harvester
{
public Harvester(CharberryTree tree)
{

}
}

public class RipenedEventArgs : EventArgs
{
public bool Ripe { get; set; }
public RipenedEventArgs(bool ripe) => Ripe = ripe;
}
CharberryTree tree = new CharberryTree();
while (true)
tree.MaybeGrow();

public class CharberryTree
{
public event EventHandler<RipenedEventArgs>? Ripened;

public CharberryTree()
{

}
private Random _random = new Random();
public bool Ripe { get; set; }
public void MaybeGrow()
{
// Only a tiny chance of ripening each time, but we try a lot!
if (_random.NextDouble() < 0.00000001 && !Ripe)
{
Ripe = true;
Ripened?.Invoke(this, new RipenedEventArgs(Ripe));
}
}
}

public class Notifier
{
public Notifier(CharberryTree tree)
{
tree.Ripened += OnRipened();
}
public void OnRipened()
{

}
}

public class Harvester
{
public Harvester(CharberryTree tree)
{

}
}

public class RipenedEventArgs : EventArgs
{
public bool Ripe { get; set; }
public RipenedEventArgs(bool ripe) => Ripe = ripe;
}
386 replies
CC#
Created by BigggMoustache on 8/28/2022 in #help
I don't understand what this is asking for at all (sry for bad title) [Answered]
Create a Sieve class with a public bool IsGood(int number) method. This class needs a constructor with a delegate parameter that can be invoked later within the IsGood method. Hint: You can make your own delegate type or use Func<int, bool>
Create a Sieve class with a public bool IsGood(int number) method. This class needs a constructor with a delegate parameter that can be invoked later within the IsGood method. Hint: You can make your own delegate type or use Func<int, bool>
299 replies
CC#
Created by BigggMoustache on 8/26/2022 in #help
while() loop exits after first run [Answered]
int targetNumber = RandomNumberGenerator();
Console.WriteLine($"TargetNumber = {targetNumber}");
MainLoop();

void MainLoop()
{

bool parseSuccess = false;
int answerInt = 0;

while(!parseSuccess && answerInt != targetNumber)
{
parseSuccess = int.TryParse(Texting(), out answerInt);
if (parseSuccess && answerInt == targetNumber)
{
Console.WriteLine("Success!");
EndGame();
}
if (parseSuccess && answerInt != targetNumber)
{
Console.WriteLine("Wrong!");
}
if (!parseSuccess)
{
Console.WriteLine("That's not a valid numeral!");
}
}

}

string Texting()
{
Console.Write("Guess a number between 1 and 10: ");
string ?answer = Console.ReadLine();
if (string.IsNullOrEmpty(answer))
{
Console.WriteLine("Actually enter something!");
Texting();
}
return answer;
}

int RandomNumberGenerator()
{
Random random = new Random();
int randomInt = random.Next(1, 11);
return randomInt;
}

void EndGame()
{
Console.WriteLine("Would you like to play again");
string input = Console.ReadLine();
if (input == "yes")
{
targetNumber = RandomNumberGenerator();
MainLoop();
}
}
int targetNumber = RandomNumberGenerator();
Console.WriteLine($"TargetNumber = {targetNumber}");
MainLoop();

void MainLoop()
{

bool parseSuccess = false;
int answerInt = 0;

while(!parseSuccess && answerInt != targetNumber)
{
parseSuccess = int.TryParse(Texting(), out answerInt);
if (parseSuccess && answerInt == targetNumber)
{
Console.WriteLine("Success!");
EndGame();
}
if (parseSuccess && answerInt != targetNumber)
{
Console.WriteLine("Wrong!");
}
if (!parseSuccess)
{
Console.WriteLine("That's not a valid numeral!");
}
}

}

string Texting()
{
Console.Write("Guess a number between 1 and 10: ");
string ?answer = Console.ReadLine();
if (string.IsNullOrEmpty(answer))
{
Console.WriteLine("Actually enter something!");
Texting();
}
return answer;
}

int RandomNumberGenerator()
{
Random random = new Random();
int randomInt = random.Next(1, 11);
return randomInt;
}

void EndGame()
{
Console.WriteLine("Would you like to play again");
string input = Console.ReadLine();
if (input == "yes")
{
targetNumber = RandomNumberGenerator();
MainLoop();
}
}
32 replies
CC#
Created by BigggMoustache on 8/25/2022 in #help
Example of 'Exception Continuing Up The Stack'? [Answered]
Quote from book "Only Handle What You Can Fix: If an exception handler cannot resolve the problem represented by the exception, the handler should not exist. Instead, the exception should be allowed to continue up the call stack, hoping that something farther up has meaningful resolution steps for the problem. This is a counterpoint to the previous item. If there is no recourse for an error, it is reasonable for the program to end. There are some allowances here. Sometimes, a handler will repair or address what it can (even just logging the problem) while still allowing the exception to continue (described later)." I'm having a hard time conceptualizing when to use try catch because things break all over the place lol and how 'continuing up the stack' can resolve the issue.
22 replies
CC#
Created by BigggMoustache on 8/17/2022 in #help
Move File To A Matching Type Refactoring
When everything is top-level do you not need namespaces because everything is "top-level"? Thanks for helping my understanding.
20 replies
CC#
Created by BigggMoustache on 8/16/2022 in #help
Replace text in VS within scope or highlighted?
I'd like to replace a specific section of text in the same way ctrl+r+r would but couldn't find an answer googling. Thanks!
7 replies