452 questions from the last 30 days
3
votes
4
answers
102
views
Populating generic object that is known to be an array at runtime
I have a generic method that returns type T (generic). In the method, if T is an array, I want to create and populate this array with data and return.
I've gotten to the point where I have a List<...
-2
votes
2
answers
147
views
How do you implement reader/writer task synchronization using C# async programming?
This is basic task synchronization 101 but I can't find search terms that tell me what I need to know. And I'm sure it's a dup here.
The classic task synchronization reader/writer problem is you have ...
1
vote
2
answers
131
views
Is there a tidy way to declare a variable that I need to assign to inside a lock()? [closed]
I have a line of code:
var dates = League.AllGames.Select(g => g.Time.Date).Distinct().ToList();
But I need to lock the League object before I do LINQ on AllGames -- League has several lists that ...
4
votes
1
answer
181
views
Why is a ConcurrentDictionary faster than a Dictionary in benchmark?
I have a really simple benchmark to measure and compare performance of Dictionary<string, int> and ConcurrentDictionary<string, int>:
[MemoryDiagnoser]
public class ...
6
votes
1
answer
157
views
Is it possible to use Buttons while keeping the dropdown List of a ComboBox open?
I'm trying to create a ComboBox with 2 Buttons (Sort / Expand).
I've created the Buttons in code and I show them in the DropDown Event of the ComboBox, right next to the ComboBox.
Is it possible to ...
3
votes
1
answer
172
views
Why is EnterCriticalSection not timing out?
From the documentation on EnterCriticalSection:
This function can raise EXCEPTION_POSSIBLE_DEADLOCK, also known as STATUS_POSSIBLE_DEADLOCK, if a wait operation on the critical section times out. The ...
1
vote
3
answers
119
views
Can I declare an intersection type in C#
In C#, I have the following classes and interfaces (outside my control)
public interface IA
{
int doA();
}
public interface IB
{
int doB();
}
class Impl1: IA, IB
{
int doA() => 1;
...
2
votes
2
answers
211
views
Load Custom Controls into ToolBox in .NET 8
I have a library project which is .NET8-windows:
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<...
3
votes
2
answers
97
views
Does UDP receive messages in a queue-like format?
I have two programs set up to mimic two machines that will be communicating using UDP (I know TCP sounds better in this situation, but the manufacturer for one of the machines made it such that ...
0
votes
2
answers
451
views
Trouble with ASP.NET Core 8 & Angular project
I'm trying to launch the "Weather Forecast" template solution but encountering an issue I can't resolve.
Here's what I've done:
First, I installed Visual Studio 2022 and Angular 17 (npm ...
1
vote
1
answer
114
views
Can I send Console.WriteLine() output to a control on a Winform within the same app
I have a .NET console app that does some processing - reading .TXT files, and generating new ones. Throughout the code are instances of Console.WriteLine(...) that outputs various progressing info to ...
1
vote
1
answer
73
views
Why does ISymbol.ContainingNamespace always return System for nullable structs?
Using the Roslyn API I tried to retrieve the namespace of a nullable struct type (using ISymbol.ContainingNamespace) and was suprised when it returned the System namespace instead. This only happens ...
2
votes
2
answers
143
views
Skip Take performance issue
I am coming across a strange issue with EF Core 8.017.
I have a query that searches a table of document metadata. A document's text is a column with a full text catalog that is queried using the EF....
0
votes
2
answers
142
views
A C# question about adding a value to a dictionary
I have
var foundItems = new Dictionary<string, List<string>>();
string[] targetColumns;
string value;
Adding a value to a key works fine with this code:
foundItems[targetColumns[i]].Add(...
3
votes
1
answer
190
views
How to free memory in cpp that is allocated in c# on linux
My function that returns a string looks like this in c#:
[return: MarshalAs(UnmanagedType.LPWStr)]
public static string? GetText()
{
return SomeClass.SomeMethodThatReturnsAString();
}
And function ...
0
votes
2
answers
195
views
How to define the data model as a SQL variable not a table or view in EF Core?
I can't figure out if I properly defined the data model as a SQL variable, not a table or view, in EF Core, because the SQL Server's stored procedure and the Blazor web app are successfully ...
3
votes
1
answer
145
views
Why FileSystemInfo.Refresh doesn't update timestamps after file deletion
There's a few posts here explaining the caching behavior of FileSystemInfo and the derived FileInfo class such as this one . But when the following code is run,
static void Main(string[] args)
{
...
1
vote
1
answer
107
views
How does C# determine the end of a string without a null terminator?
I'm new to C#. While learning about strings, I came across the fact that C# strings are internally a sequence of char objects and do not use a null-terminating character ('\0') like in C or C++.
Given ...
1
vote
2
answers
75
views
Is there a way to ignore specific subfolders when using DirectoryInfo.EnumerateFiles without manual recursion?
I'm using the following code to get all files of given extensions inside a folder with it's respective subfolders.
string path = "C:\\FolderA\\FolderB\\FolderC\\FolderD";
List<string> ...
-1
votes
1
answer
81
views
Regex character range excluding one character
Is there any straight-forward way to create a regex pattern in .NET that includes all characters in a range except one?
I want to find any lowercase letter except 's'.
Currently I'm using "[a-r t-...
3
votes
2
answers
73
views
Required attribute is not working for the body request at the method of API endpoint
I have simple API methods. I need to check whether the body request is null. For example:
[HttpPost]
public ActionResult<Product> CreateProduct([FromBody] Product product)
{
if (product == ...
0
votes
1
answer
107
views
How can I refactor a widely-used C# class to support constructor dependency injection without breaking existing usages? [closed]
In my C# ASP.NET Core project, I have a class that is currently instantiated using a parameterless constructor. This class is used in hundreds of places throughout the solution.
I now need to refactor ...
-2
votes
1
answer
185
views
Interpolate the SqlParameter[] arguments with "EXEC {storedProcedure}" dynamically [closed]
I am using .NET 9 for this Blazor web app project, what I'm trying to achieve is to write a dynamic handling of SqlParameter[] arguments and interpolate it with "EXEC {storedProcedure}" ...
4
votes
1
answer
157
views
Calculate rotation of a point around another point on earth (or sphere)
Essentially what I'm trying to do is moving a point relative to two different scales.
The reason is to edit values in a database of a 3d party application.
So basically I want to relocate the red ...
3
votes
1
answer
122
views
I have an encrypted text from Java's Bouncy Castle Library using AES/GCM which I am unable to decrypt using C# Bouncy Castle library AES/GCM
I have a text which I am encrypting using Java's Bouncy Castle AES/GCM utility.
package com.stackoflow.symmetric_token_decryptor;
import static org.apache.commons.codec.binary.Hex.encodeHex;
...
3
votes
2
answers
103
views
Convince System.Text.Json to ignore a property with the `required` modifier
I've got a simple type:
public class Example {
[JsonIgnore]
public required string RequiredButDontSerialize {get;init;}
public string AnotherPropertyWhatever {get;init;}
}
that causes System....
3
votes
1
answer
128
views
How to bind "DataGridComboBoxColumn.ItemsSource" to Enum collections declared in different derived classes displayed by DataGrid rows?
I have an ObservableCollection of Base Objects bound to a datagrid. I am trying to populate a DataGridComboBoxColumn with Enum values from a derived class instantiated in the observable collection.
...
0
votes
2
answers
102
views
If I specify the capacity of a dictionary through the constructor, should I use a prime? [closed]
I am initializing a fairly large dictionary in C#.
I have benchmarked the speed of building the dictionary with the capacity and without. It is (as expected) significantly faster (and uses ...
1
vote
1
answer
98
views
How to find and read files with malformed names in .NET?
I have deliberately create a file with a malformed name:
printf '\xC3\x28malformed_name.txt' | xargs touch
Verifying it exists:
ls
''$'\303''(malformed_name.txt'
.NET can also see the file:
open ...
4
votes
2
answers
99
views
How do I mock DbSet.Add() for Entity Framework Core?
I'm mocking a DbContext to auto-test classes that update the database.
I'm using Entity Framework Core and .NET 5.
Mock<MyDbContext> fakeDbContext = new Mock<MyDbContext>();
List<Book&...
0
votes
2
answers
152
views
C# System.IO.FileNotFoundException Loading Dll
Assembly assembly = Assembly.LoadFrom("System.Private.CoreLib.dll");
With C#, I am trying to load that dll, but it keeps saying:
Unhandled exception. System.IO.FileNotFoundException: Could ...
1
vote
2
answers
100
views
How can I improve input validation in a C# console application? [closed]
I’m currently working on a Student Grade Management System in C# as part of my learning project. The application allows users to add students, assign grades, calculate averages, and display student ...
4
votes
1
answer
155
views
How to connect .NET application to IBM MQ using Server Side SSL/TLS authentication with username and password (X.509 certificate-based auth)?
I'm trying to connect my .NET (8.0) application to IBM MQ over TLS using X.509 certificate-based authentication, but running into issues during the SSL handshake.
Using Python + pymqi, I was able to ...
1
vote
1
answer
100
views
How can I disable these C# suggestions in Visual Studio?
Since a recent update, when editing C# code, I'm getting suggestions in Visual Studio which I have not seen before, see the highlighted part in the screenshot.
This is not the IntelliSense auto-...
0
votes
1
answer
125
views
Where is the flaw in this greedy approach?
I am sitting on a LeetCode problem, specifically Minimum Time to Repair Cars.
You get a list of how many mechanics you have and how many cars you need to fix.
Each mechanic has a rank, and he takes ...
1
vote
2
answers
158
views
PowerShell.Create() New-LocalUser not recognized as the name of a cmdlet [closed]
I'm trying to create a new local user in Windows by running a PowerShell script from a C# console application. I installed the necessary NuGet packages Microsoft.PowerShell.SDK (v7.5.2) and System....
0
votes
1
answer
140
views
.NET DataViewGrid displays both date and time in a column unless it's midnight then you only see the date
I'm displaying the date and time in a DataViewGrid column and that works as expected unless it's midnight and then it's only displaying the date. I want it to display the time no matter what.
// ...
0
votes
3
answers
87
views
Loop through tags based on IgnoreCase attribute value
Please consider this xml:
<Interface>
<Header>...</Header>
<Body>...</Body>
<Footer>...</Footer>
<Parameters>
<...
-5
votes
3
answers
144
views
How to log and return in one statement? [closed]
A lot of code we write looks like this:
void myBigFunction()
{
doSomething()
if (somethingAintRight())
{
_log.LogWarning("Something ain't write");
return;
}
...
1
vote
1
answer
91
views
How does TaskCompletionSource work when an exception occurs?
I'm trying to understand how exception handling works with TaskCompletionSource and await in a console application (which has no SynchronizationContext).
I've written simple code that waits for a ...
-1
votes
1
answer
170
views
How to have one view instance per viewmodel in tabcontrol? [closed]
I have a TabControl showing views from ObservableCollection<IProjectViewModel> Projects.
ProjectViewModel and ProjectVarioViewModel do implement IProjectViewModel. The first of each get one ...
2
votes
1
answer
179
views
Awaiting a TaskCompletionSource from two threads
I got curious about what would happen if you await a TaskCompletionSource from two threads.
using System.Diagnostics;
var t = Start();
var t1 = Task.Run(async () => {
await t;
Thread.Sleep(...
4
votes
1
answer
130
views
How to get csharp-ls language server in neovim to find the root of my project?
I'm trying to set up the csharp-ls LSP for use in neovim for C# files. My init.lua file looks like this:
vim.lsp.config(
'csharp-ls',
{
cmd = { 'csharp-ls' },
filetypes = { 'cs'...
0
votes
0
answers
173
views
Access denied while deleting in .NET
I'm trying to figure out why I'm getting an "Access denied" error while deleting a Directory via
System.IO.Directory.Delete(Path.Combine(path, folderName), true);
These folders are being ...
1
vote
2
answers
122
views
Multiple buttons which act independently on click
I'm working with Winforms and using Visual Studio.
I'm curious as if to whether or not there is a bulk way to create multiple buttons that act independently (have their own click functions).
I know I ...
2
votes
1
answer
75
views
C# GDI+ questionable font rendering on Win 7
I am trying to render some kind of a picture using GDI+ with dynamically loaded fonts. Here is a minimal example (.NET 8.0):
private void Form1_Load(object sender, EventArgs e)
{
...
1
vote
1
answer
100
views
How to bind List item inside DataTemplate
I have a ListView that I fill with a list of items of type FooBar, which contains only one public member Foo of string. I have my own UserControl called FooBarControl, which has a member FooBar from ...
-1
votes
2
answers
96
views
How to deserialize JSON object with nesting [closed]
I am trying to deserialize a JSON object:
{
"columns":"1",
"ctrl":{
"height":"24",
"offcolour":"#ff000000",...
1
vote
0
answers
178
views
How to write data to a gip device (Xbox Series controller)?
I am working on a C# program that would send a power off packet to my xbox series controller in order to turn it off.
In 2024 Microsoft released GIP docs and as far as I understand Xbox One and Series ...
0
votes
3
answers
144
views
Can't validate shopify header in webhook
I’m building an application using .NET 8 and created a webhook through Shopify’s API to detect when new products are created.
This is the request body I used to register the webhook:
{
"webhook&...