DaVinki
DaVinki
CC#
Created by DaVinki on 11/2/2023 in #help
❔ ✅ WinForms ListBox.DataSource not working
I have a ListBox that contains only instances of Employee. ToString looks like Employee { Name: "John Smith", Id: 123, Salary: $100,000.00 }. Without creating my own list and instead just adding objects to the ObjectCollection already owned by the ListBox, everything works. When I create my own list public List<Employee> _employees and initialize it before the components of the form and set the ListBox data source after the components in the form constructor, no values from the list are shown. I am refreshing the ListBox in its prompt closing event after adding the Employee to the list. Looking online did not help since they all said to do what I thought I needed to do to bind a ListBox in the first place, which is to just set the data source using the appropriate object or refreshing the list. Here's the relevant code:
public partial class Form1 : Form
{
private List<Employee> _employees;
public Form1()
{
_employees = new();
InitializeComponent();
EmployeesListBox.DataSource = _employees;
}

private void CreateEmployeeButton_Click(object sender, EventArgs e)
{
var employee = new Employee();
var prompt = new EmployeeCreatorForm(employee);
prompt.Closing += (_, _) => // No leaking since prompt is closing
{
if (!prompt.Completed)
return;

_employees.Add(employee);
Show();
EmployeesListBox.Refresh();
};

Hide();
prompt.Show();
}

private void CreateManagerButton_Click(object sender, EventArgs e)
{
var manager = new Manager();
var prompt = new ManagerCreatorForm(manager);
prompt.Closing += (_, _) =>
{
if (!prompt.Completed)
return;

_employees.Add(manager);
Show();
EmployeesListBox.Refresh();
};

Hide();
prompt.Show();
}
}
public partial class Form1 : Form
{
private List<Employee> _employees;
public Form1()
{
_employees = new();
InitializeComponent();
EmployeesListBox.DataSource = _employees;
}

private void CreateEmployeeButton_Click(object sender, EventArgs e)
{
var employee = new Employee();
var prompt = new EmployeeCreatorForm(employee);
prompt.Closing += (_, _) => // No leaking since prompt is closing
{
if (!prompt.Completed)
return;

_employees.Add(employee);
Show();
EmployeesListBox.Refresh();
};

Hide();
prompt.Show();
}

private void CreateManagerButton_Click(object sender, EventArgs e)
{
var manager = new Manager();
var prompt = new ManagerCreatorForm(manager);
prompt.Closing += (_, _) =>
{
if (!prompt.Completed)
return;

_employees.Add(manager);
Show();
EmployeesListBox.Refresh();
};

Hide();
prompt.Show();
}
}
9 replies
CC#
Created by DaVinki on 8/28/2023 in #help
❔ ✅ Display all properties of different types without an attribute in a WPF list?
I have a Vehicle object that looks like this:
public class Vehicle
{
[DoNotLogInCsv]
private ILogger? Logger { get; }
[DoNotLogInCsv]
public VehicleProfile Profile { get; }
public DescribedValue<float> Rpm { get; private set; }
public DescribedValue<int> IntakeManifoldAbsolutePressure { get; private set; }
public DescribedValue<float> EngineLoad { get; private set; }
public DescribedValue<int> FuelPressure { get; private set; }
public DescribedValue<float> ThrottlePosition { get; private set; }
public DescribedValue<float> TimingAdvance { get; private set; }
public DescribedValue<float> IntakeAirTemperature { get; private set; }
public DescribedValue<float> ShortTermFuelTrimBank1 { get; private set; }
public DescribedValue<float> LongTermFuelTrimBank1 { get; private set; }
public DescribedValue<int> VehicleSpeed { get; private set; }
public DescribedValue<float> MafAirFlowRate { get; private set; }
public DescribedValue<int> RuntimeSinceEngineStart { get; private set; }
public DescribedValue<float> CommandedAirFuelEquivalencyRatio { get; private set; }
public DescribedValue<int> EngineOilTemperature { get; private set; }
public DescribedValue<float> FuelInjectionTiming { get; private set; }
}
public class Vehicle
{
[DoNotLogInCsv]
private ILogger? Logger { get; }
[DoNotLogInCsv]
public VehicleProfile Profile { get; }
public DescribedValue<float> Rpm { get; private set; }
public DescribedValue<int> IntakeManifoldAbsolutePressure { get; private set; }
public DescribedValue<float> EngineLoad { get; private set; }
public DescribedValue<int> FuelPressure { get; private set; }
public DescribedValue<float> ThrottlePosition { get; private set; }
public DescribedValue<float> TimingAdvance { get; private set; }
public DescribedValue<float> IntakeAirTemperature { get; private set; }
public DescribedValue<float> ShortTermFuelTrimBank1 { get; private set; }
public DescribedValue<float> LongTermFuelTrimBank1 { get; private set; }
public DescribedValue<int> VehicleSpeed { get; private set; }
public DescribedValue<float> MafAirFlowRate { get; private set; }
public DescribedValue<int> RuntimeSinceEngineStart { get; private set; }
public DescribedValue<float> CommandedAirFuelEquivalencyRatio { get; private set; }
public DescribedValue<int> EngineOilTemperature { get; private set; }
public DescribedValue<float> FuelInjectionTiming { get; private set; }
}
A described value is just a string Description and T Value pair object I want to get all of these properties without the CSV logging attribute to be shown in a WPF list. Any ideas on how I can do this? Couldn't come up with anything after a few hours and can't find much online.
5 replies
CC#
Created by DaVinki on 8/27/2023 in #help
❔ WPF TextBlock colored background no stretching with ListBox HorizontalContentAlignment
3 replies
CC#
Created by DaVinki on 8/19/2023 in #help
❔ Questions regarding delegates and closures
If I had some static objects with a delegate member (Func<byte[], int>) that was assigned an anonymous function on startup, how much slower would calling the delegate be than a regular function after JIT warmup? No closures. This would be a hot path. My second question would be is it possible to capture a variable without going through the whole closure process? The capturing delegate is also a hot path so I want to avoid instantiating any objects for a function call or at least what could effectively be a function call. There's potentially over 150 different ways of doing things and I don't want to create 150+ types to implement or override a function. I believe anonymous functions are the best way to go about it for the programmer's convenience I might be overthinking this or have an inadequate understanding of delegates to know if they're right for the task or right for performance. The data is live and constantly being received which is where the concern for performance comes from
3 replies
CC#
Created by DaVinki on 6/19/2023 in #help
❔ Does the C# version matter for a netstandard2.1 library?
Title
10 replies
CC#
Created by DaVinki on 6/14/2023 in #help
❔ Best pattern to alleviate the pain of a many-to-many unit conversion program?
For example, converting gallons to any other volumetric unit and vice versa
11 replies
CC#
Created by DaVinki on 6/1/2023 in #help
✅ Framework targeting
A little lost on the point of targeting multiple frameworks. Why target anything higher than your lowest target? For example, why target netstandard2.1 if you're already targeting netstandard2.0? What benefits does a project get from targeting net48, netstandard2.0, netstandard2.1, netcoreapp3.1 and net6.0 all at once? What happens when all of these are targeted vs just net6.0 or just netstandard2.1?
201 replies
CC#
Created by DaVinki on 5/2/2023 in #help
❔ Background process in tray without window
I'm having a hard time finding information on running an app in the system tray without a window. In this case it's a little console app that will make an API request every 2-3 hours to automate something. Everything I've found so far either refers to ASP.NET, UI background workers or using a process to start another process without a window using the Process class. If there really is no other way to do it other than using the Process class to start another process of my own without a window, how would I publish it to have both processes and have the starting process correctly reference the background process?
9 replies
CC#
Created by DaVinki on 3/31/2023 in #help
❔ Ignore fallback folders that don't exist in a NuGet config (MSB4018)?
I installed a "portable" .NET build of Godot that leaves behind a file %APPDATA%/NuGet/config/Godot.Offline.Config which defines a fallback folder in Godot's settings folder. The thing is, I have it on a USB drive so the file that was generated on my C drive points to a directory on my F drive. On my laptop, everything becomes broken, the .NET namespaces can't be found, and MSBB4018 is thrown when trying to build while the Godot config file exists. On my desktop, nothing is wrong and the file coexists. Why does indexing and building break on my laptop but not on my desktop? Why, when the fallback folder isn't found, is it not just ignored like it is on my desktop?
4 replies
CC#
Created by DaVinki on 3/30/2023 in #help
✅ ResolvePackageAssets is failing because it can't find the NuGet fallback folder
I installed something called Godot portably on a USB which ended up being more invasive than everybody says. Now, none of my projects across all .NET SDKs are failing because it can't find "GodotNuGetFallbackFolder" that Godot created when the USB isn't plugged in. This is happening on all computers I ran Godot on. It's not malware, but it sure sounds like it. Is there some way to reset it back to what it was? I've reinstalled .NET, ran the repair tool, and I couldn't find much online. To nobody's surprise, deleting the obj and bin of a project and restoring NuGet doesn't fix it. Restoring the NuGet doesn't error when restoring though
Microsoft.PackageDependencyResolution.targets(266, 5): [MSB4018] The "ResolvePackageAssets" task failed unexpectedly.
NuGet.Packaging.Core.PackagingException: Unable to find fallback package folder 'F:\Godot\Godot_v4.0.1-stable_mono_win64\editor_data\mono\GodotNuGetFallbackFolder'.
at NuGet.Packaging.FallbackPackagePathResolver..ctor(String userPackageFolder, IEnumerable`1 fallbackPackageFolders)
at Microsoft.NET.Build.Tasks.NuGetPackageResolver.CreateResolver(IEnumerable`1 packageFolders)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheWriter..ctor(ResolvePackageAssets task)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader.CreateReaderFromDisk(ResolvePackageAssets task, Byte[] settingsHash)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader..ctor(ResolvePackageAssets task)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ReadItemGroups()
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ExecuteCore()
at Microsoft.NET.Build.Tasks.TaskBase.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask)
Microsoft.PackageDependencyResolution.targets(266, 5): [MSB4018] The "ResolvePackageAssets" task failed unexpectedly.
NuGet.Packaging.Core.PackagingException: Unable to find fallback package folder 'F:\Godot\Godot_v4.0.1-stable_mono_win64\editor_data\mono\GodotNuGetFallbackFolder'.
at NuGet.Packaging.FallbackPackagePathResolver..ctor(String userPackageFolder, IEnumerable`1 fallbackPackageFolders)
at Microsoft.NET.Build.Tasks.NuGetPackageResolver.CreateResolver(IEnumerable`1 packageFolders)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheWriter..ctor(ResolvePackageAssets task)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader.CreateReaderFromDisk(ResolvePackageAssets task, Byte[] settingsHash)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.CacheReader..ctor(ResolvePackageAssets task)
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ReadItemGroups()
at Microsoft.NET.Build.Tasks.ResolvePackageAssets.ExecuteCore()
at Microsoft.NET.Build.Tasks.TaskBase.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask)
4 replies
CC#
Created by DaVinki on 2/14/2023 in #help
❔ ✅ Using a foreach loop on a custom enumerator
I created my own enumerator using the IEnumerator<T> interface but refactored it into a ref struct which can't implement interfaces. How can I use foreach with it? I noticed that Span<T>.Enumerator does this but probably because it's a part of .NET
using System.Numerics;

namespace common_vector_ops;

public ref struct VectorIterator<T> where T : struct
{
public int Index { get; private set; }
public int Increment { get; }
public Span<T> VectorizedSpan { get; }

public VectorIterator() : this(Span<T>.Empty)
{
}

public VectorIterator(T[] array)
{
VectorizedSpan = array.AsSpan();
Increment = Vector<T>.Count;
Index = -Increment;
}

public VectorIterator(Span<T> span)
{
VectorizedSpan = span;
Increment = Vector<T>.Count;
Index = -Increment;
}

public bool MoveNext()
{
Index += Increment;
return Index <= VectorizedSpan.Length - Increment;
}

public void Reset()
{
Index = -Increment;
}

public Vector<T> Current => new Vector<T>(VectorizedSpan[Index..]);
}
using System.Numerics;

namespace common_vector_ops;

public ref struct VectorIterator<T> where T : struct
{
public int Index { get; private set; }
public int Increment { get; }
public Span<T> VectorizedSpan { get; }

public VectorIterator() : this(Span<T>.Empty)
{
}

public VectorIterator(T[] array)
{
VectorizedSpan = array.AsSpan();
Increment = Vector<T>.Count;
Index = -Increment;
}

public VectorIterator(Span<T> span)
{
VectorizedSpan = span;
Increment = Vector<T>.Count;
Index = -Increment;
}

public bool MoveNext()
{
Index += Increment;
return Index <= VectorizedSpan.Length - Increment;
}

public void Reset()
{
Index = -Increment;
}

public Vector<T> Current => new Vector<T>(VectorizedSpan[Index..]);
}
14 replies
CC#
Created by DaVinki on 2/5/2023 in #help
❔ What is the difference between string pool and intern pool?
In the Windows Community Toolkit's high performance library, there is a string pool. What makes this different from the intern pool that .NET has? They both store strings to reuse so I'm curious
10 replies
CC#
Created by DaVinki on 1/18/2023 in #help
❔ Can someone help me fully understand ref returns?
I have not been able to get this through my head aside from a few things like never using a ref return if a variable does not exist outside of scope. What about something like keeping local variables alive through ref returns? Seeing the Span<T> type do these things confuses me. How is it able to do something like this considering ref return constraints, knowing it's a ref struct only on the stack? It's local but the GC knows it's still in use after returning
public static Span<int> SpanOf(int[] arr)
{
var span = new Span<int>(arr);
return span;
}
public static Span<int> SpanOf(int[] arr)
{
var span = new Span<int>(arr);
return span;
}
But you can't do anything like this which is what confuses me about the whole thing:
public static ref int RefCopyOf(int n)
{
ref var refCopyOfN = ref n;
return ref refCopyOfN;
}
public static ref int RefCopyOf(int n)
{
ref var refCopyOfN = ref n;
return ref refCopyOfN;
}
11 replies
CC#
Created by DaVinki on 1/14/2023 in #help
❔ Are there standards to whether someone should use fields or properties?
I always spend a second thinking if I should use fields or properties when I am making classes. I'm not sure which one to use ever aside from having a public getter and private setter but it always works out anyways lol. Is there a standard that I can follow in order to properly use fields and properties? I also have a question about using reference types in structs. I have read in most places that it is generally frowned upon to use reference type inside of structures, but I have also seen and read many things that do this. What is the general consensus on using reference types inside of structures, or when is it OK to do this?
10 replies
CC#
Created by DaVinki on 1/4/2023 in #help
✅ Creating a number generically?
Is it possible to do this? For example, here's this basic method that gets the digits of any object implementing INumber:
public static IEnumerable<TNumber> GetDigits<TNumber>(TNumber number, TNumber ten) where TNumber : INumber<TNumber>
{
List<TNumber> digits = new();
while (number > TNumber.Zero)
{
digits.Add(number % ten);
number /= ten;
}

digits.Reverse();
return digits;
}
public static IEnumerable<TNumber> GetDigits<TNumber>(TNumber number, TNumber ten) where TNumber : INumber<TNumber>
{
List<TNumber> digits = new();
while (number > TNumber.Zero)
{
digits.Add(number % ten);
number /= ten;
}

digits.Reverse();
return digits;
}
Instead of having to pass 10 into the method, would there be a way to create the 10 inside of the method to hide it from the user?
4 replies
CC#
Created by DaVinki on 1/4/2023 in #help
✅ Code highlighting issue in Rider with Int128 and UInt128 types
9 replies
CC#
Created by DaVinki on 12/14/2022 in #help
✅ Using Linq's Cast Method
I've never been able to get it to not warn and throw errors except for one, maybe two times. It is always warning me even if the cast is what I want and has thrown over it before. These casts are trivial casts like casting an int to another value type like long or char. I also have never really bothered asking about it since I just do .Select(o => (T)o) in the end. Say I had an IEnumerable of random ints. Why can't I just do .Cast<char>() if I wanted to cast them into chars instead of doing .Select(i => (char)i)? If I can, what am I missing to do so?
10 replies
CC#
Created by DaVinki on 9/28/2022 in #help
Is there any way to simplify this, or a design pattern I should be following?
public event EventHandler<FizzbuzzDetermineNumberRequest>? DetermineNumberRequestHandlers;
public event EventHandler<FizzbuzzNumberDeterminedEvent>? NumberDeterminedEventHandlers;
public event EventHandler<FizzbuzzPrintInfo>? PrintRequestHandlers;
public event EventHandler<FizzbuzzPrintInfo>? PrintEventHandlers;

public void RequestDetermineNumber(object? sender, FizzbuzzDetermineNumberRequest? rq)
{
DetermineNumberRequestHandlers?.Invoke(sender, rq);
}

public void FireNumberDeterminedEvent(object? sender, FizzbuzzNumberDeterminedEvent ev)
{
NumberDeterminedEventHandlers?.Invoke(sender, ev);
}

public void RequestPrint(object? sender, FizzbuzzPrintInfo rq)
{
PrintRequestHandlers?.Invoke(sender, rq);
}

public void FirePrintEvent(object? sender, FizzbuzzPrintInfo ev)
{
PrintEventHandlers?.Invoke(sender, ev);
}
public event EventHandler<FizzbuzzDetermineNumberRequest>? DetermineNumberRequestHandlers;
public event EventHandler<FizzbuzzNumberDeterminedEvent>? NumberDeterminedEventHandlers;
public event EventHandler<FizzbuzzPrintInfo>? PrintRequestHandlers;
public event EventHandler<FizzbuzzPrintInfo>? PrintEventHandlers;

public void RequestDetermineNumber(object? sender, FizzbuzzDetermineNumberRequest? rq)
{
DetermineNumberRequestHandlers?.Invoke(sender, rq);
}

public void FireNumberDeterminedEvent(object? sender, FizzbuzzNumberDeterminedEvent ev)
{
NumberDeterminedEventHandlers?.Invoke(sender, ev);
}

public void RequestPrint(object? sender, FizzbuzzPrintInfo rq)
{
PrintRequestHandlers?.Invoke(sender, rq);
}

public void FirePrintEvent(object? sender, FizzbuzzPrintInfo ev)
{
PrintEventHandlers?.Invoke(sender, ev);
}
29 replies
CC#
Created by DaVinki on 9/21/2022 in #help
How to use relative path in referenced project within same solution?
I made a project for a simple Person object. In this project, I include a resources directory that contains a names.txt. I use a relative path to the text file in my Person project but when I run the program, the directory isn't correct. The path is Person/Resources/names.txt but comes out to be SolutionDirectory\bin\Debug\net6.0\Person\Resources\names.txt in the error where the entire relative path doesn't exist. It ends at net6.0. Is there a way I can include resources from other projects into the running project's bin?
12 replies