br4kejet
br4kejet
CC#
Created by br4kejet on 8/11/2024 in #help
✅ SerialPort performance
I'm doing some tests on the performance of serial communication and I'm geting a fair chunk of perforance loss. At a baud rate of 38400, with 7 data bits and 1 stop bit, then I can expect to get a maximum of 26kbps, but I received 120 bytes in just under 50 milliseconds which seems to be about 20 kbps. Anyone know what would be causing this?
68 replies
CC#
Created by br4kejet on 8/10/2024 in #help
Type arguments cannot be inferred from usage
This is the code I have now:
public OperationResult<string> ReadString(string address) {
OperationResult<EfortData> read = this.ReadEfortData();
if (!read.IsSuccess)
return read.CreateFailedResult();
...
}
public OperationResult<string> ReadString(string address) {
OperationResult<EfortData> read = this.ReadEfortData();
if (!read.IsSuccess)
return read.CreateFailedResult();
...
}
And CreateFailedResult is implemented as:
public OperationResult<A1> CreateFailedResult<A1>() => new OperationResult<A1>(this.ErrorCode, this.Message);
public OperationResult<A1> CreateFailedResult<A1>() => new OperationResult<A1>(this.ErrorCode, this.Message);
I don't really understand why it can't figure out that A1 is going to be string, since that's the type argument for ReadString's return type?
10 replies
CC#
Created by br4kejet on 3/10/2024 in #help
Is volatile necessary when using a lock to read/write the variable?
On this line, i defined the state as volatile and the code works fine, but I'm wondering if it really needs to be volatile? Multiple threads can read/write the variable but they always lock the stateLock first https://github.com/AngryCarrot789/SharpPad/blob/ef18f1767eb7e855e5575ff0457bdd793947f973/SharpPad/Utils/RDA/RapidDispatchActionEx.cs#L38
14 replies
CC#
Created by br4kejet on 2/24/2024 in #help
Adding cmake project to VS solution?
I use a C library (which uses cmake to compile it), and I use P/Invoke to call the methods. At the moment, I just manually clone the git repo, add to my solution folder, compile it and then copy the output DLL files to my C# app's bin folder. Is there a way to automate this?
4 replies
CC#
Created by br4kejet on 2/22/2024 in #help
✅ Invalidating inherited Properties Tree in WPF
I'm trying to implement an inherited list property (called InheritedCustomContextList) which merged all of the values for my property called CustomContext in the visual tree (e.g. if window has ObjA, Grid has ObjB, then the value of InheritedCustomContextList for a child inside of the grid will contain ObjA and ObjB). I managed to get it to work by setting the value for InheritedCustomContextList to the parent's value + the CustomContext value (if available), and I do basically the same the Coerce callback for InheritedCustomContextList My problem though is that, If I change CustomContext for the window, then that child inside the grid will still reference ObjA, because WPF's tree walker thing that updates inherited values does not continue walking once it sees a DP has a local value set (in this case, it reaches the Grid, sees that it has a local value for InheritedCustomContextList and stops). I'm not sure how to fix this, maybe if there was a way to regenerate all inherited values for the entire visual tree (starting at the window's content element). Any help would be great 😄
1 replies
CC#
Created by br4kejet on 2/20/2024 in #help
Version based serialisation
Is there a good way to implement version-based serialisation? E.g. if ObjectA has some serialisable data in version 1.0, but in v1.1 some things are removed and new things are added, how do you maintain backwards compatibility with the old serialised data?
7 replies
CC#
Created by br4kejet on 2/15/2024 in #help
Is there a name for this type of code/system?
I couldn't think of a better title, but the system I'm talking about is IntelliJ IDEA's Disposer system (I imagine Rider uses it too). If you don't know what it is, it has a central manager class that manages a tree of disposable object, and when you dispose of an object, it first disposes all children before finally disposing the object itself. The disposable objects themselves don't actually store any child disposable objects; the manager class stores it in that tree (application wide), so it's very easy to use and implement new disposable objects. I really want to look up more info about systems similar to this like some sort of "deferred node tree", but I don't know where to begin researching it
3 replies
CC#
Created by br4kejet on 2/7/2024 in #help
Best practices when using C++ DLL Project interop with C#?
I've implemented some of my project in C++ and I call that code from C#. My current way of loading the DLL is to call the LoadLibrary (and then use GetProcAddress + the Delegate helper method to invoke methods safely from C#). But I have to hard code the DLL's path, allowing it to either exist in the bin folder, or backing out of that folder to the solution folder and into x64, etc., to the built DLL file. How else can I load the DLL?
8 replies
CC#
Created by br4kejet on 2/5/2024 in #help
✅ LoadLibrary works, but does not show in Debug>Windows>Modules tab
I'm trying to load a DLL file into my WPF app, and it works since the returned address is valid, GetProcAddress works and I'm able to call a method and have it return an expected value. But if I try to place breakpoints in the C++ project I get "breakpoint will not be hit", and the DLL doesn't show up in the tab in Debug>Windows>Modules. Anyone know why this happens?
2 replies
CC#
Created by br4kejet on 1/12/2024 in #help
Struggling to keep using MVVM, feeling like abandoning it
Hi, i've been making a video editor for fun in my spare time and, while it functions, the code base is dreadful and adding new features takes so long and always leads to bugs because I'm basically shadowing all models with view models, in order to bind things in the UI In my app, I have a VideoEditor class, which contains the active Project, containing the main Timeline, which contains a list of Track objects, which contains a list of Clip objects, so overall a somewhat deep hierarchy of objects. But in order to fully support binding, I have to create a complete shadow with view models: VideoEditorViewModel (the datacontext of the main window), ProjectViewModel, TimelineViewModel, TrackViewModel, ClipViewModel. And since tracks and clips are basically abstract, I have to create a view model for each type of model, and register some type of mapping between model and view model so that I can create view models from models. But there's also this: tracks have add, remove and move events for clips and, while adding/removing clips is easy (model fires add or remove event, track view model responds), implementing a move operation is difficult; the model can't access view models, so how do I move the clip VM from the source track VM to target track VM? Sorry for the ultra long post but trying to keep this app within the MVVM bounds is becoming more and more difficult. I experimented by accessing models directly in controls and it feels so much easier, although I have to manually handle all the appropriate events in the models (such as DisplayNameChanged, FrameSpanChanged; frame spans containing a pos and duration) instead of just relying on PropertyChanged+Binding in view models... but at least the code becomes much much easier to write and modify, and is more straight forward to me. Does anyone have any advice? It would be really helpful, thanks 😄
59 replies
CC#
Created by br4kejet on 12/2/2023 in #help
WPF window doesn't render after opening
I sometime experience this bug where when a window (whose mode is set to tool so that it only shows a close button) is shown using ShowDialog, it doesn't render sometimes. It seems to be random so i've never been able to reproduce it reliably. I'm also using a WindowChrome, so maybe that's why? Does anyone know what causes this?
5 replies
CC#
Created by br4kejet on 10/22/2023 in #help
❔ Best way to cache index of an object in a list
I have a list with anywhere from 0 to maybe 1000 objects in it, and I have to try and find the index of that object very quickly (during mouse move events, so 100s of times per second possibly) What would be a good way to optimise this?
65 replies
CC#
Created by br4kejet on 10/11/2023 in #help
✅ Compiler creates closure when it's not necessary?
I have this function here:
public static void Run<T>(Action<T> action, T parameter) => action(parameter);
public static void Run<T>(Action<T> action, T parameter) => action(parameter);
And then I'm using it like this:
MyObject obj = null;
Run(t => t.Item1.DoThing(t.Item2), (this, obj));
MyObject obj = null;
Run(t => t.Item1.DoThing(t.Item2), (this, obj));
But I have the "Heap Allocation Viewer" plugin installed in Rider, and it says it allocates a closure for the variable t? Even when I run my app, and debug the Run function, it seems to create a hidden class. Why does it do this, even though the Action isn't accessing any variables in the outer scope?
29 replies
CC#
Created by br4kejet on 10/6/2023 in #help
❔ A Dictionary<Type, List<T>> that bakes the list for the type hierarchy (for fast Get calls)
Does C# have an object that does this? When you try to Get/TryGet from the map, it will check if the given type exists in the internal map, and if so, it just returns the list that it maps to. However if it doesn't, it keeps scanning the BaseType until it finds a valid entry, and then it adds each of those types (that weren't in the map). But it also combines the values of each BaseType's list Say I had an instance of it as ClassDictionary<string>, i could map do:
class ObjectA {}
class ObjectB : ObjectA {}
class ObjectC : ObjectB {}
dict.AddRange(typeof(ObjectA), "str1", "str2", "str3");
dict.AddRange(typeof(ObjectB), "str4", "str5", "str6");
class ObjectA {}
class ObjectB : ObjectA {}
class ObjectC : ObjectB {}
dict.AddRange(typeof(ObjectA), "str1", "str2", "str3");
dict.AddRange(typeof(ObjectB), "str4", "str5", "str6");
And then if I do dict.Get(typeof(ObjectC)), it would return a baked list containing "str1", "str2", "str3", "str4", "str5" and "str6" I could just use a for loop using the key's type, and then accumulate all of the values of each type found, into a new list, and then return that list. But that would be quite slow, especially if the Get method is being called many times a second, and there's a lot of entries and values in each list, hence why this class would bake all of it so that it would eventually be O1 just like a normal dictionary
6 replies
CC#
Created by br4kejet on 10/5/2023 in #help
Can you await a Task and return Task<bool> (with a constant bool value) without the `await` keyword?
I came up with this code which does what I want:
Task myTask = ...
return myTask.ContinueWith(t => true);
Task myTask = ...
return myTask.ContinueWith(t => true);
but the problem is that the t => true part ends up being executed on a worker thread, even if myTask is completed (e.g. status is RanToCompletion). Is there a proper way to do this without checking if myTask is completed?
30 replies
CC#
Created by br4kejet on 9/20/2023 in #help
❔ Accessing the 'current' window from anywhere in the App
My program has multiple windows that can be opened, and each of them have their own notification manager (a view model) Now say for instance some of the windows run a background task every n seconds to perform some operation that could fail (e.g. read from a file). If that operation fails, I want to notify the users that something bad happened. I could use dialogs (so that I don't really need a parent window), but I really want to use that windows' notification manager. But I don't know how I would access that notification manager from anywhere in the code, because some of the functions are very 'generic', like TryReadFile. I could pass the notification manager to each function (that automatically handles errors), but that doesn't feel like good design... Anyone have any ideas?
10 replies
CC#
Created by br4kejet on 8/26/2023 in #help
❔ Invoking internal methods without reflection?
I'm trying to enable virtualization for a custom TreeView type in WPF, but it requires that I invoke a bunch of methods and access fields that are all internal, such as UncommonField. Is there an easier way to invoke this stuff without using reflection? Having to manually write out all the type names is gonna take forever 😦
6 replies
CC#
Created by br4kejet on 8/24/2023 in #help
❔ Hierarchical data types and inheritance
I have a small file browser app, and I use view models to store the files (lazily loading child files when my view models' IsExpanded property is modified by the view). But I'm struggling to find a way to avoid repeating the same code for the same type of files (as in, file extension like .zip) when those files are placed in special folder view models. I have BaseTreeItem which is the base view model for all tree items. Then, BasePhysicalTreeItem (contains a File Path) which PhsyicalTreeFile and PhsyicalTreeFolder (which stores child BaseTreeItems) both extend. But then I could have special files, like ZipTreeFile or MyCustomCompressionTreeFile or TextDocumentTreeFile. ZipTreeFile would contain a collection of children (similar to PhysicalTreeFolder), but they would be of type BaseZipEntryViewModel (which extends BaseTreeItem) so that it can store a reference to the owning Zip file and other stuff to. And now the problem is that, I have to have 2 different types of TextDocumentTreeFile, one for a physical file, and one for a zipped file:
class PhysicalTextDocumentTreeFile : PhsyicalTreeFile {}
class ZippedTextDocumentTreeFile : BaseZipEntryViewModel {}
class PhysicalTextDocumentTreeFile : PhsyicalTreeFile {}
class ZippedTextDocumentTreeFile : BaseZipEntryViewModel {}
and there's no way to have some common base class for text documents, meaning I have to repeat the same code for both of those types. How can I get around this?
8 replies
CC#
Created by br4kejet on 8/23/2023 in #help
❔ Unsafe Reading different types of structs from a byte array
I'm currently using the Unsafe class to help me read (and also write) different types of structs into a byte array. This is my read function so far:
public static unsafe T ReadStruct<T>(byte[] array, int offset, int size) where T : unmanaged {
T value = default;
Unsafe.CopyBlock(ref *(byte*) &value, ref array[offset], (uint) size);
return value;
}
public static unsafe T ReadStruct<T>(byte[] array, int offset, int size) where T : unmanaged {
T value = default;
Unsafe.CopyBlock(ref *(byte*) &value, ref array[offset], (uint) size);
return value;
}
It works for me, even if the byte array contains something like 3 ints, a byte, and a long after than (21 byte elements). But I've also read about possible alignment issues which I'm not very familiar with... will my code run into problems at some point?
94 replies
CC#
Created by br4kejet on 8/10/2023 in #help
❔ Executing a method every n seconds but only during certain conditions
What would be the best way to do this? The easiest way I can think of would be:
Task.Run(MainAsync);
...
public async Task MainAsync()
{
while (true)
{
if (SomeCondition)
{
// do stuff
SomeCondition = false;
}

await Task.Delay(1000);
}
}
Task.Run(MainAsync);
...
public async Task MainAsync()
{
while (true)
{
if (SomeCondition)
{
// do stuff
SomeCondition = false;
}

await Task.Delay(1000);
}
}
But this feels like it might be wasteful, especially if I end up having 100s of these tasks running. Is there a better way to do this?
95 replies