populus
populus
CC#
Created by populus on 2/13/2023 in #help
❔ Implementing RoleStore/RoleManager
Hey, I'm dealing with roles for my 2nd time ever and I can't seem to figure this out.
System.NullReferenceException: 'Object reference not set to an instance of an object.'

roleStore was null.
System.NullReferenceException: 'Object reference not set to an instance of an object.'

roleStore was null.
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>();
UserManager<Account>? userManager = services.GetService<UserManager<Account>>();
var roleStore = services.GetService<RoleStore<IdentityRole>>();
var roleManager = services.GetService<RoleManager<Account>>();

// Create my user.
var user = new Account { UserName = "foo", Email = "foo" };
var password = "foo";
await userManager.CreateAsync(user, password);

// Create role(s).
var rolea = new IdentityRole { Name = "Blogger" };
var roleb = new IdentityRole { Name = "Discusser" };
var rolec = new IdentityRole { Name = "Planner" };

// Insert role(s) into "RoleStore".
var roleTasks = new Task[] {
roleStore.CreateAsync(rolea),
roleStore.CreateAsync(roleb),
roleStore.CreateAsync(rolec)
};
await Task.WhenAll(roleTasks);

// Assign the role(s) to my user.
await userManager.AddToRoleAsync(user, "Blogger");
await userManager.AddToRoleAsync(user, "Discusser");
await userManager.AddToRoleAsync(user, "Planner");
}
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>();
UserManager<Account>? userManager = services.GetService<UserManager<Account>>();
var roleStore = services.GetService<RoleStore<IdentityRole>>();
var roleManager = services.GetService<RoleManager<Account>>();

// Create my user.
var user = new Account { UserName = "foo", Email = "foo" };
var password = "foo";
await userManager.CreateAsync(user, password);

// Create role(s).
var rolea = new IdentityRole { Name = "Blogger" };
var roleb = new IdentityRole { Name = "Discusser" };
var rolec = new IdentityRole { Name = "Planner" };

// Insert role(s) into "RoleStore".
var roleTasks = new Task[] {
roleStore.CreateAsync(rolea),
roleStore.CreateAsync(roleb),
roleStore.CreateAsync(rolec)
};
await Task.WhenAll(roleTasks);

// Assign the role(s) to my user.
await userManager.AddToRoleAsync(user, "Blogger");
await userManager.AddToRoleAsync(user, "Discusser");
await userManager.AddToRoleAsync(user, "Planner");
}
Secondly if I implement the following code I get a massive error when trying to build the builder.
//builder.Services.AddScoped<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>();
//builder.Services.AddScoped<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>();
2 replies
CC#
Created by populus on 2/12/2023 in #help
✅ ForeignKey Entity Framework and Identity
I've got the following classes: "Account", "Post", "Tag" and "Image". The "Post" class contains the following:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid? PostId { get; set; }

public List<Tag> Tags { get; set; }

public List<Image> AttachedImages { get; set; }

[ForeignKey("Account")]
public Guid? OriginalPosterId { get; set; }
public Account? OriginalPoster { get; set; }

[ForeignKey("Account")]
public List<Guid> PostParticipantsIds { get; set; }
public virtual ICollection<Account> PostParticipants { get; set; }

[ForeignKey("Account")]
public List<Guid> UsersAttendingIds { get; set; }
public virtual ICollection<Account> UsersAttending { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid? PostId { get; set; }

public List<Tag> Tags { get; set; }

public List<Image> AttachedImages { get; set; }

[ForeignKey("Account")]
public Guid? OriginalPosterId { get; set; }
public Account? OriginalPoster { get; set; }

[ForeignKey("Account")]
public List<Guid> PostParticipantsIds { get; set; }
public virtual ICollection<Account> PostParticipants { get; set; }

[ForeignKey("Account")]
public List<Guid> UsersAttendingIds { get; set; }
public virtual ICollection<Account> UsersAttending { get; set; }
I can't seem to quite understand how this type of mapping works. Why can't the Lists simply reference the correct AccountId? I see no reason there could not be different fields referencing the same "Id" for different purposes. What am I doing wrong?
24 replies
CC#
Created by populus on 2/4/2023 in #help
❔ View cannot be found.
LoginModel.cs Pages/Account/Login.cshtml Pages/Account/Register.cshtml AccountController.cs attached. Why am I getting the following error when submitting a POST request?
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Register' was not found. The following locations were searched:
/Views/Account/Register.cshtml
/Views/Shared/Register.cshtml
/Pages/Shared/Register.cshtml
Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable<string> originalLocations)
An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Register' was not found. The following locations were searched:
/Views/Account/Register.cshtml
/Views/Shared/Register.cshtml
/Pages/Shared/Register.cshtml
Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable<string> originalLocations)
23 replies
CC#
Created by populus on 2/3/2023 in #help
❔ Unsupported Media Type - Razor page
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"00-de8ff040b623653dab0b747f6f7991ff-34ebbb1f01794d2d-00"}
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"00-de8ff040b623653dab0b747f6f7991ff-34ebbb1f01794d2d-00"}
The 415 (Unsupported Media Type) status code indicates that the
origin server is refusing to service the request because the payload
is in a format not supported by this method on the target resource.
The format problem might be due to the request's indicated
Content-Type or Content-Encoding, or as a result of inspecting the
data directly.
The 415 (Unsupported Media Type) status code indicates that the
origin server is refusing to service the request because the payload
is in a format not supported by this method on the target resource.
The format problem might be due to the request's indicated
Content-Type or Content-Encoding, or as a result of inspecting the
data directly.
I haven't run into this type of problem before. Setting breakpoints in Visual Studio isn't triggering the breakpoints. It just shows me the first code-block provided in the browser. Here's the "Pages/Account/Register.cshtml":
@page
@{
ViewData["Title"] = "Register";
}
@model CommunityWebsite_Lexicon_Project.Models.LoginModel
@{
<h3>Register</h3>
<form asp-action="Register" asp-controller="Account" method="post">
<div asp-validation-summary="ModelOnly"></div>

<h4>Email</h4>
<input asp-for="Email" type="email" />
<span asp-validation-for="Email"></span>

<h4>Username</h4>
<input asp-for="Username" type="text" />
<span asp-validation-for="Username"></span>

<h4>Password</h4>
<input asp-for="Password" type="password" />
<span asp-validation-for="Password"></span>

<h4>Confirm Password</h4>
<input asp-for="PasswordConfirm" type="password" />
<span asp-validation-for="PasswordConfirm"></span>

<button type="submit" value="Register">Register</button>
</form>
}
@{
if (ViewBag.Message != null)
{
<div>
@ViewBag.Message
</div>
}
}
@page
@{
ViewData["Title"] = "Register";
}
@model CommunityWebsite_Lexicon_Project.Models.LoginModel
@{
<h3>Register</h3>
<form asp-action="Register" asp-controller="Account" method="post">
<div asp-validation-summary="ModelOnly"></div>

<h4>Email</h4>
<input asp-for="Email" type="email" />
<span asp-validation-for="Email"></span>

<h4>Username</h4>
<input asp-for="Username" type="text" />
<span asp-validation-for="Username"></span>

<h4>Password</h4>
<input asp-for="Password" type="password" />
<span asp-validation-for="Password"></span>

<h4>Confirm Password</h4>
<input asp-for="PasswordConfirm" type="password" />
<span asp-validation-for="PasswordConfirm"></span>

<button type="submit" value="Register">Register</button>
</form>
}
@{
if (ViewBag.Message != null)
{
<div>
@ViewBag.Message
</div>
}
}
6 replies
CC#
Created by populus on 1/3/2023 in #help
❔ Entity Framework - SqlException
Microsoft.Data.SqlClient.SqlException: '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: SNI_PN11, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid.
)'
Microsoft.Data.SqlClient.SqlException: '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: SNI_PN11, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid.
)'
internal static async Task Initialize(WebScraperContext context)
{
context.Database.Migrate();
}
internal static async Task Initialize(WebScraperContext context)
{
context.Database.Migrate();
}
using (var db = new WebScraperContext())
{
db.Database.EnsureCreated();
db.SaveChanges();
}
using (var db = new WebScraperContext())
{
db.Database.EnsureCreated();
db.SaveChanges();
}
public class WebScraperContext : DbContext
{
public DbSet<WebPage> WebPages { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\\MSSQLLocalDB;Database=my_localnetwork;Trusted_Connection=True;");
}
}
public class WebScraperContext : DbContext
{
public DbSet<WebPage> WebPages { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\\MSSQLLocalDB;Database=my_localnetwork;Trusted_Connection=True;");
}
}
15 replies
CC#
Created by populus on 12/3/2022 in #help
❔ Invalid column name 'CityId'.
Working on MVC and EF, created repos,services,viewmodels etc. About to fire up and see if everything is working, accessing the People index causes user-handled exception 'Invalid column name 'CityId''. I have not explicitly typed 'CityId' anywhere, wondering where this variable comes from. Any takers?
6 replies
CC#
Created by populus on 10/25/2022 in #help
Sequential 'ForEach' functions doesn't work.
tileMap01.mapGrid.forEach( element => {
element.forEach( ele => {
console.log(ele);
switch(ele) {
case " ":
let iele = document.createElement(img);
iele.id = "emptyImg" + counter++;
console.log(iele.id);
iele.src = "/images/tile1.png";

console.log(iele);

document.body.appendChild(iele);
tileMap01.mapGrid.forEach( element => {
element.forEach( ele => {
console.log(ele);
switch(ele) {
case " ":
let iele = document.createElement(img);
iele.id = "emptyImg" + counter++;
console.log(iele.id);
iele.src = "/images/tile1.png";

console.log(iele);

document.body.appendChild(iele);
10 replies
CC#
Created by populus on 10/16/2022 in #help
{ expected when creating new razor page.
83 replies
CC#
Created by populus on 9/27/2022 in #help
Nested KeyValuePair
private KeyValuePair<string, double> priceAndCurrency;

private KeyValuePair<string, KeyValuePair<>> periodAndPriceAndCurrency;
private KeyValuePair<string, double> priceAndCurrency;

private KeyValuePair<string, KeyValuePair<>> periodAndPriceAndCurrency;
I want to create a to-do / shopping list and need to write up price in selected currency and also have a datapoint for things like subscriptions or even due bills. Any other type that would be simpler than what I'm trying to do here? If no, what's wrong with what I'm doing?
6 replies
CC#
Created by populus on 9/13/2022 in #help
Hangman exercise - line 41-47 not behaving.
https://pastebin.com/NdZFzCcX
https://pastebin.com/NdZFzCcX
4 replies
CC#
Created by populus on 9/10/2022 in #help
Return amount of denominations
static void RunExerciseNineteen()
{
int price = 150;
Console.WriteLine($"It'll cost you: {price}\nHow much are you providing?");
int input = Convert.ToInt32(Console.ReadLine());
int[] denominations = new int[] { 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000 };
int temp = 0;

int retur = input - price; // Remainder. (Negative if insufficient).
Console.WriteLine(retur); // Print how much is owed.
if (retur < 0)
{
Console.WriteLine("You didn't provide enough funds.");
} else if (retur > 0)
{
for (int i = denominations.Length - 1; i >= 0; i--)
{
if (denominations[i] / retur == 1 && retur > denominations[i])
{
retur += denominations[i];
}
}
}
Console.WriteLine("Retur: " + retur);
}
static void RunExerciseNineteen()
{
int price = 150;
Console.WriteLine($"It'll cost you: {price}\nHow much are you providing?");
int input = Convert.ToInt32(Console.ReadLine());
int[] denominations = new int[] { 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000 };
int temp = 0;

int retur = input - price; // Remainder. (Negative if insufficient).
Console.WriteLine(retur); // Print how much is owed.
if (retur < 0)
{
Console.WriteLine("You didn't provide enough funds.");
} else if (retur > 0)
{
for (int i = denominations.Length - 1; i >= 0; i--)
{
if (denominations[i] / retur == 1 && retur > denominations[i])
{
retur += denominations[i];
}
}
}
Console.WriteLine("Retur: " + retur);
}
I'm having trouble constructing the logic behind returning bills. Am I on the right path? What am I missing?
33 replies
CC#
Created by populus on 9/10/2022 in #help
double array yields only zeroes
static void RunExerciseSixteen()
{
int[] ints = new int[10];
Random rnd = new Random();
double[] dbls = new double[ints.Length];

for (int i = 0; i < ints.Length; i++)
{
ints[i] = rnd.Next(1, 500);
}

for (int i = 0; i < dbls.Length; i++)
{
Convert.ToDouble(dbls[i] = 1 / ints[i]);
}

foreach (int i in ints)
{
Console.WriteLine("Intsarray: " + i);
}
foreach (double i in dbls)
{
Console.WriteLine("Dblsarray: " + i); // Yields '0' repeatedly, why?
}
}
static void RunExerciseSixteen()
{
int[] ints = new int[10];
Random rnd = new Random();
double[] dbls = new double[ints.Length];

for (int i = 0; i < ints.Length; i++)
{
ints[i] = rnd.Next(1, 500);
}

for (int i = 0; i < dbls.Length; i++)
{
Convert.ToDouble(dbls[i] = 1 / ints[i]);
}

foreach (int i in ints)
{
Console.WriteLine("Intsarray: " + i);
}
foreach (double i in dbls)
{
Console.WriteLine("Dblsarray: " + i); // Yields '0' repeatedly, why?
}
}
What am I getting wrong here?
23 replies
CC#
Created by populus on 8/28/2022 in #help
List as a field of an object. [Answered]
public class Character
{
public string? Id { get; set; } // Identifier.
public List<string>? Name { get; set; } // In-game identifier.
}
public class Character
{
public string? Id { get; set; } // Identifier.
public List<string>? Name { get; set; } // In-game identifier.
}
static void Main(string[] args)
{
Character Populus = new Character();
Populus.Name[0] = "test";
}
static void Main(string[] args)
{
Character Populus = new Character();
Populus.Name[0] = "test";
}
What am I doing wrong? I'm trying to have a Character object with ever increasing amount of Names.
14 replies
CC#
Created by populus on 8/21/2022 in #help
Paradoxical initializers [Answered]
Two classes. Class Character and Class Guild. Character has a field of Guild. Guild has an array of Members composed of a Character[] array. Wondering how to re-concile the constructors to allow for creation of one before the other. Code attached:
public class Character
{
public string? Name { get; set; } // In-game identifier.
public Guild? Guild { get; set; } // In-game guild identifier.

public Character(string Name)
{
this.Name = Name;
}

public Character(
string Name,
Guild Guild,
)
{
this.Name = Name;
this.Guild = Guild;
}
}
public class Character
{
public string? Name { get; set; } // In-game identifier.
public Guild? Guild { get; set; } // In-game guild identifier.

public Character(string Name)
{
this.Name = Name;
}

public Character(
string Name,
Guild Guild,
)
{
this.Name = Name;
this.Guild = Guild;
}
}
public class Guild
{
public string? Name { get; set; } // Name of Guild. (i.e "chumbucket & Associates").
public Character[]? Members { get; set; } // Array of characters.

public Guild(string Name, Character[] Members)
{
this.Name = Name;
this.Members = Members;
}
}
public class Guild
{
public string? Name { get; set; } // Name of Guild. (i.e "chumbucket & Associates").
public Character[]? Members { get; set; } // Array of characters.

public Guild(string Name, Character[] Members)
{
this.Name = Name;
this.Members = Members;
}
}
17 replies