nathanAjacobs
nathanAjacobs
Explore posts from servers
CC#
Created by nathanAjacobs on 3/3/2025 in #help
Managed callback to native code (reverse p/invoke)
If I pass a managed callback to native code, do I need to pin the stored delegate so it does not get moved to a new memory address or is this handled by the runtime?
public class MyTestClass
{
private delegate void NativeTestCallback(int num);

[DllImport("TestNative")]
private static extern void NativeFunc(NativeTestCallback callback);

private NativeTestCallback _callback;
public MyTestClass()
{
// do I need to pin this?
_callback = TestCallback;
NativeFunc(_callback);
}

private void TestCallback(int num)
{

}
}
public class MyTestClass
{
private delegate void NativeTestCallback(int num);

[DllImport("TestNative")]
private static extern void NativeFunc(NativeTestCallback callback);

private NativeTestCallback _callback;
public MyTestClass()
{
// do I need to pin this?
_callback = TestCallback;
NativeFunc(_callback);
}

private void TestCallback(int num)
{

}
}
6 replies
CC#
Created by nathanAjacobs on 2/21/2025 in #help
Would this AsyncQueue have issues with multiple producers and a single consumer?
First, I know Channels exist and I would obviously use them instead. I can't use them because I'm adding functionality to an existing Unity library that does not have access to them. I'm intending to use this internally in the library for IPC purposes between Unity Editor instances. Will this implementation have issues with synchronization? Also will FIFO be preserved? I think the answer is there are no issues with this, but want to confirm.
internal class AsyncQueue<T>
{
private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);

public void Enqueue(T item)
{
_queue.Enqueue(item);
_semaphore.Release();
}

public async Task<T> DequeueAsync()
{
await _semaphore.WaitAsync().ConfigureAwait(false);
if (_queue.TryDequeue(out T item))
{
return item;
}

throw new InvalidOperationException("Something went wrong, there is nothing to dequeue.");
}
}
internal class AsyncQueue<T>
{
private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);

public void Enqueue(T item)
{
_queue.Enqueue(item);
_semaphore.Release();
}

public async Task<T> DequeueAsync()
{
await _semaphore.WaitAsync().ConfigureAwait(false);
if (_queue.TryDequeue(out T item))
{
return item;
}

throw new InvalidOperationException("Something went wrong, there is nothing to dequeue.");
}
}
18 replies
CC#
Created by nathanAjacobs on 2/10/2025 in #help
How can I reference multiple generics in summary?
This does not work. Is there a way to do this?
/// <summary>
/// </summary>
/// <returns>
/// A <see cref="Task{Handle{T}}"/>
/// </returns>
public async Task<Handle<T>> Foo()
{
}
/// <summary>
/// </summary>
/// <returns>
/// A <see cref="Task{Handle{T}}"/>
/// </returns>
public async Task<Handle<T>> Foo()
{
}
14 replies
CC#
Created by nathanAjacobs on 2/1/2025 in #help
Reccomended approach for sending messages from ASP.NET backend server to TypeScript web front-end?
^
10 replies
CC#
Created by nathanAjacobs on 1/27/2025 in #help
Prevent Visual Studio from adding NotImplementedException when generating method
Is it possible to configure Visual Studio to not add the throw new NotImplementedException(); line when generating methods via quick actions? I just want it to create an empty method.
13 replies
CC#
Created by nathanAjacobs on 1/8/2025 in #help
Declaring methods with `in` parameters
If a I'm writing a synchronous method, should I always declare read-only value types with the in keyword.
void Foo(in int i)
{

}
void Foo(in int i)
{

}
17 replies
AAE📼 Addie’s Analog Emporium 🌐
Created by nathanAjacobs on 12/24/2024 in #tech-help
Adobe Audition not saving "Monitor Input" for saved multitrack session
Every time I open my saved session, I have to enable the I monitor input button Does anyone know why this might be the case?
1 replies
CC#
Created by nathanAjacobs on 12/2/2024 in #help
WPF - Custom Control Help
See attached files, the template binding to FlyoutDirection is not working. I am getting this exception:
System.Windows.Markup.XamlParseException
HResult=0x80131501
Message='Set property 'System.Windows.Condition.Binding' threw an exception.' Line number '46' and line position '34'.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>

This exception was originally thrown at this call stack:
[External Code]

Inner Exception 1:
InvalidCastException: Unable to cast object of type 'System.Windows.TemplateBindingExpression' to type 'System.Windows.Data.BindingBase'.
System.Windows.Markup.XamlParseException
HResult=0x80131501
Message='Set property 'System.Windows.Condition.Binding' threw an exception.' Line number '46' and line position '34'.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>

This exception was originally thrown at this call stack:
[External Code]

Inner Exception 1:
InvalidCastException: Unable to cast object of type 'System.Windows.TemplateBindingExpression' to type 'System.Windows.Data.BindingBase'.
3 replies
CC#
Created by nathanAjacobs on 11/27/2024 in #help
CommunityToolkit.MVVM ObservableProperty and JsonIgnore
I have an observable property like so:
[ObservableProperty]
private string _online;
[ObservableProperty]
private string _online;
Is there any way to specify that the generated property be ignored for json serialization?
7 replies
CC#
Created by nathanAjacobs on 11/26/2024 in #help
WPF - DataGridCheckBoxColumn Issues
In WPF, how can I have a DataGridCheckBoxColumn that allows me to click the checkboxes without having to select the row first. It's weird that when I click the checkbox it selects the row rather than just clicking the checkbox I have this which seems to work, but it doesn't seem to update the value in the model when the checkbox is clicked. It only gets updated when I click the cell and click away. How can I fix it so that when I click the checkbox it updates the model?
<DataGridTemplateColumn Header="Enabled" MinWidth="100" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Enabled, Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Enabled" MinWidth="100" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Enabled, Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
5 replies
CC#
Created by nathanAjacobs on 11/4/2024 in #help
Deep copying data from class instances
Is there something that can generically and efficiently deep copy all of the data from one instance of a class into another already existing instance?
14 replies
CC#
Created by nathanAjacobs on 10/23/2024 in #help
Aspire and PgAdmin
No description
3 replies
CC#
Created by nathanAjacobs on 10/7/2024 in #help
✅ Can you run EF Core migration update at application startup rather than with the CLI tools?
^
8 replies
CC#
Created by nathanAjacobs on 10/6/2024 in #help
Is it necessary to setup validation constraints at the api level and database level?
I'm setting up a minimal api and just started to use FluentValidation. Should I also setup validation constraints at the database level as well?
6 replies
CC#
Created by nathanAjacobs on 9/2/2024 in #help
Worse performance with pointers?
No description
9 replies
CC#
Created by nathanAjacobs on 6/5/2024 in #help
NamedPipeClientStream.ReadAsync() continuously reads after the first message arrives
How come NamedPipeClientStream.ReadAsync continuously reads 0 bytes after the first message arrives? Basically is there a way to have it asynchronously wait until more data arrives after the first message?
5 replies
CC#
Created by nathanAjacobs on 5/6/2024 in #help
Can Memory<T> be created from a pointer?
Can Memory<T> be created with a pointer and a length? If not, how come?
15 replies
CC#
Created by nathanAjacobs on 2/27/2024 in #help
Help with LibraryImport and custom marshalling
What am I doing wrong here? I am getting a System.AccessViolationException when it tries to convert the first string (DeviceName) from unmanaged to managed.
[LibraryImport("user32.dll", EntryPoint = "EnumDisplayDevicesW", StringMarshalling = StringMarshalling.Utf16)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool EnumDisplayDevices(string? lpDevice, uint iDevNum, [MarshalUsing(typeof(DISPLAY_DEVICEMarshaller))] ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DISPLAY_DEVICE
{
[MarshalAs(UnmanagedType.U4)]
public uint cb;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string? DeviceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string? DeviceString;
[MarshalAs(UnmanagedType.U4)]
public DisplayDeviceStateFlags StateFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string? DeviceID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string? DeviceKey;

public static DISPLAY_DEVICE Create() => new DISPLAY_DEVICE { cb = (uint)Marshal.SizeOf<DISPLAY_DEVICE>() };
}

[Flags]
public enum DisplayDeviceStateFlags : uint
{
AttachedToDesktop = 0x1,
MultiDriver = 0x2,
PrimaryDevice = 0x4,
MirroringDriver = 0x8,
VGACompatible = 0x10,
Removable = 0x20,
ModesPruned = 0x8000000,
Remote = 0x4000000,
Disconnect = 0x2000000
}

[CustomMarshaller(typeof(DISPLAY_DEVICE), MarshalMode.ManagedToUnmanagedRef, typeof(DISPLAY_DEVICEMarshaller))]
public static unsafe class DISPLAY_DEVICEMarshaller
{
internal struct DISPLAY_DEVICE_Unmanaged
{
public uint cb;
public ushort* DeviceName;
public ushort* DeviceString;
public uint StateFlags;
public ushort* DeviceID;
public ushort* DeviceKey;
}

public static DISPLAY_DEVICE ConvertToManaged(DISPLAY_DEVICE_Unmanaged unmanaged)
{
return new DISPLAY_DEVICE
{
cb = unmanaged.cb,
DeviceName = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceName),
DeviceString = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceString),
StateFlags = (DisplayDeviceStateFlags)unmanaged.StateFlags,
DeviceID = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceID),
DeviceKey = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceKey)
};
}

public static DISPLAY_DEVICE_Unmanaged ConvertToUnmanaged(DISPLAY_DEVICE managed)
{
return new DISPLAY_DEVICE_Unmanaged
{
cb = managed.cb,
DeviceName = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceName),
DeviceString = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceString),
StateFlags = (uint)managed.StateFlags,
DeviceID = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceID),
DeviceKey = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceKey)
};
}

public static unsafe void Free(DISPLAY_DEVICE_Unmanaged unmanaged)
{
Utf16StringMarshaller.Free(unmanaged.DeviceName);
Utf16StringMarshaller.Free(unmanaged.DeviceString);
Utf16StringMarshaller.Free(unmanaged.DeviceID);
Utf16StringMarshaller.Free(unmanaged.DeviceKey);
}
}
[LibraryImport("user32.dll", EntryPoint = "EnumDisplayDevicesW", StringMarshalling = StringMarshalling.Utf16)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool EnumDisplayDevices(string? lpDevice, uint iDevNum, [MarshalUsing(typeof(DISPLAY_DEVICEMarshaller))] ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DISPLAY_DEVICE
{
[MarshalAs(UnmanagedType.U4)]
public uint cb;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string? DeviceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string? DeviceString;
[MarshalAs(UnmanagedType.U4)]
public DisplayDeviceStateFlags StateFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string? DeviceID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string? DeviceKey;

public static DISPLAY_DEVICE Create() => new DISPLAY_DEVICE { cb = (uint)Marshal.SizeOf<DISPLAY_DEVICE>() };
}

[Flags]
public enum DisplayDeviceStateFlags : uint
{
AttachedToDesktop = 0x1,
MultiDriver = 0x2,
PrimaryDevice = 0x4,
MirroringDriver = 0x8,
VGACompatible = 0x10,
Removable = 0x20,
ModesPruned = 0x8000000,
Remote = 0x4000000,
Disconnect = 0x2000000
}

[CustomMarshaller(typeof(DISPLAY_DEVICE), MarshalMode.ManagedToUnmanagedRef, typeof(DISPLAY_DEVICEMarshaller))]
public static unsafe class DISPLAY_DEVICEMarshaller
{
internal struct DISPLAY_DEVICE_Unmanaged
{
public uint cb;
public ushort* DeviceName;
public ushort* DeviceString;
public uint StateFlags;
public ushort* DeviceID;
public ushort* DeviceKey;
}

public static DISPLAY_DEVICE ConvertToManaged(DISPLAY_DEVICE_Unmanaged unmanaged)
{
return new DISPLAY_DEVICE
{
cb = unmanaged.cb,
DeviceName = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceName),
DeviceString = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceString),
StateFlags = (DisplayDeviceStateFlags)unmanaged.StateFlags,
DeviceID = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceID),
DeviceKey = Utf16StringMarshaller.ConvertToManaged(unmanaged.DeviceKey)
};
}

public static DISPLAY_DEVICE_Unmanaged ConvertToUnmanaged(DISPLAY_DEVICE managed)
{
return new DISPLAY_DEVICE_Unmanaged
{
cb = managed.cb,
DeviceName = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceName),
DeviceString = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceString),
StateFlags = (uint)managed.StateFlags,
DeviceID = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceID),
DeviceKey = Utf16StringMarshaller.ConvertToUnmanaged(managed.DeviceKey)
};
}

public static unsafe void Free(DISPLAY_DEVICE_Unmanaged unmanaged)
{
Utf16StringMarshaller.Free(unmanaged.DeviceName);
Utf16StringMarshaller.Free(unmanaged.DeviceString);
Utf16StringMarshaller.Free(unmanaged.DeviceID);
Utf16StringMarshaller.Free(unmanaged.DeviceKey);
}
}
Calling code:
public static DISPLAY_DEVICE GetPrimaryDisplay()
{
uint id = 0;
while (true)
{
DISPLAY_DEVICE d = DISPLAY_DEVICE.Create();

bool done = EnumDisplayDevices(null, id, ref d, 0);

if ((d.StateFlags & DisplayDeviceStateFlags.PrimaryDevice) == DisplayDeviceStateFlags.PrimaryDevice)
{
return d;
}

if (done)
break;

id++;
}

return default;
}
public static DISPLAY_DEVICE GetPrimaryDisplay()
{
uint id = 0;
while (true)
{
DISPLAY_DEVICE d = DISPLAY_DEVICE.Create();

bool done = EnumDisplayDevices(null, id, ref d, 0);

if ((d.StateFlags & DisplayDeviceStateFlags.PrimaryDevice) == DisplayDeviceStateFlags.PrimaryDevice)
{
return d;
}

if (done)
break;

id++;
}

return default;
}
15 replies
CC#
Created by nathanAjacobs on 2/7/2024 in #help
What exactly do these limitations mean for NativeAOT?
24 replies
CC#
Created by nathanAjacobs on 1/19/2024 in #help
Optional parameters with dependency injection
Is it possible to have an optional parameter for a constructor with dependency injection. I know that dependency injection usually it implies it is a required dependency, but for example if the only dependency is an ILogger, then I don't really care if one was registered or not. EDIT: Changed ILogger<Test> to be nullable
public class Test
{
private readonly ILogger<Test>? _logger;

public Test(ILogger<Test>? logger = null) // does this work?
{
_logger = logger
}

public void DoSomething()
{
_logger?.LogInformation("Doing something...");
}
}
public class Test
{
private readonly ILogger<Test>? _logger;

public Test(ILogger<Test>? logger = null) // does this work?
{
_logger = logger
}

public void DoSomething()
{
_logger?.LogInformation("Doing something...");
}
}
10 replies