alkasel#159
alkasel#159
CC#
Created by alkasel#159 on 2/14/2024 in #help
Visual Studio: user frustrated by auto-completion
Hi, I'm a bit frustrated by Visual Studio auto-completion feature. For example I noticed it suggests only words that matches perfectly the prefix you've just typed in: for example, if I mistype a character, the word I intend to write is no more suggested as completion. As a result, the user experience is not smooth as it should be. I don't remember having this kind of problems in Eclipse something like 10 years ago. Am I the only one frustrated by this behavior? Is it only a problem on my installation?
18 replies
CC#
Created by alkasel#159 on 4/21/2023 in #help
✅ Controller method can be invoked from Edge and Postman but not by Firefox
Hi, I've the following server controller:
[Route("[controller]")]
[ApiController]
public class ProductionOrderController : ControllerBase
{
// ...

[HttpGet("GetCount")]
public async Task<ActionResult<string>> GetCount() {
try {
int result = await _productionOrderDAL.GetCountAsync();
return result.ToString();
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
return new StatusCodeResult((int)HttpStatusCode.InternalServerError);
}
}
}
[Route("[controller]")]
[ApiController]
public class ProductionOrderController : ControllerBase
{
// ...

[HttpGet("GetCount")]
public async Task<ActionResult<string>> GetCount() {
try {
int result = await _productionOrderDAL.GetCountAsync();
return result.ToString();
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
return new StatusCodeResult((int)HttpStatusCode.InternalServerError);
}
}
}
Client side (blazor wasm) I invoke such method as follows:
private async Task MyMethod() {
try {
Task<HttpResponseMessage> t1 = _httpClient.GetAsync("ProductionOrder/GetCount");
HttpResponseMessage response = await t1;
string countStr = await response.Content.ReadAsStringAsync();
int count = int.Parse(countStr);

// ...

} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private async Task MyMethod() {
try {
Task<HttpResponseMessage> t1 = _httpClient.GetAsync("ProductionOrder/GetCount");
HttpResponseMessage response = await t1;
string countStr = await response.Content.ReadAsStringAsync();
int count = int.Parse(countStr);

// ...

} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
If I launch the server and edge client, the latter retrieves the integer value. Same with Postman. Using Firefox, on the other hand, I have that the request is sent, the controller returns the correct integer value (I can see that debugging) but it seems like the client is not receiving the answer: from developer tools, there is no status code as well as response header. The "response" tab in developers tool shows the client index.html page with an error:
<!DOCTYPE html>
...
<body>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
</div>
</body>
...
<!DOCTYPE html>
...
<body>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
</div>
</body>
...
And of course the parsing fails. Please note that the controller has another method, a get request returning a list of items, and in that case firefox client retrieves the list of items successfully. Could you please give me a hand?
7 replies
CC#
Created by alkasel#159 on 4/5/2023 in #help
✅ .NET Localization Culture Fallback
Hi, I'm using .NET localization in a blazor wasm hosted app, and I have the following issue: Let's consider the generic class myclass, for which I have the following files: myclass.razor myclass.razor.cs myclass.en.resx (english translations) myclass.it.resx (italian translations) Now, if I access the web app by means of a browser with culture set to "en", the english translations are displayed correctly. In fact, from developer tools I can see the request http://.../_framework/en/Client.resources.dll, which is answered with a 200 OK containing some data as response. If then I set the browser culture to "en-US", no term is translated. In fact I see browser is making the following requests: http://.../_framework/en-US/Client.resources.dll http://.../_framework/en/Client.resources.dll Both of which are answerede with a 304 Not Modified. I've tested on Firefox and Edge: the behavior is the same. This is strange because the documentation describes a "Culture fallback" mechanism that should make the above scenario work. Any idea what I could be doing wrong? Thanks
3 replies
CC#
Created by alkasel#159 on 4/4/2023 in #help
✅ Visual Studio nesting resource files
Hi, I'm using File Nesting In Visual Studio in order to organize files this way:
FileName.razor
FileName.razor.cs
FileName.resx
FileName.en-US.resx
FileName.it-IT.resx
...
FileName.razor
FileName.razor.cs
FileName.resx
FileName.en-US.resx
FileName.it-IT.resx
...

I'm using custom settings with
"allExtensions": {
"add": {
".*": [
".razor"
]
}
"allExtensions": {
"add": {
".*": [
".razor"
]
}

This way I have that FileName.resx is correctly nested under FileName.razor, but FileName.en-US.resx is not nested. Could you please help me understand how should I correct the settings file?
4 replies
CC#
Created by alkasel#159 on 3/31/2023 in #help
❔ How to organize Windows Forms application
Hi, I'm developing a Windows Forms app that can perform a bunch of translation-related tasks such as: 1) Parsing a c# file, looking for terms, listing those for which there is no translation on database and printing this list 2) Use a file containing <term, translation, language> records and write them onto database and so on Now, I'd like to organize properly this application. In particular, I'd like to keep in the Form class only the code related to the form controls, and everything else somewhere else. Furthermore, I'd like the front-end not to be frozen while the app is working, but rather showing progress bars and so on. I understand I need to use BackgroundWorker for this. So I have my form, where I'll initialize a BackgroudWorker... but where should the method that will be executed by the Background Worker be placed? And should I use services (like in .net web app)? Thanks!
13 replies
CC#
Created by alkasel#159 on 2/17/2023 in #help
❔ Transform ASP.NET Core IdentityUser into a two-keys table
I need to modify the IdentityUser class so that it has two keys, id and companyId. I tried to extend the IdentityUser class like this
[PrimaryKey(nameof(Id), nameof(CompanyId))]
public class User : IdentityUser
{
public int CompanyId { get; set; }

[ForeignKey(nameof(CompanyId))]
public Company Company { get; set; }

public User() : base() {
}
}
[PrimaryKey(nameof(Id), nameof(CompanyId))]
public class User : IdentityUser
{
public int CompanyId { get; set; }

[ForeignKey(nameof(CompanyId))]
public Company Company { get; set; }

public User() : base() {
}
}
but, when I try to generate the migration data, I have the following error
The derived type 'User' cannot have the [Key] attribute on property 'CompanyId' since primary keys may only be declared on the root type. Move the property 'CompanyId' to 'IdentityUser' or remove 'IdentityUser' from the model by using [NotMapped] attribute or calling 'EntityTypeBuilder.Ignore' on the base type in 'OnModelCreating'.
The derived type 'User' cannot have the [Key] attribute on property 'CompanyId' since primary keys may only be declared on the root type. Move the property 'CompanyId' to 'IdentityUser' or remove 'IdentityUser' from the model by using [NotMapped] attribute or calling 'EntityTypeBuilder.Ignore' on the base type in 'OnModelCreating'.
Of course, since IdentityUser is a type from Microsoft, I don't think it's a good idea to change it. How should I do? Thanks
6 replies
CC#
Created by alkasel#159 on 2/15/2023 in #help
❔ Organize database for central replica of applications data
Hi, my company has developed a SCADA software that acquires data from our customers machines and allows further analysis on them. The software and its database are deployed at the customer's site. Now we'd like to setup a central replica of all the data stored at our customers SCADA systems in order to better understand how our customers work. However I'm not sure about how should I organize the database: As of now the database knows nothing about customers: for example, all the "production orders" listed in the related table of a given customer are implicitly associated to customer itself. This allows me to use an integer field "production order id" as key of the "production order" table, and scan it efficiently. However now I need to store informations from multiple customers at our central database. The only thing that comes up to my mind is to add to the "production order" table a "customer" column, and make the pair <production order id, customer> the key of the table. However this way indexing should be less efficient as far as I know. Is this the correct way to handle something like this? Thanks
2 replies
CC#
Created by alkasel#159 on 2/2/2023 in #help
❔ Producer Consumer ISourceBlock<T>, periodically flushing consumed data
Hi, I've the following scenario: I've a camera continuously acquiring frames and a c# app receiving it and storing it in a
List<MemoryStream>
List<MemoryStream>
. Once per minute, the memory stream is copied, passed to a task in charge of rendering a video file from such frames, and then emptying the original stream in order to use it for consequent frames. Now I'm trying to perform video rendering in real-time, as frames are received by the program. I've seen this guide from Microsoft about using
ISourceBlock<T>
ISourceBlock<T>
to implement a buffer that can be used in a producer-consumer scenario. This is good for me, since I can have a task receiving data from the camera and producing data in the buffer and a parallel task consuming data from the buffer. The problem is, once per minute I need the rendering task (the consuming one) to finalize the video file it has been adding frames to. At the same time, I need the producer task to continue producing frames, in the same buffer or in a different one. In order to accomplish this, the only way that came up to my mind is the following: 1) when the producer start producing data belonging to a new video file that's supposed to belong to a new video, it starts a new task, passing to it bufferA. The consumer will start consume data as it is produced. 2) when the producer has produced all data related to the video file that is being parallely rendered, it calls
ITargetBlock<T>.Complete()
ITargetBlock<T>.Complete()
to notify the consumer that frames for this video have finished and it needs to finalize the video rendering. 3) then the procuder will continue producing data, this time putting it in a bufferB. 4) rendering of frames in buffer B is completed 5) buffer A is cleared and producer start filling it again etc...
4 replies
CC#
Created by alkasel#159 on 12/15/2022 in #help
✅ Split string on list of strings and on whathever number
Hi, I need to split a string in substrings, splitting every time I find some specific strings (e.g. ">>>") and everytime I find a number of whathever length. I can successfully split on any of the specified string, but I cannot do it with numbers. My C# code is the following:
string value = "545: hello world: <<<example text 567 king's choice>>>";

string[] separators = new string[] {||
"<<<",
">>>",
":"
}

string[] substrings = value.Split(separators, StringSplitOptions.TrimEntries);
string value = "545: hello world: <<<example text 567 king's choice>>>";

string[] separators = new string[] {||
"<<<",
">>>",
":"
}

string[] substrings = value.Split(separators, StringSplitOptions.TrimEntries);
I've tried with Regex.split as well but it includes all kind of characters, so I think it's not supposed to be used like that (https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.split?view=net-7.0).
25 replies
CC#
Created by alkasel#159 on 11/29/2022 in #help
❔ Blazor JSInterop declare component-scoped javascript variables
Hi, I've the following problem: I have a bunch of Blazor components that needs to invoke some javascript methods; each of these components needs to work with its own instance of an object created in the javascript code, let's call it object O. So I'd need - component A to have instance A of object O (let's call it OA) - component B to have instance B of object O (let's call it OB) - and so on... I've tried declaring a global variabile in the .js file, but that way there is only one instance across the whole application: I've initialized the global object O in Blazor component A and later I've read its value from Blazor component B, and I've read the value set by A. That seems to confirm that there is a single instance of O across the whole application. The other way I thought of was to have javascript return to Blazor the object it created. But I think this is not possible since this is not a primitive type, it is a https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection, and I think there is no C# equivalent. By the way, I need this object because in javascript I open the WebRTC Connection, and later I need to close it, and thus I need a reference to it. Do you know a way around this? Thanks, Alessandro
3 replies
CC#
Created by alkasel#159 on 11/24/2022 in #help
❔ Blazor JS Interop - Return RTCPeerConnection from js to Blazor in order to close it
Hi, I've quite a complex task: In my Blazor application I use javascript to read webrtc data produced by https://github.com/deepch/RTSPtoWeb, which basically take streams from a bunch of RTSP IP Cameras and publishes them as webrtc streams. Now, everything works fine, the only problem I have is that, after the webrtc connection is open, at a certain point (e.g. if the user leaves the page) I need to close such connection. In order to establish the connection I use the javascript script provided by the above-mentioned project: https://github.com/deepch/RTSPtoWeb/blob/master/docs/examples/webrtc/main.js, mutatis mutandae. Now, inside the javascript file, the RTCPeerConnection is created by means of
const webrtc = new RTCPeerConnection({
iceServers: [{
urls: ['stun:stun.l.google.com:19302']
}],
sdpSemantics: 'unified-plan'
})
const webrtc = new RTCPeerConnection({
iceServers: [{
urls: ['stun:stun.l.google.com:19302']
}],
sdpSemantics: 'unified-plan'
})
And in order to close it, I suppose I need to return the created 'webrtc' object to the calling Blazor method, so that Blazor side I can close the RTCPeerCOnnection when needed. But Blazor side, I don't know which object I need to use to "store" the result. Do you have any tip about how should I proceed? Thanks
3 replies
CC#
Created by alkasel#159 on 11/21/2022 in #help
❔ Passing parameters to Services
Hi, I've a webapp where, at start, I parse some configuration values from
appssettings.json
appssettings.json
Then, from these configuration values, I'd like to build some object and passing them to services. Please note these services could have other services injected into them. Should I have classes representing configuration objects, make them services, use
GetRequestService
GetRequestService
to initialize them and finally inject them into other services?
11 replies
CC#
Created by alkasel#159 on 11/17/2022 in #help
❔ EF Core - Select items such that attribute sum is greater than...
Hi everyone, I have an object Recording having attributes start_time and size_byte. Now, when the space occupied by recordings exceeds a threshold t1, I want to delete oldest recordings until the total space occupied is below threshold t2 < t1. So I'll have to free an amount of space at least equal to space_to_free = occupied_space - t2. Thus I need to perform a query like "give me the records, ordered by start_time, such that the sum of their size is >= space_to_free." The problem is with the second part of the query, that in PostgreSQL would be like at the following article: https://dba.stackexchange.com/a/106737 Could you please give me a hand implementing this in EF Core?
3 replies
CC#
Created by alkasel#159 on 11/11/2022 in #help
✅ Software architecture for front-end translations
I've an .NET 7 Blazor WebAssembly Hosted web application meant to be deployed in a industrial environment local network and to be used by as few as 5 users simultaneously. Since at the factory there can be workers speaking different languages, and since we can connect via VPN for maintenance, I need to include a translation mechanism, which should involve all the front-end writings. As of now I've setup some .cs files containing constants fields representing symbols. Example:

public string CAMERA_CONNECTION_LOST = "camera_connection_lost"

public string CAMERA_CONNECTION_LOST = "camera_connection_lost"
Then, in the database I'll have a "transl" table structured like this

--------------------------------------------------------
| symbol | lang | translation |
--------------------------------------------------------
| camera_connection_lost | en_us | Connection lost |
| camera_connection_lost | it_it | Connessione persa |

--------------------------------------------------------
| symbol | lang | translation |
--------------------------------------------------------
| camera_connection_lost | en_us | Connection lost |
| camera_connection_lost | it_it | Connessione persa |
And so on. When an use launch the blazor application, blazor could 1) Retrieve from back-end translations for all the symbols defined in the web application (larger loading time at startup, larger memory usage, lower latency when navigating to another page of the application since no need to request translation for that specific page) 2) Retrieve from back-end translations for the symbols of a given page (maybe I should have a "page" table (representing a Blazor page) and an M-to-M relationship between pages and symbols. What do you think of this approach? What bothers me of this approach is to have the symbols hard-coded in the program. I'm not sure if that's acceptable or not.
6 replies
CC#
Created by alkasel#159 on 11/10/2022 in #help
❔ .NET 6 GET method returns OK even if there is no such endpoint
I've a .NET 6 Web Application with Blazor wasm front-end. When I make an HTTP GET request from front-end to back-end, even if the address I specify in the request is mapped to no controller method, the server would still respond with an OK and with the index.html page. I'd like to have a NOT FOUND answer from the server, instead. I've tried searching on the web but I had no luck until now
4 replies
CC#
Created by alkasel#159 on 10/7/2022 in #help
[ASP.NET Core 6] Performance when registering a lot of singleton as services
Hi, Does having a lot of classes registered as singleton (_builder.Services.AddSingleton(...)) reduce web app performances? In my .NET 6 web application I have like 4 macro-features that the user may or may not want to buy (e.g. ProductionAssistant, ForecastedMaintenance etc). Inside every macro-feature I have like 20 entities, e.g ProductionOrder, Product, Customer etc. As of now I'm using a single controller and a single singleton service for each macro-features. The controller receives a request and forwards it to the Singleton Service that will invoke one or more scoped services which are in charge of performing the actual query. However, as I write down the code, I notice that controllers and singleton services classes become more and more long, making reading and modifying them a bit of a pain. Should I instead make a service and a controller for each entity? would having like 80 singleton services and 80 controllers slow down the web application? Thanks
14 replies
CC#
Created by alkasel#159 on 10/7/2022 in #help
[EntityFramework Core] Populate complex object from query with join
Hi, I've the following objects representing tables:
[Table("ProductionOrder", Schema = "public")]
public class ProductionOrder
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Code { get; set; }

[ForeignKey("ProductId")]
public Product Product { get; set; }
public int ProductId { get; set; }

[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
public int CustomerId { get; set; }
}
[Table("ProductionOrder", Schema = "public")]
public class ProductionOrder
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Code { get; set; }

[ForeignKey("ProductId")]
public Product Product { get; set; }
public int ProductId { get; set; }

[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
public int CustomerId { get; set; }
}
[Table("Product", Schema = "public")]
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
[Table("Product", Schema = "public")]
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
[Table("Customer", Schema = "public")]
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
[Table("Customer", Schema = "public")]
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
I'd like to retrieve the list of all ProductionOrder items together with their Product and Customer. From what I've experimented, the following code returns the ProductionOrder list but Customer and Product fields are both null:
public async Task<List<ProductionOrder>> GetProductionOrdersAsync() {
return await _dbContext.ProductionOrder.ToListAsync();
}
public async Task<List<ProductionOrder>> GetProductionOrdersAsync() {
return await _dbContext.ProductionOrder.ToListAsync();
}
Of course I could manually perform a couple of query for each ProductionOrder, retrieving its Product and Customer. But it seems a waste of resources, since with JOIN I can achieve the same result with a single query. So I'm trying to understand if the above code can somehow perform JOIN and retrieve Product and Customer automatically or if I'm required to perform JOIN manually. Thanks
2 replies
CC#
Created by alkasel#159 on 9/15/2022 in #help
ASP. NET Core 6 - Architectural doubt, how to protect data access layer
23 replies
CC#
Created by alkasel#159 on 9/9/2022 in #help
ASP.NET Core 6 - Strange Monitor.TryLock behavior
Hi, I'm making some experiment to better understand the Monitor. Looks like something is off: I've written the following code
internal class Program
{
private static Object obj = new();

static async Task Main(string[] args) {
for (int i = 0; i < 9; i++) {
Console.WriteLine(string.Concat("Starting task ", i));
var task = Task.Run(() => Foo(i));
await Task.Delay(500);
}
}

private static async Task Foo(int value) {
if (Monitor.TryEnter(obj)) {
Console.WriteLine(value + ": monitor entered");
await Task.Delay(new Random().Next() % 2 * 1000);
Monitor.Exit(obj);
Console.WriteLine(value + ": monitor released");
} else {
Console.WriteLine(value + ": monitor refused me "));
}
}
}
internal class Program
{
private static Object obj = new();

static async Task Main(string[] args) {
for (int i = 0; i < 9; i++) {
Console.WriteLine(string.Concat("Starting task ", i));
var task = Task.Run(() => Foo(i));
await Task.Delay(500);
}
}

private static async Task Foo(int value) {
if (Monitor.TryEnter(obj)) {
Console.WriteLine(value + ": monitor entered");
await Task.Delay(new Random().Next() % 2 * 1000);
Monitor.Exit(obj);
Console.WriteLine(value + ": monitor released");
} else {
Console.WriteLine(value + ": monitor refused me "));
}
}
}
And I have this strange (apparently) result:
Starting task 0
0: monitor entered
Starting task 1
1: monitor refused me :c
Starting task 2
2: monitor entered
Starting task 3
3: monitor refused me :c
2: monitor released
Starting task 4
4: monitor entered
Starting task 5
5: monitor refused me :c
Starting task 6
6: monitor refused me :c
Starting task 7
7: monitor refused me :c
Starting task 8
8: monitor entered
8: monitor released
Starting task 0
0: monitor entered
Starting task 1
1: monitor refused me :c
Starting task 2
2: monitor entered
Starting task 3
3: monitor refused me :c
2: monitor released
Starting task 4
4: monitor entered
Starting task 5
5: monitor refused me :c
Starting task 6
6: monitor refused me :c
Starting task 7
7: monitor refused me :c
Starting task 8
8: monitor entered
8: monitor released
At first I couldn't understand this strange behavior. Now I've noticed that Monitor.Try enter description says "returns true if the current thread acquires the lock". From my understanding, Task.Run may or may not create a new thread, so for example task 0 and task 2 could have been executed inside the same thread, and this would explain why task 2 entered the monitor even though it should have been acquired by task 0. What do you think? is this the correct explanation? If that's the case, it seems to me Monitor is not suitable for protect a resource from multiple-task access
6 replies
CC#
Created by alkasel#159 on 9/8/2022 in #help
EF Core 6 - Create table if not exists by means of Add-Migration
Hi, Let's say I've a database with tables A, B and C. When from packet manager console I issue
Add-Migration mig1
Update-Database
Add-Migration mig1
Update-Database
The database is correctly created. Howerver, if later on I add a table D to my DbContext, remove previously created migrations and I run
Add-Migration mig2
Update-Database
Add-Migration mig2
Update-Database
The second command fails with error message
relation "A" already exists
relation "A" already exists
Is there a way to only add not-existing tables (i.e. create if not exists) using migrations?
3 replies