Connor
Connor
CC#
Created by Connor on 6/10/2023 in #help
❔ Blazor WASM Default Template 15mb, Production even larger (60mb)
3 replies
CC#
Created by Connor on 5/1/2023 in #help
❔ How to setup the following relationship?
C#
public class Partner
{
public long Id { get; set; }
public ICollection<User> Users { get; set; }
}
public class User
{

public long Id { get; set; }
public long PartnerId { get; set; }
public Partner Partner { get; set; }
public ICollection<Ticket> Tickets { get; set; }
public class Ticket : ITrackedResource
{
public long Id { get; set; }
public long UserId { get; set; }
public User User { get; set; }
// public long PartnerId => User?.PartnerId; // would work with eager loading, lazy loading, or explicit loading but I don’t like any of those
}
public interface ITrackedResource
{
public long PartnerId { get; }
}
C#
public class Partner
{
public long Id { get; set; }
public ICollection<User> Users { get; set; }
}
public class User
{

public long Id { get; set; }
public long PartnerId { get; set; }
public Partner Partner { get; set; }
public ICollection<Ticket> Tickets { get; set; }
public class Ticket : ITrackedResource
{
public long Id { get; set; }
public long UserId { get; set; }
public User User { get; set; }
// public long PartnerId => User?.PartnerId; // would work with eager loading, lazy loading, or explicit loading but I don’t like any of those
}
public interface ITrackedResource
{
public long PartnerId { get; }
}
18 replies
CC#
Created by Connor on 3/14/2023 in #help
❔ How to achieve databinding with render fragments? If at all possible
I know components are a little more suited for this, but this is something I really want to be able to do.
TextInput.razor

<input @bind="Value" @bind:event="oninput" placeholder="Enter text"/>

@code {
private string _value;
[Parameter]
public string Value
{
get => _value;
set
{
_value = value;
if (ValueChanged is {HasDelegate: true})
ValueChanged.InvokeAsync(_value);
}
}
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
}
TextInput.razor

<input @bind="Value" @bind:event="oninput" placeholder="Enter text"/>

@code {
private string _value;
[Parameter]
public string Value
{
get => _value;
set
{
_value = value;
if (ValueChanged is {HasDelegate: true})
ValueChanged.InvokeAsync(_value);
}
}
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
}
I want to be able to use this on a page but as a renderfragment.
//Can't be used with other two, causes infinite loop
@Example1(TestString1)
<p>@TestString1</p>
// ##################################################
@Example2(TestString2)
<p>@TestString2</p>
@Example3(x => TestString3 = x)
<p>@TestString3</p>
@code {
private string TestString1 { get; set; }
private string TestString2 { get; set; }
private string TestString3 { get; set; }
private RenderFragment Example1(string str)
{
return @<TextInput @bind-Value="str" ></TextInput>;
}

private RenderFragment Example2(string str)
{
var action = new Action<string>(value => str = value);
return@<TextInput ValueChanged="action" ></TextInput>;
}

private RenderFragment Example3(Action<string> action)
{
return @<TextInput ValueChanged="action" ></TextInput>;
}
}
//Can't be used with other two, causes infinite loop
@Example1(TestString1)
<p>@TestString1</p>
// ##################################################
@Example2(TestString2)
<p>@TestString2</p>
@Example3(x => TestString3 = x)
<p>@TestString3</p>
@code {
private string TestString1 { get; set; }
private string TestString2 { get; set; }
private string TestString3 { get; set; }
private RenderFragment Example1(string str)
{
return @<TextInput @bind-Value="str" ></TextInput>;
}

private RenderFragment Example2(string str)
{
var action = new Action<string>(value => str = value);
return@<TextInput ValueChanged="action" ></TextInput>;
}

private RenderFragment Example3(Action<string> action)
{
return @<TextInput ValueChanged="action" ></TextInput>;
}
}
Currently only Test3 "works". It appears as if the references to the str in Test1 and Test2 are lost. It would be best if I could put the <input/> directly in the RenderFragment and just bind the value to it but I had to create a component to show that it works with ValueChanged
4 replies
CC#
Created by Connor on 1/17/2023 in #help
❔ Is there any way to test the rendering of a component in Blazor based on different screen sizes?
I have a component that renders a table. It will render a different amount of rows based on screen size (Width < 800px). Is there any way for me to simulate adjusting screen size in BUnit? Couldn’t find any information online about it
2 replies
CC#
Created by Connor on 1/5/2023 in #help
✅ Can you add related data to a DbContext like this
I have these classes where Company.Locations navigates to a Locations table and Location.LocationReviews navigates to a LocationReviews table
public class Company : IEntity
{
public string Id { get; set; }
public string Name { get; set; }
public List<Location> Locations {get;set;}
}
public class Location : IEntity
{
public string Id { get; set; }
public Company Company { get; set; }
public List<LocationReview> LocationReviews { get; set; } = new();
}
public class LocationReview : IEntity
{
public string Id { get; set; }
public Location Location { get; set; }
}
public class Company : IEntity
{
public string Id { get; set; }
public string Name { get; set; }
public List<Location> Locations {get;set;}
}
public class Location : IEntity
{
public string Id { get; set; }
public Company Company { get; set; }
public List<LocationReview> LocationReviews { get; set; } = new();
}
public class LocationReview : IEntity
{
public string Id { get; set; }
public Location Location { get; set; }
}
I have a generic controller that Im now finding out only works for Company entities.
[HttpPut]
public async Task<ActionResult> Save([FromBody] TItem entity)
{
var result = await _dbContext.Set<TItem>().Where(x => x.Id == entity.Id)
.AsNoTracking()
.FirstOrDefaultAsync();
if (result != null)
{
_dbContext.Update(entity);
}
else
{
await _dbContext.Set<TItem>().AddAsync(entity);
}
await _dbContext.SaveChangesAsync();
return Ok();
}
[HttpPut]
public async Task<ActionResult> Save([FromBody] TItem entity)
{
var result = await _dbContext.Set<TItem>().Where(x => x.Id == entity.Id)
.AsNoTracking()
.FirstOrDefaultAsync();
if (result != null)
{
_dbContext.Update(entity);
}
else
{
await _dbContext.Set<TItem>().AddAsync(entity);
}
await _dbContext.SaveChangesAsync();
return Ok();
}
31 replies
CC#
Created by Connor on 1/4/2023 in #help
❔ Unsupported method exception, how do I fix it?
[ApiController]
[Route($"api/[controller]")]
public class CompanyController : ControllerBase
{
private ApplicationDbContext _dbContext;
public CompanyController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpPost("{id}")]
public async Task<ActionResult<TItem>> Get(string id, [FromBody] string[] includes)
{
var result = await _dbContext.Set<Company>()
.Include(x => x.Locations) // THIS CAUSES ERROR
.Where(x => x.Id == id)
.AsNoTracking()
.FirstOrDefaultAsync();
if (result == null)
{
return BadRequest(nameof(TItem) + "Id does not exist");
}
return Ok(result);
}
}


[Test]
public async Task GetTest()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "TestDb")
.Options;
var operationalStoreOptions = Options.Create(new OperationalStoreOptions());

var mockDbContext = new Mock<ApplicationDbContext>(options, operationalStoreOptions);
var mockDbSet = new Mock<DbSet<Company>>();
mockDbContext.Setup(x => x.Set<Company>()).Returns(mockDbSet.Object);
var companyController= new CompanyController(mockDbContext.Object);
var id = "123";
var includes = new string[] { "Locations" };

// Act
var result = await companyController.Get(id, includes);

// Assert
Assert.IsInstanceOf<OkObjectResult>(result);
}
[ApiController]
[Route($"api/[controller]")]
public class CompanyController : ControllerBase
{
private ApplicationDbContext _dbContext;
public CompanyController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpPost("{id}")]
public async Task<ActionResult<TItem>> Get(string id, [FromBody] string[] includes)
{
var result = await _dbContext.Set<Company>()
.Include(x => x.Locations) // THIS CAUSES ERROR
.Where(x => x.Id == id)
.AsNoTracking()
.FirstOrDefaultAsync();
if (result == null)
{
return BadRequest(nameof(TItem) + "Id does not exist");
}
return Ok(result);
}
}


[Test]
public async Task GetTest()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "TestDb")
.Options;
var operationalStoreOptions = Options.Create(new OperationalStoreOptions());

var mockDbContext = new Mock<ApplicationDbContext>(options, operationalStoreOptions);
var mockDbSet = new Mock<DbSet<Company>>();
mockDbContext.Setup(x => x.Set<Company>()).Returns(mockDbSet.Object);
var companyController= new CompanyController(mockDbContext.Object);
var id = "123";
var includes = new string[] { "Locations" };

// Act
var result = await companyController.Get(id, includes);

// Assert
Assert.IsInstanceOf<OkObjectResult>(result);
}
But I get this error
System.NotSupportedException : Specified method is not supported.
at Microsoft.EntityFrameworkCore.DbSet`1.System.Linq.IQueryable.get_Provider()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Include[TEntity](IQueryable`1 source, String navigationPropertyPath)
System.NotSupportedException : Specified method is not supported.
at Microsoft.EntityFrameworkCore.DbSet`1.System.Linq.IQueryable.get_Provider()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Include[TEntity](IQueryable`1 source, String navigationPropertyPath)
28 replies
CC#
Created by Connor on 1/3/2023 in #help
❔ Why does one request work but the other doesn't when they're exactly the same.
private readonly JsonSerializerOptions JsonOptions = new () { ReferenceHandler = ReferenceHandler.Preserve};

// This works
public async Task CreateMany1(IEnumerable<TEntity> entities)
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = JsonContent.Create(entities, new MediaTypeHeaderValue("application/json"), JsonOptions),
RequestUri = new Uri(_httpClient.BaseAddress.AbsoluteUri + "/createmany"),
};
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
}

public async Task CreateMany2(IEnumerable<TEntity> entities)
{
var response = await _httpClient.PostAsJsonAsync("createmany", entities, JsonOptions);
response.EnsureSuccessStatusCode();
}
private readonly JsonSerializerOptions JsonOptions = new () { ReferenceHandler = ReferenceHandler.Preserve};

// This works
public async Task CreateMany1(IEnumerable<TEntity> entities)
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = JsonContent.Create(entities, new MediaTypeHeaderValue("application/json"), JsonOptions),
RequestUri = new Uri(_httpClient.BaseAddress.AbsoluteUri + "/createmany"),
};
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
}

public async Task CreateMany2(IEnumerable<TEntity> entities)
{
var response = await _httpClient.PostAsJsonAsync("createmany", entities, JsonOptions);
response.EnsureSuccessStatusCode();
}
7 replies
CC#
Created by Connor on 12/30/2022 in #help
❔ Visual Studios tooling not migrating the right SQL server
3 replies
CC#
Created by Connor on 12/28/2022 in #help
❔ IIS Server doesn't work when I set IP address to all unasssigned
17 replies
CC#
Created by Connor on 12/19/2022 in #help
❔ How to deal with property’s that need data from a database?
public class Company
{
public float Rating { get; set; }
public async Task<float> GetRating(IMongoService mongoService)
{
var locations = await mongoService.GetLocationsAsync(LocationIds);
if(locations.Count == 0)
return 0;
return locations.Average(location=> location.Rating)

}

public List<string> LocationIds { get; set; } = new List<string>();
}
public class Company
{
public float Rating { get; set; }
public async Task<float> GetRating(IMongoService mongoService)
{
var locations = await mongoService.GetLocationsAsync(LocationIds);
if(locations.Count == 0)
return 0;
return locations.Average(location=> location.Rating)

}

public List<string> LocationIds { get; set; } = new List<string>();
}
I have a Blazor page where I want to display a Company’s rating which is the average of its location ratings. The problem is, I only store the locationIds on the company, not all the data. The best, botched solution I’ve come up with is doing company.Rating = company.GetRating() on initialization (I need the mongo service from the Blazor page to even get it); I can’t remove the Rating property because you can put as async method in html. I feel like a better solution might lie in Lazy initialization or something. I really don’t know though, hence why I’m here. I’m also currently “cluttering” the db of Companies with a Rating property that is always 0 (I get it on demand)
2 replies
CC#
Created by Connor on 11/19/2022 in #help
How to convert this method into a generic one?
private List<string> GetEnumNamesCorrected()
{
var correctedNames = new List<string>();
foreach (var enumName in Enum.GetNames(typeof(ManagerType)))
{
var wordsInType =
Regex.Matches(enumName.ToString(), @"([A-Z][a-z]+)")
.Cast<Match>()
.Select(m => m.Value);

var withSpaces = string.Join(" ", wordsInType);
correctedNames.Add(withSpaces);
}
return correctedNames;
} // Outpets new() { "Human Resources", "General Manager" } just converts to string and adds space at Capital letters
public enum ManagerType
{
HumanResources,
GeneralManager
}
private List<string> GetEnumNamesCorrected()
{
var correctedNames = new List<string>();
foreach (var enumName in Enum.GetNames(typeof(ManagerType)))
{
var wordsInType =
Regex.Matches(enumName.ToString(), @"([A-Z][a-z]+)")
.Cast<Match>()
.Select(m => m.Value);

var withSpaces = string.Join(" ", wordsInType);
correctedNames.Add(withSpaces);
}
return correctedNames;
} // Outpets new() { "Human Resources", "General Manager" } just converts to string and adds space at Capital letters
public enum ManagerType
{
HumanResources,
GeneralManager
}
I want to be able to do ManagerType.GetEnumNamesCorrected(), as well as with all my other enums. I've come up with this sudo code but it doesn't work
public static class ExtensionMethods
{
public static List<string> GetEnumNamesCorrected<T>(this T enu) where T : Enum
{
var correctedNames = new List<string>();
foreach (var enumName in Enum.GetNames(typeof(enu))) // this is an error
{
var wordsInType =
Regex.Matches(enumName.ToString(), @"([A-Z][a-z]+)")
.Cast<Match>()
.Select(m => m.Value);

var withSpaces = string.Join(" ", wordsInType);
correctedNames.Add(withSpaces);
}
return correctedNames;
}
}
public static class ExtensionMethods
{
public static List<string> GetEnumNamesCorrected<T>(this T enu) where T : Enum
{
var correctedNames = new List<string>();
foreach (var enumName in Enum.GetNames(typeof(enu))) // this is an error
{
var wordsInType =
Regex.Matches(enumName.ToString(), @"([A-Z][a-z]+)")
.Cast<Match>()
.Select(m => m.Value);

var withSpaces = string.Join(" ", wordsInType);
correctedNames.Add(withSpaces);
}
return correctedNames;
}
}
20 replies
CC#
Created by Connor on 11/11/2022 in #help
❔ Enumerable.Current is not null in debug mode but assigns null to variable
7 replies
CC#
Created by Connor on 10/19/2022 in #help
Don’t understand nullable reference types
17 replies