Hercules
Hercules
CC#
Created by Hercules on 2/23/2024 in #help
AutoMapper: Ignoring Nested Property in Mapping Configuration Results in Null Value
I'm encountering an issue with AutoMapper where I'm trying to ignore a nested property during mapping, but it's still being set to null in the destination object. Here's my setup: I have two classes, CompanyUpdateRequest and ApiUpdateRequest, where ApiUpdateRequestcontains a nested property ApiKey:
public class CompanyUpdateRequest
{
public int Id { get; set; }
public List<ApiUpdateRequest> AssignedApis { get; set; }
// Other properties...
}
public class ApiUpdateRequest
{
public int Id { get; set; }
public string ApiKey { get; set; }
// Other properties...
}

And here is an entity called Api

public class Api: BaseEntity
{
public string ApiKey { get; set; } = null!;
// Other properties...
}

in my mapping profil i've added the following

CreateMap<CompanyUpdateRequest, Company>()
.ForMember(dest => dest.AssignedApis, opt => opt
.MapFrom(src => src.AssignedApis));
CreateMap<ApiUpdateRequest, Api>()
.ForMember(dest => dest.ApiKey, opt => opt.Ignore()); // Ignore mapping apiKey

public class CompanyUpdateRequest
{
public int Id { get; set; }
public List<ApiUpdateRequest> AssignedApis { get; set; }
// Other properties...
}
public class ApiUpdateRequest
{
public int Id { get; set; }
public string ApiKey { get; set; }
// Other properties...
}

And here is an entity called Api

public class Api: BaseEntity
{
public string ApiKey { get; set; } = null!;
// Other properties...
}

in my mapping profil i've added the following

CreateMap<CompanyUpdateRequest, Company>()
.ForMember(dest => dest.AssignedApis, opt => opt
.MapFrom(src => src.AssignedApis));
CreateMap<ApiUpdateRequest, Api>()
.ForMember(dest => dest.ApiKey, opt => opt.Ignore()); // Ignore mapping apiKey

However, when I map from CompanyUpdateRequest to Company, the ApiKey property within the Api objects ends up being null, even though it's not present in the source object (ApiUpdateRequest). I'm puzzled as to why this is happening. Is there a limitation in AutoMapper that prevents ignoring properties within nested entities, or am I missing something in my configuration?
5 replies
CC#
Created by Hercules on 2/8/2024 in #help
Trouble Including staticwebassets.build.json from Shared Project in .NET MAUI Blazor Hybrid App
I'm facing an issue with including the staticwebassets.build.json file from a shared class library project (HikaridoConnect.Shared) in the publish output of my .NET MAUI Blazor hybrid app (HikaridoConnect.NativeClients). Despite setting the "Copy to Output Directory" property and ensuring proper project references, the file isn't included in the published output, causing functionality issues. Question: How can I ensure that the staticwebassets.build.json file from the shared project is correctly included in the publish output of my .NET MAUI Blazor hybrid app? Are there any specific configurations or settings I might be overlooking? I'd appreciate any insights or guidance on resolving this issue. Thanks in advance for your help!
1 replies
CC#
Created by Hercules on 10/12/2023 in #help
✅ Seeking Help with Blazor WebAssembly Deployment Issue
Hello, I'm facing an issue with deploying my Blazor WebAssembly (WASM) app to Azure. The problem is that the deployed website doesn't reflect my code changes. Here are the details: Issue: * Blazor WebAssembly app deployed to Azure Web App. * Deployment process runs without errors. * Website shows an older version of the app, not reflecting recent code changes. Additional Info: *GitHub Actions workflow is used for building and publishing. *Azure App Service Publish Profile is correctly set as a GitHub secret. * Project includes shared components from other libraries. Request for Help: I need assistance in diagnosing and fixing this issue. If you've encountered a similar problem or have tips for troubleshooting Blazor WebAssembly deployments on Azure, please share your expertise. Thank you for your help!
4 replies
CC#
Created by Hercules on 9/23/2023 in #help
❔ Blazor WebAssembly: How to dynamically hide a layout component after logging out
Question: I have a Blazor WebAssembly application where I'm using the MudBlazor library to create a layout that includes a navigation bar (MudAppBar). I want to dynamically hide this navigation bar after a user logs out of the application. Here's the relevant part of my layout:
@if (AuthState != null && AuthState.User.Identity.IsAuthenticated)
{
<!-- MudAppBar and other layout components -->
}
else
{
<!-- Layout without MudAppBar -->
}
@if (AuthState != null && AuthState.User.Identity.IsAuthenticated)
{
<!-- MudAppBar and other layout components -->
}
else
{
<!-- Layout without MudAppBar -->
}
I'm triggering the logout process using the following code:
private async Task<bool> SignOut()
{
var isLoggedOut = await _JwtAuthProvider.Logout();
if (isLoggedOut)
{
_navigationManager.NavigateTo("/login");
}
return isLoggedOut;
}
private async Task<bool> SignOut()
{
var isLoggedOut = await _JwtAuthProvider.Logout();
if (isLoggedOut)
{
_navigationManager.NavigateTo("/login");
}
return isLoggedOut;
}
Inside my Logout method, I'm using NotifyAuthenticationStateChanged to reset the authentication state and set it to an empty ClaimsPrincipal. However, after navigating to the login page (/login), the navigation bar (MudAppBar) is still visible. It seems that the main layout is rendered when _navigationManager.NavigateTo("/login") is invoked. How can I ensure that the navigation bar is hidden after a user logs out and navigates to the login page? Is there a way to dynamically update the layout based on the authentication state without requiring a hard refresh of the page? I appreciate any insights or suggestions to resolve this issue. Here is my custom AuthenticationStateProvider - how i user NotifyAuthenticationStateChanged - -> check the Logout() method. https://paste.mod.gg/kvvtgasbzsxo/0
2 replies
CC#
Created by Hercules on 9/12/2023 in #help
❔ Troubleshooting JSON Mapping for POST Request to UserAsync Endpoint
I'm seeking guidance on formatting the JSON body for a POST request to the following API endpoint: API Signature: csharp
[HttpPost("CreateProjectUser")]
public async Task<ActionResult> CreateProjectUserAsync(HikariUser projectUser, string userName)
[HttpPost("CreateProjectUser")]
public async Task<ActionResult> CreateProjectUserAsync(HikariUser projectUser, string userName)
JSON Body (inputData):
{
"projectUser": {
"Username": "exampleProjectUser",
"Email": "exampleProjectUser1@example.com",
"Password": "Abc!123",
"Role": "Contributor"
},
"userName": "AM"
}
{
"projectUser": {
"Username": "exampleProjectUser",
"Email": "exampleProjectUser1@example.com",
"Password": "Abc!123",
"Role": "Contributor"
},
"userName": "AM"
}
The issue I'm encountering is that "userName": "AM" is being incorrectly mapped to HikariUser projectUser.Username, when it should be filling the *exampleProjectUser *field. Additionally, the other properties of HikariUser are not being correctly populated and are showing as null. I've already tried using [JsonPropertyName("")] attributes without success. Any guidance or solutions to ensure the correct mapping of JSON properties to the method parameters would be greatly appreciated.
public class HikariUser
{
[JsonPropertyName("username")]
public string UserName { get; set; }

[JsonPropertyName("email")]
public string Email { get; set; }

[JsonPropertyName("password")]
public string Password { get; set; }

[JsonPropertyName("role")]
public string Role { get; set; }
}
public class HikariUser
{
[JsonPropertyName("username")]
public string UserName { get; set; }

[JsonPropertyName("email")]
public string Email { get; set; }

[JsonPropertyName("password")]
public string Password { get; set; }

[JsonPropertyName("role")]
public string Role { get; set; }
}
5 replies
CC#
Created by Hercules on 5/10/2023 in #help
❔ I need help making my code threadsafe that uses Selenium webdriver.
I am currently working on a service worker where i user selenium to take screenshots and the process for taking the screenshots is a multthreaded solutions where i use a Parallel.ForEach- loop with 4 or more threads on each round in the loops. in the loops i am createing a chrome driver and a ChromeDriverService for the driver. The service worker is installed as a windows service and it generates the following error after sometime after running perfectly fine.
2023-05-10 09:45:37.202 +00:00;;[INF];[T-];Unexpected Exception: OpenQA.Selenium.WebDriverException: An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL http://localhost:51961/session/ea521700fe9032a7c342c5da4ebfd806/window/rect. The exception message was: An error occurred while sending the request.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: The response ended prematurely.
2023-05-10 09:45:37.202 +00:00;;[INF];[T-];Unexpected Exception: OpenQA.Selenium.WebDriverException: An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL http://localhost:51961/session/ea521700fe9032a7c342c5da4ebfd806/window/rect. The exception message was: An error occurred while sending the request.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: The response ended prematurely.
I need help stabilizing the code.
Task<ChromeDriver> PrepareDriverAsync(int portValue)
{
var options = new ChromeOptions();
options.AddArguments(new List<string> { "--headless", "--hide-scrollbars" });
options.PageLoadStrategy = PageLoadStrategy.Normal;
ChromeDriverService service = await CreateChromeDriverServiceAysnc();
service.Port = portValue;
var driver = new ChromeDriver(service, options);
return driver;
}

Task<ChromeDriverService> CreateChromeDriverServiceAysnc()
{
ChromeDriverService chromeDriverService = null;
try
{
chromeDriverService = ChromeDriverService.CreateDefaultService();
break;
}
catch (DriverServiceNotFoundException)
{

}
return chromeDriverService;
}
Task<ChromeDriver> PrepareDriverAsync(int portValue)
{
var options = new ChromeOptions();
options.AddArguments(new List<string> { "--headless", "--hide-scrollbars" });
options.PageLoadStrategy = PageLoadStrategy.Normal;
ChromeDriverService service = await CreateChromeDriverServiceAysnc();
service.Port = portValue;
var driver = new ChromeDriver(service, options);
return driver;
}

Task<ChromeDriverService> CreateChromeDriverServiceAysnc()
{
ChromeDriverService chromeDriverService = null;
try
{
chromeDriverService = ChromeDriverService.CreateDefaultService();
break;
}
catch (DriverServiceNotFoundException)
{

}
return chromeDriverService;
}
8 replies
CC#
Created by Hercules on 5/5/2023 in #help
❔ I have this serviceWorker running Selenium for screenshots and its not working properly.
I need help identifying my problem and i have reasons to believe there is a leak somewhere in the code. Since the windows service is still running all night but not giving back any logs (using serilog) after sometime. I have handled the my exceptions that I want to keep pushing for a screenshot. But I believe in the longer run the selenium webdriver clashes with the ports.
Description: The process was terminated due to an unhandled exception.
Exception Info: OpenQA.Selenium.WebDriverException: An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL http://localhost:51960/session. The exception message was: An error occurred while sending the request.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
Description: The process was terminated due to an unhandled exception.
Exception Info: OpenQA.Selenium.WebDriverException: An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL http://localhost:51960/session. The exception message was: An error occurred while sending the request.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
I've tried to handle the ports by using an ConcurrentDictionary and giving every instance of webdriver its own port. But i have zero understanding why my logs stops becuase i have nothing from the event viewer or any output. The code is in the link since its to long to share. https://codeshare.io/QneYzm
2 replies
CC#
Created by Hercules on 4/24/2023 in #help
❔ Getting started with windows service - onStart won't work. I am using VS 22.
I have this sample code trying to print to my event viewer. But this won't hit Onstart or give me the right sources in eventView its still "service1" as by default.
public partial class Worker : ServiceBase
{
Timer timer;
private int eventId = 1;
EventLog eventLog;
public Worker()
{
InitializeComponent();
eventLog = new EventLog();
if (!EventLog.SourceExists("Alexander"))
{
EventLog.CreateEventSource(
"Alexander", "AlexandersLog");
}
eventLog.Source = "Alexander";
eventLog.Log = "AlexandersLog";

timer = new Timer();
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}

protected override void OnStart(string[] args)
{
eventLog.WriteEntry("Service onStart - final");
}

protected override void OnStop()
{
EventLog.WriteEntry("Service OnStop - final");

}

public void OnTimer(object sender, ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
eventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
}
}
public partial class Worker : ServiceBase
{
Timer timer;
private int eventId = 1;
EventLog eventLog;
public Worker()
{
InitializeComponent();
eventLog = new EventLog();
if (!EventLog.SourceExists("Alexander"))
{
EventLog.CreateEventSource(
"Alexander", "AlexandersLog");
}
eventLog.Source = "Alexander";
eventLog.Log = "AlexandersLog";

timer = new Timer();
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}

protected override void OnStart(string[] args)
{
eventLog.WriteEntry("Service onStart - final");
}

protected override void OnStop()
{
EventLog.WriteEntry("Service OnStop - final");

}

public void OnTimer(object sender, ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
eventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
}
}
https://codeshare.io/dw8mzK
2 replies
CC#
Created by Hercules on 4/4/2023 in #help
❔ Do I need to take any extra steps to install a Windows service with Parallel.ForEach?
Is there any additional step required to install a Windows service when utilizing Parallel.ForEach, as I am encountering difficulties during the installation process? My code used to work perfectly fine before when i used async but I later noticed I needed to use multiple threads to achive better performance. So I did some updates. The new code look like this https://pastebin.com/hvntiY5U and when I deploy sc.exe create $serviceName binpath= $servicePath start= auto The Event Viewer returns: "A timeout was reached (30000 milliseconds) while waiting for the ElicitStampenScreenshots-test service to connect." "The myService service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion." Is there any abnormality with my code that creates a timeout or breaks the start process?
44 replies
CC#
Created by Hercules on 4/2/2023 in #help
✅ What other prerequisites are necessary to run service worker as a service on a Windows Server?
I have developed a service worker using .NET 7, and it successfully runs when tested through dotnet build. However, when attempting to publish the code and run it as a Windows service in the background, I consistently encounter Error 1053. I am utilizing Selenium webdriver to extract data, and I have installed the latest drivers and Chrome on the server. Despite this, I continue to receive Error 1053 and require assistance in deploying the service. I am unsure of what I am missing or what mistake I may be making. Is it possible that the server is not recognizing the driver, resulting in a timeout during startup?
RUN dotnet add package Selenium.Support --version 4.8.1
RUN dotnet add package Azure.Storage.Blobs --version 12.15.1
RUN dotnet add package Microsoft.Azure.Functions.Extensions --version 1.1.0
RUN dotnet add package Microsoft.NET.Sdk.Functions --version 4.1.1
RUN dotnet add package Microsoft.VisualStudio.Azure.Containers.Tools.Targets --version 1.17.2
RUN dotnet add package System.Threading.AccessControl --version 7.0.1

Other installations
Latest stabel chromedriver - https://sites.google.com/chromium.org/driver/
Chrome web browser
RUN dotnet add package Selenium.Support --version 4.8.1
RUN dotnet add package Azure.Storage.Blobs --version 12.15.1
RUN dotnet add package Microsoft.Azure.Functions.Extensions --version 1.1.0
RUN dotnet add package Microsoft.NET.Sdk.Functions --version 4.1.1
RUN dotnet add package Microsoft.VisualStudio.Azure.Containers.Tools.Targets --version 1.17.2
RUN dotnet add package System.Threading.AccessControl --version 7.0.1

Other installations
Latest stabel chromedriver - https://sites.google.com/chromium.org/driver/
Chrome web browser
Code can be found here: https://pastebin.com/dAjhfK0i
1 replies
CC#
Created by Hercules on 3/28/2023 in #help
❔ I am need of help before I give up and run my code on a server instead of a serverless solution.
I have create an azure function locally and i've used the selenuim webdriver package for taking screenshots and automate logins on certains urls, And the client wished it to be serveless but my gut feeling said that it might nog be possible. I wrote the code and now after i did some i found this information on google
"The base Azure Function image does not contain the necessary chromium packages to run selenium webdriver. [...] "
and when I try to deploy the code to azure function app I get an error and it doesn't say much in the output field and in the message. Fellow develoeprs do we have any ideas on how to make an azure function app know of chromium?
2 replies
CC#
Created by Hercules on 3/17/2023 in #help
✅ I get dotnet.exe' has exited with code 4294967295 (0xffffffff). When im try to run my WASM project
25 replies
CC#
Created by Hercules on 2/1/2023 in #help
✅ Im trying to migrate my ef core project into my local MSSql Database but a context is wrong.
4 replies
CC#
Created by Hercules on 1/31/2023 in #help
❔ My web api works fine when i run it from VS but i can't publish it?
49 replies
CC#
Created by Hercules on 1/26/2023 in #help
✅ Dockerfile goes where exactly if I have multiple class libraries in a sln?
19 replies
CC#
Created by Hercules on 1/16/2023 in #help
❔ I just created a Assembly issue post in Stackoverflow all help are welcome
2 replies
CC#
Created by Hercules on 1/10/2023 in #help
❔ Can't run Add-migration to create my local database.
12 replies
CC#
Created by Hercules on 12/14/2022 in #help
❔ How do I resolve the SocketException (10061)?
2 replies
CC#
Created by Hercules on 11/20/2022 in #help
❔ Can't get around on how to instantiate this.
I can't get around on how to instantiate this in my service.cs so i can call it properly in my controller. Relevant code below. https://paste.mod.gg/kocfivzcagoc/0
43 replies
CC#
Created by Hercules on 11/19/2022 in #help
❔ How do you merging Dictionaries into one Dictionary?
Has anyone merged two dictionaries of same type into one?
I read something like this


var result = dictionaries.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key, group => group.First());
I read something like this


var result = dictionaries.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key, group => group.First());
Lookup(https://learn.microsoft.com/en-us/dotnet/api/system.linq.lookup-2?view=net-7.0). But will this code make the dictionary distinct (that values and keys don't repeat). I rather use same key and add the value from the dictionary i'm merging/joining. Maybe this option makes it ignore
new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
58 replies