electronic heartbreak.
electronic heartbreak.
CC#
Created by electronic heartbreak. on 12/22/2024 in #help
✅ How to talk to Web API hosted on RPI?
No description
24 replies
CC#
Created by electronic heartbreak. on 12/15/2024 in #help
Docker-compose volume storing image
In my Web API I receive images. These images should be stored, prefferable in my local directory. My project uses docker (compose). I managed to use a volume where the images are getting stored in a folder called unfiltered_images in the docker container. However, the saved images do not appear into my specified folder on my d-drive. docker-compose
services:
apitest.api:
image: ${DOCKER_REGISTRY-}apitestapi
build:
context: .
dockerfile: apitest.API/Dockerfile
volumes:
- "D:/image_test:/unfiltered_images"
services:
apitest.api:
image: ${DOCKER_REGISTRY-}apitestapi
build:
context: .
dockerfile: apitest.API/Dockerfile
volumes:
- "D:/image_test:/unfiltered_images"
In the future. I want to deploy this app onto my Raspberry Pi where an external hard disk will be used to store the images.
7 replies
CC#
Created by electronic heartbreak. on 12/11/2024 in #help
Is it possible to create a file outside the project folder?
A yes/no question basically. This is the code I currently use to create and store files. When the StoragePath is "uploads", it creates an upload directory within my project folder.
c#
var savePath = Path.Combine(StoragePath, "test.png");
string directory = Path.GetDirectoryName(savePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}

using (var fileStream = new FileStream(savePath, FileMode.Create))
{
await myObject.Image.CopyToAsync(fileStream);
}
c#
var savePath = Path.Combine(StoragePath, "test.png");
string directory = Path.GetDirectoryName(savePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}

using (var fileStream = new FileStream(savePath, FileMode.Create))
{
await myObject.Image.CopyToAsync(fileStream);
}
9 replies
CC#
Created by electronic heartbreak. on 12/10/2024 in #help
Architectural advice needed
Hi, as the title suggest I am looking for advice on my current architecture and how I can improve things. I have some knowlegde on both onion architecture and clean architecture. My current solution is setup like this:
/ Solution
/- docker-compose
/- MyProject.API
/- MyProject.Domain
/- MyProject.Services
/ Solution
/- docker-compose
/- MyProject.API
/- MyProject.Domain
/- MyProject.Services
In brief, my API takes in an Image, validates it and then the image should be stored into a folder. Now for the storage I rely on my Service. Would it not be better to place my API in my Service project? If you have other suggestions or improvements feel free to suggest them.
5 replies
CC#
Created by electronic heartbreak. on 12/8/2024 in #help
Unable to properly launch Web API using Docker (Compose)
As the title suggests, I am having issues in running my Web API through Docker. When I launch the project and want to open it using localhost it is unreachable. My project structure: Solution/ - docker-compose (default) - docker-compose.override (default) - API/ - dockerfile The files: Dockerfile:
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081


# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["test.API/test.API.csproj", "test.API/"]
RUN dotnet restore "./test.API/test.API.csproj"
COPY . .
WORKDIR "/src/test.API"
RUN dotnet build "./test.API.csproj" -c $BUILD_CONFIGURATION -o /app/build

# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./test.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "test.API.dll"]
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081


# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["test.API/test.API.csproj", "test.API/"]
RUN dotnet restore "./test.API/test.API.csproj"
COPY . .
WORKDIR "/src/test.API"
RUN dotnet build "./test.API.csproj" -c $BUILD_CONFIGURATION -o /app/build

# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./test.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "test.API.dll"]
Docker-compose:
services:
test.api:
image: ${DOCKER_REGISTRY-}testapi
build:
context: .
dockerfile: test.API/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "8080:8080"
- "8081:8081"
services:
test.api:
image: ${DOCKER_REGISTRY-}testapi
build:
context: .
dockerfile: test.API/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "8080:8080"
- "8081:8081"
7 replies
CC#
Created by electronic heartbreak. on 11/24/2024 in #help
✅ Can f# also use the newest .NET 9?
As the title says.
6 replies
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