electronic heartbreak.
electronic heartbreak.
CC#
Created by electronic heartbreak. on 8/23/2024 in #help
Azurite to run in VS or Docker
As the title suggests I wonder if there are any tradeoffs whether I should use Azurite through the built-in Visual Studio method or to implement it through Docker? The project is already configured in Docker, so maybe that's a hint it should be used through Docker too?
1 replies
CC#
Created by electronic heartbreak. on 7/18/2024 in #help
Using IFormFile in Web API project results in network failure.
Hello everyone reading this thread, As the title suggests, I am trying to upload an image using the IFormFile interface in a property. When I upload the image, the system 'crashes' and I get a network failure with the following message:
Undocumented
Failed to fetch.
Possible Reasons:

CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
Undocumented
Failed to fetch.
Possible Reasons:

CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
This is the only code I have added to a default ASP .NET Web API project: Controller:
c#
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpPost("simplepost")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Create(IFormFile file)
{
Debug.WriteLine(file.FileName);

return Ok(file.FileName);
}

[HttpPost("uploadfile")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> UploadFile([FromForm] DtoImage model)
{
try
{
_logger.LogInformation("UploadFile called.");

if (model.File == null || model.File.Length == 0)
{
_logger.LogWarning("No file uploaded.");
return BadRequest("No file uploaded.");
}

if (string.IsNullOrEmpty(model.Name))
{
_logger.LogWarning("No name provided.");
return BadRequest("No name provided.");
}

var uploadsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
_logger.LogInformation("Uploads directory: {UploadsDirectory}", uploadsDirectory);
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Internal server error.");
return StatusCode(500, $"Internal server error: {ex.Message}");
}}}
c#
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpPost("simplepost")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Create(IFormFile file)
{
Debug.WriteLine(file.FileName);

return Ok(file.FileName);
}

[HttpPost("uploadfile")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> UploadFile([FromForm] DtoImage model)
{
try
{
_logger.LogInformation("UploadFile called.");

if (model.File == null || model.File.Length == 0)
{
_logger.LogWarning("No file uploaded.");
return BadRequest("No file uploaded.");
}

if (string.IsNullOrEmpty(model.Name))
{
_logger.LogWarning("No name provided.");
return BadRequest("No name provided.");
}

var uploadsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
_logger.LogInformation("Uploads directory: {UploadsDirectory}", uploadsDirectory);
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Internal server error.");
return StatusCode(500, $"Internal server error: {ex.Message}");
}}}
6 replies
CC#
Created by electronic heartbreak. on 7/13/2024 in #help
How is Modelstate.IsValid triggered?
Hello! I am reading this tutorial on how DTO's can be implemented with API's: https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e The process in this tutorial seems normal and you can easily follow along. There are only 2 things I have my questions about: 1. The Driver class in this tutorial has no DataAnnotations (see first codeblock). How come the Modelstate.IsValid can be triggered in codeblock 2?
namespace SampleMapper.Models;

public class Driver
{
public Guid Id { get; set; }
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public int DriverNumber { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateUpdated { get; set; }
public int Status { get; set; }
public int WorldChampionships { get; set; }
}
namespace SampleMapper.Models;

public class Driver
{
public Guid Id { get; set; }
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public int DriverNumber { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateUpdated { get; set; }
public int Status { get; set; }
public int WorldChampionships { get; set; }
}
2. How does Modelstate.IsValid get triggered when a Dto is passed but it gets mapped to an entity?
[HttpPost]
public IActionResult CreateDriver(DriverCreationDto data)
{
var _driver = _mapper.Map<Driver>(data);

if(ModelState.IsValid)
{
drivers.Add(_driver);

return CreatedAtAction("GetDriver", new {_driver.Id}, data);
}

return new JsonResult("Something went wrong") {StatusCode = 500};
}
[HttpPost]
public IActionResult CreateDriver(DriverCreationDto data)
{
var _driver = _mapper.Map<Driver>(data);

if(ModelState.IsValid)
{
drivers.Add(_driver);

return CreatedAtAction("GetDriver", new {_driver.Id}, data);
}

return new JsonResult("Something went wrong") {StatusCode = 500};
}
91 replies
CC#
Created by electronic heartbreak. on 7/11/2024 in #help
ASP.NET Core Web API byte[] issues
Hello there, I am trying to accept a byte array in my API request:
class X {
public byte[] Test { get; set; }
}
class X {
public byte[] Test { get; set; }
}
Swagger is used to test the API. When I launch the project and open it in my browser I see that this property accepts a string instead of a byte[]. Googling this issue did not gave much information besides this SO-thread https://stackoverflow.com/questions/77233543/call-an-api-with-byte-array-in-net-6 My question is if this is good enough or has anyone else faced similar issues?
15 replies
CC#
Created by electronic heartbreak. on 7/8/2024 in #help
✅ Expandability of the ASP.NET WEB API - Mongo tutorial code
Hello there, I am currently following this tutorial: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-8.0&tabs=visual-studio This tutorial explores the integration of mongo and c#. What in this tutorial is done is that they set collection, database and connection in the env-like file. This means that when you have multiple collections you need to add them here and expend all the setting classes. Another issue I see with this is that https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-8.0&tabs=visual-studio#add-a-crud-operations-service is not maintainable in the long run, becuase of this line:
_booksCollection = mongoDatabase.GetCollection<Book>(
bookStoreDatabaseSettings.Value.BooksCollectionName);
_booksCollection = mongoDatabase.GetCollection<Book>(
bookStoreDatabaseSettings.Value.BooksCollectionName);
Would an EF-like approach be more suitable? So you have a MongoDBContext class that holds the collections and DI this Context class into the Service classes?
152 replies
CC#
Created by electronic heartbreak. on 6/30/2024 in #help
✅ Folder selector can not select folder from phone
No description
18 replies
CC#
Created by electronic heartbreak. on 6/22/2023 in #help
❔ reduce these magic number code smells
18 replies
CC#
Created by electronic heartbreak. on 6/12/2023 in #help
❔ Possibilities in simplifying these loops?
I have these 5 loops, however, they look all quite similar, is there a method in simplifying these?
string[] sudokuStrings = filecontent.Split("\r\n");

//First sudoku (top left) min x = 0, min y = 0, max x = 8, max y = 8
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[0][index].ToString());
//Console.WriteLine($"Cell ({x}, {y}): {value}");
}
}

//Second sudoku (top right) min x = 18, min y = 0, max x = 26, max y = 8
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[1][index].ToString());
// Console.WriteLine($"Cell ({18+x}, {18+y}): {value}");
}
}

//Third sudoku (center) min x = 9, min y = 9, max x = 17, max y = 17
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[2][index].ToString());
//Console.WriteLine($"Cell ({9 + x}, {9 + y}): {value}");
}
}

//Fourth sudoku (bottom left) min x = 0, min y = 18, max x = 8, max y = 26
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[3][index].ToString());
//Console.WriteLine($"Cell ({x}, {18 + y}): {value}");
}
}
string[] sudokuStrings = filecontent.Split("\r\n");

//First sudoku (top left) min x = 0, min y = 0, max x = 8, max y = 8
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[0][index].ToString());
//Console.WriteLine($"Cell ({x}, {y}): {value}");
}
}

//Second sudoku (top right) min x = 18, min y = 0, max x = 26, max y = 8
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[1][index].ToString());
// Console.WriteLine($"Cell ({18+x}, {18+y}): {value}");
}
}

//Third sudoku (center) min x = 9, min y = 9, max x = 17, max y = 17
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[2][index].ToString());
//Console.WriteLine($"Cell ({9 + x}, {9 + y}): {value}");
}
}

//Fourth sudoku (bottom left) min x = 0, min y = 18, max x = 8, max y = 26
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
int index = y * 9 + x;
int value = int.Parse(sudokuStrings[3][index].ToString());
//Console.WriteLine($"Cell ({x}, {18 + y}): {value}");
}
}
8 replies
CC#
Created by electronic heartbreak. on 6/7/2023 in #help
❔ Get property from type
Through reflection I get all the types matching the interface.
public void GetRegularTypes()
{
var interfaceType = typeof(IRegularPuzzle);
var implementingTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(type => interfaceType.IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);

foreach (var type in implementingTypes)
{
PropertyInfo nameProperty = type.GetProperty("Name");
string name = (string)nameProperty.GetValue(null);
_regularTypes[name.ToLower()] = type;
}
}
public void GetRegularTypes()
{
var interfaceType = typeof(IRegularPuzzle);
var implementingTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(type => interfaceType.IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);

foreach (var type in implementingTypes)
{
PropertyInfo nameProperty = type.GetProperty("Name");
string name = (string)nameProperty.GetValue(null);
_regularTypes[name.ToLower()] = type;
}
}
However, a class has for example:
public class NineByNineRegularPuzzle : IRegularPuzzle
{
public string Name => "9x9";

public int Size => 9;
}
public class NineByNineRegularPuzzle : IRegularPuzzle
{
public string Name => "9x9";

public int Size => 9;
}
Is there a way I can get the Name property in the foreach? What i tried didnt work.
13 replies
CC#
Created by electronic heartbreak. on 6/7/2023 in #help
Issue setting up Singleton
In my project, I have a Singleton which I want to use in certain files. When I try to implement it in one I get an error. First, let me show some code: The singleton:
public sealed class RegularPuzzleSingleton : ISingleton
{
private const int TrimLength = 13;
private Dictionary<string, Type> _regularTypes;
public IRegularPuzzle RegularPuzzle { get; private set; }

private RegularPuzzleSingleton()
{
GetRegularTypes();
}

public static RegularPuzzleSingleton _instance;

public static RegularPuzzleSingleton GetInstance()
{
_instance ??= new RegularPuzzleSingleton();

return _instance;
}

public void GetRegularTypes()
{
var interfaceType = typeof(IRegularPuzzle);
var implementingTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(type => interfaceType.IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);

foreach (var type in implementingTypes)
{
string name = type.Name.ToLower()[..(type.Name.Length - TrimLength)];
_regularTypes[name] = type;
}
}

public bool IsRegularType(string extension)
{
if (_regularTypes.TryGetValue(extension, out Type? regular) && regular != null)
{
RegularPuzzle = (IRegularPuzzle)Activator.CreateInstance(regular);
return true;
}

return false;
}
}
public sealed class RegularPuzzleSingleton : ISingleton
{
private const int TrimLength = 13;
private Dictionary<string, Type> _regularTypes;
public IRegularPuzzle RegularPuzzle { get; private set; }

private RegularPuzzleSingleton()
{
GetRegularTypes();
}

public static RegularPuzzleSingleton _instance;

public static RegularPuzzleSingleton GetInstance()
{
_instance ??= new RegularPuzzleSingleton();

return _instance;
}

public void GetRegularTypes()
{
var interfaceType = typeof(IRegularPuzzle);
var implementingTypes = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(type => interfaceType.IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface);

foreach (var type in implementingTypes)
{
string name = type.Name.ToLower()[..(type.Name.Length - TrimLength)];
_regularTypes[name] = type;
}
}

public bool IsRegularType(string extension)
{
if (_regularTypes.TryGetValue(extension, out Type? regular) && regular != null)
{
RegularPuzzle = (IRegularPuzzle)Activator.CreateInstance(regular);
return true;
}

return false;
}
}
26 replies
CC#
Created by electronic heartbreak. on 6/7/2023 in #help
Testing private methods
Hey there, I have the following code:
c#
public class Input
{
public string SelectLevel() {
string level;
bool isValid = false;

do
{
Console.WriteLine("Selecteer een level");
level = Console.ReadLine();

if (IsInputValid(level))
{
isValid = true;
}
}
while (!isValid);

return level;
}

private static bool IsInputValid(string level)
{
return !string.IsNullOrWhiteSpace(level) && level.Length > 5 && level.Contains('.');
}

public void AskInput()
{

}
}
}
c#
public class Input
{
public string SelectLevel() {
string level;
bool isValid = false;

do
{
Console.WriteLine("Selecteer een level");
level = Console.ReadLine();

if (IsInputValid(level))
{
isValid = true;
}
}
while (!isValid);

return level;
}

private static bool IsInputValid(string level)
{
return !string.IsNullOrWhiteSpace(level) && level.Length > 5 && level.Contains('.');
}

public void AskInput()
{

}
}
}
I want to unit test this code using NUnit, When creating a Setup and initializing the class these 2 methods are in, and trying to write a test for the IsInputValid I see that I cant test private methods. However, it feels needed to test that method. I worked around the issue doing the following, but this feel very ugly.
c#
[Test]
public void IsInputValid_ReturnsTrue()
{
// Arrange
MethodInfo isInputValidMethod = typeof(Input)
.GetMethod("IsInputValid",
BindingFlags.NonPublic | BindingFlags.Static);

string level = "level1.txt";
// Act
bool result = (bool)isInputValidMethod.Invoke(null, new object[] { level });

// Assert
Assert.That(result, Is.True);
}
c#
[Test]
public void IsInputValid_ReturnsTrue()
{
// Arrange
MethodInfo isInputValidMethod = typeof(Input)
.GetMethod("IsInputValid",
BindingFlags.NonPublic | BindingFlags.Static);

string level = "level1.txt";
// Act
bool result = (bool)isInputValidMethod.Invoke(null, new object[] { level });

// Assert
Assert.That(result, Is.True);
}
If you have a solution for this or adivce, I am curious to know!
7 replies
CC#
Created by electronic heartbreak. on 5/27/2023 in #help
❔ Choosing correct Console App project.
34 replies