Determinism
Determinism
CC#
Created by Determinism on 9/19/2023 in #help
❔ Is it possible to serialize this struct?
Hello, I want to serialize this struct to json:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct EndOfBarTelegram
{
public static readonly string Key = nameof(EndOfBarTelegram);

public uint MessageLength;
public uint MessageId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]
public string ProfileType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
public string ProfileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string BloomId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string TimeIn;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string TimeOut;
public float BarLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] Mean;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] Max;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] Min;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] DefectLength;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct EndOfBarTelegram
{
public static readonly string Key = nameof(EndOfBarTelegram);

public uint MessageLength;
public uint MessageId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]
public string ProfileType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
public string ProfileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string BloomId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string TimeIn;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string TimeOut;
public float BarLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] Mean;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] Max;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] Min;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public float[] DefectLength;
}
I'm have these methods:
public static ReadOnlyMemory<byte> SetTJson<T>(T obj)
{
string s = JsonSerializer.Serialize(obj);
return new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(s));
}

public static ReadOnlyMemory<byte> SetTJson<T>(T obj, JsonSerializerOptions jsonOptions)
{
string s = JsonSerializer.Serialize(obj, jsonOptions);
return new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(s));
}
public static ReadOnlyMemory<byte> SetTJson<T>(T obj)
{
string s = JsonSerializer.Serialize(obj);
return new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(s));
}

public static ReadOnlyMemory<byte> SetTJson<T>(T obj, JsonSerializerOptions jsonOptions)
{
string s = JsonSerializer.Serialize(obj, jsonOptions);
return new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(s));
}
Is it possible? At the moment it only returns 2 bytes (the curly braces). I'm assuming this has something to do with the marshalling because it works without it
12 replies
CC#
Created by Determinism on 1/18/2023 in #help
❔ Generic factory with dependency injection
Hello, I am trying to create a generic factory. However, I don't want to pass T as it creates much more boilerplate code:
internal static class MonitoredValueInstanceFactoryExtension
{
public static void AddMonitoredValueInstanceFactory<T>(this IServiceCollection services)
{
services.AddTransient<IMonitoredValue<T>, MonitoredValue<T>>();
services.AddTransient<Func<IMonitoredValue<T>>>(x => x.GetRequiredService<IMonitoredValue<T>>);
services.AddSingleton<IMonitoredValueInstanceFactory<T>, MonitoredValueInstanceFactory<T>>();
}
}

internal sealed class MonitoredValueInstanceFactory<T> : IMonitoredValueInstanceFactory<T>
{
private readonly Func<IMonitoredValue<T>> _factory;

public MonitoredValueInstanceFactory(Func<IMonitoredValue<T>> factory)
{
_factory = factory;
}

public IMonitoredValue<T> Create(string location, Subscription sub, ushort namespaceIndex = 2, bool callbackOnInitialize = true)
{
var factory = _factory();

MonitoredValue<T> mi = new(sub.DefaultItem)
{
DisplayName = location,
StartNodeId = new NodeId(location, namespaceIndex),
CallbackOnInitialize = callbackOnInitialize
};

sub.AddItem(mi);

return factory;
}
}

// Program.cs, how it currently needs to be called
services.AddMonitoredValueInstanceFactory<string>();
services.AddMonitoredValueInstanceFactory<float>();
services.AddMonitoredValueInstanceFactory<int>();
services.AddMonitoredValueInstanceFactory<short>();
services.AddMonitoredValueInstanceFactory<bool>();
services.AddMonitoredValueInstanceFactory<ushort>();


// I would prefer to call it like this with no type
services.AddMonitoredValueInstanceFactory();
internal static class MonitoredValueInstanceFactoryExtension
{
public static void AddMonitoredValueInstanceFactory<T>(this IServiceCollection services)
{
services.AddTransient<IMonitoredValue<T>, MonitoredValue<T>>();
services.AddTransient<Func<IMonitoredValue<T>>>(x => x.GetRequiredService<IMonitoredValue<T>>);
services.AddSingleton<IMonitoredValueInstanceFactory<T>, MonitoredValueInstanceFactory<T>>();
}
}

internal sealed class MonitoredValueInstanceFactory<T> : IMonitoredValueInstanceFactory<T>
{
private readonly Func<IMonitoredValue<T>> _factory;

public MonitoredValueInstanceFactory(Func<IMonitoredValue<T>> factory)
{
_factory = factory;
}

public IMonitoredValue<T> Create(string location, Subscription sub, ushort namespaceIndex = 2, bool callbackOnInitialize = true)
{
var factory = _factory();

MonitoredValue<T> mi = new(sub.DefaultItem)
{
DisplayName = location,
StartNodeId = new NodeId(location, namespaceIndex),
CallbackOnInitialize = callbackOnInitialize
};

sub.AddItem(mi);

return factory;
}
}

// Program.cs, how it currently needs to be called
services.AddMonitoredValueInstanceFactory<string>();
services.AddMonitoredValueInstanceFactory<float>();
services.AddMonitoredValueInstanceFactory<int>();
services.AddMonitoredValueInstanceFactory<short>();
services.AddMonitoredValueInstanceFactory<bool>();
services.AddMonitoredValueInstanceFactory<ushort>();


// I would prefer to call it like this with no type
services.AddMonitoredValueInstanceFactory();
Is this something that is possible?
6 replies
CC#
Created by Determinism on 1/17/2023 in #help
Avoiding 'new' in IOC
Hello, I am learning about dependency injection and one of the things said to avoid is using new in the constructor. How can I avoid doing stuff like this:
private readonly ILogger<DowntimeClient> _logger;
private readonly PipeAsync _pipeAsync;
private readonly Helper _helper;

private TcpClient _sendingClient;

private DowntimeClient(ILogger<DowntimeClient> logger, PipeAsync pipeAsync, Helper helper)
{
_logger = logger;
_pipeAsync = pipeAsync;
_helper = helper;
_sendingClient = new TcpClient();
}
private readonly ILogger<DowntimeClient> _logger;
private readonly PipeAsync _pipeAsync;
private readonly Helper _helper;

private TcpClient _sendingClient;

private DowntimeClient(ILogger<DowntimeClient> logger, PipeAsync pipeAsync, Helper helper)
{
_logger = logger;
_pipeAsync = pipeAsync;
_helper = helper;
_sendingClient = new TcpClient();
}
where I need _sendingClient throughout multiple methods in the class? Thanks!
151 replies
CC#
Created by Determinism on 11/18/2022 in #help
✅ Associating properties with field
Given fields:
public float ZoneShape01;
public float ZoneShape02;
public float ZoneShape03;
public float ZoneShape04;
public float ZoneShape05;
public float ZoneShape06;
public float ZoneShape07;
public float ZoneShape08;
public float ZoneShape09;
public float ZoneShape10;
public float ZoneShape01;
public float ZoneShape02;
public float ZoneShape03;
public float ZoneShape04;
public float ZoneShape05;
public float ZoneShape06;
public float ZoneShape07;
public float ZoneShape08;
public float ZoneShape09;
public float ZoneShape10;
I want to associate two bool properties with each of them. Is there an easier way to do this than just making a class? ie:
public class ZoneShape01 {
public bool IsA { get; set; }
public bool IsB { get; set; }
}
public class ZoneShape01 {
public bool IsA { get; set; }
public bool IsB { get; set; }
}
8 replies
CC#
Created by Determinism on 11/15/2022 in #help
❔ Refactoring a Tag class
I have a Tag class that has the ability to store information about tags. Each tag has several properties associated with it. For example:
{
"TagName": "Leveling",
"ValType": 2,
"isScanTag": true,
"isTag": true,
"TagType": 6,
"DBField": "Leveling",
"IsQualityTag": false
}
{
"TagName": "Leveling",
"ValType": 2,
"isScanTag": true,
"isTag": true,
"TagType": 6,
"DBField": "Leveling",
"IsQualityTag": false
}
I am trying to think of a more efficient way to handle this. At the moment, each tag is stored in a json file and then loaded on startup. Therefore, I am accessing each tag with a string, and getting each property based on this file.
public sealed class Tag
{
public string TagName { get; set; }
public ValEnum ValType { get; set; }
public bool IsScanTag { get; set; }
public bool IsTag { get; set; }
public TagTypeEnum TagType { get; set; }
public string DbField { get; set; }
public bool IsQualityTag { get; set; }

public Tag()
{
TagName = "";
IsScanTag = false;
IsTag = false;
TagType = TagTypeEnum.Na;
ValType = ValEnum.VInteger;
DbField = "";
IsQualityTag = false;
}

public enum ValEnum
{
VDouble,
VInteger,
VBoolean,
VLong,
VIntAsDouble,
VByte,
VUInteger
}

public enum TagTypeEnum
{
Na,
First,
Last,
Avg,
AvgBody,
Bit,
PercentageOn
}
}
public sealed class Tag
{
public string TagName { get; set; }
public ValEnum ValType { get; set; }
public bool IsScanTag { get; set; }
public bool IsTag { get; set; }
public TagTypeEnum TagType { get; set; }
public string DbField { get; set; }
public bool IsQualityTag { get; set; }

public Tag()
{
TagName = "";
IsScanTag = false;
IsTag = false;
TagType = TagTypeEnum.Na;
ValType = ValEnum.VInteger;
DbField = "";
IsQualityTag = false;
}

public enum ValEnum
{
VDouble,
VInteger,
VBoolean,
VLong,
VIntAsDouble,
VByte,
VUInteger
}

public enum TagTypeEnum
{
Na,
First,
Last,
Avg,
AvgBody,
Bit,
PercentageOn
}
}
It works, but I think it could be better. I'm running into issues of bringing stuff back into memory with this setup. Any suggestions are welcome, thanks.
33 replies
CC#
Created by Determinism on 11/7/2022 in #help
Protobuf deserialization not working after upgrade to .net 6
Hello, I am trying to deserialize a buffer (byte array) into a model. I upgraded my solution from core 3.1 to 6 and it no longer works. I am receiving the error
Error: ProtoBuf.ProtoException: Invalid wire-type (Varint); this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354
Error: ProtoBuf.ProtoException: Invalid wire-type (Varint); this usually means you have over-written a file without truncating or setting the length; see https://stackoverflow.com/q/2152978/23354
My code is :
public WeldSeamImageRun ConvertBuffer(byte[] buffer)
{
return DecodeProtoBuf<WeldSeamImageRun>(buffer);
}

private T DecodeProtoBuf<T>(byte[] buffer)
{
var trimmedBuffer = TrimEnd(buffer);

var stream = new MemoryStream(trimmedBuffer);

stream.Position = 0;

stream.SetLength(trimmedBuffer.Length);

var telegram = Serializer.DeserializeWithLengthPrefix<T>(stream, PrefixStyle.Base128, 1);

return telegram;
}

[ProtoContract]
public class WeldSeamImageRun
{
[ProtoMember(1)] public List<WeldSeamImage> Images { get; set; }
[ProtoMember(2)] public string EntryCoil { get; set; }
[ProtoMember(3)] public List<EntryCoilSection> Sections { get; set; }
}
public WeldSeamImageRun ConvertBuffer(byte[] buffer)
{
return DecodeProtoBuf<WeldSeamImageRun>(buffer);
}

private T DecodeProtoBuf<T>(byte[] buffer)
{
var trimmedBuffer = TrimEnd(buffer);

var stream = new MemoryStream(trimmedBuffer);

stream.Position = 0;

stream.SetLength(trimmedBuffer.Length);

var telegram = Serializer.DeserializeWithLengthPrefix<T>(stream, PrefixStyle.Base128, 1);

return telegram;
}

[ProtoContract]
public class WeldSeamImageRun
{
[ProtoMember(1)] public List<WeldSeamImage> Images { get; set; }
[ProtoMember(2)] public string EntryCoil { get; set; }
[ProtoMember(3)] public List<EntryCoilSection> Sections { get; set; }
}
Thanks for any help in advance.
30 replies
CC#
Created by Determinism on 9/15/2022 in #help
Converting ReadOnlySequence of bytes to object
I have to convert a ReadOnlySequence<byte> to an object, the way I'm doing it currently is like so:
public static DataModel ConvertBytes(ReadOnlySequence<byte> b)
{
var msg = new DataModel();

int location = 8;

msg.FFOn = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.FFSel = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.On = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.Sel = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.On = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.Sel = BitConverter.ToInt32(b, location) != 0; location += 4;

// ...

location += 76 * 4;

msg.ZoneShapeTarget01 = BitConverter.ToSingle(b, location); location += 4;
msg.ZoneShapeTarget02 = BitConverter.ToSingle(b, location); location += 4;
}
public static DataModel ConvertBytes(ReadOnlySequence<byte> b)
{
var msg = new DataModel();

int location = 8;

msg.FFOn = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.FFSel = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.On = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.Sel = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.On = BitConverter.ToInt32(b, location) != 0; location += 4;
msg.Sel = BitConverter.ToInt32(b, location) != 0; location += 4;

// ...

location += 76 * 4;

msg.ZoneShapeTarget01 = BitConverter.ToSingle(b, location); location += 4;
msg.ZoneShapeTarget02 = BitConverter.ToSingle(b, location); location += 4;
}
Is there a better way to handle this? BitConverter doesn't support ReadOnlySequence, so I would have to convert it to a byte array which is not ideal. I also have tons of properties on this model so it is a ton of code. Thanks in advance!
59 replies
CC#
Created by Determinism on 8/29/2022 in #help
Image switching on bool change [Answered]
Hello, I have an image in a Blazor Server app that changes as a boolean value changes. The image flip happens, but the image flickers before being rendered to the screen. This only happens sometimes, so I figure it has something to do with the rendering speed. I am rendering it like so:
<BSCol ColumnSmall="3" style="padding: 0; margin: 0;">
@if (isRT2 || isRT2HMD)
{
<BSImage Source="Images/rt2Bar_t.png" style="padding: 0; margin: 0; width: 101%;" alt="Table" />
}
else
{
<BSImage Source="Images/rt2_t.png" style="padding: 0; margin: 0; width: 101%;" alt="Table" />
}
</BSCol>
<BSCol ColumnSmall="3" style="padding: 0; margin: 0;">
@if (isRT2 || isRT2HMD)
{
<BSImage Source="Images/rt2Bar_t.png" style="padding: 0; margin: 0; width: 101%;" alt="Table" />
}
else
{
<BSImage Source="Images/rt2_t.png" style="padding: 0; margin: 0; width: 101%;" alt="Table" />
}
</BSCol>
TLDR: image flickering on bool value change in blazor
9 replies
CC#
Created by Determinism on 8/28/2022 in #help
TCP - The IO operation has been aborted because of either a thread exit or an application request
Hello, I am trying to implement a class that connects to a server through TCP, receives a message, opens a server, then sends a message through that server to all connected clients. This class seems to work, however, incrementally I will receive:
System.Net.Sockets.SocketException (995): The I/O operation has been aborted because of either a thread exit or an application request.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Net.Sockets.Socket>.GetResult(Int16 token)
at System.Net.Sockets.TcpListener.<AcceptTcpClientAsync>g__WaitAndWrap|31_0(ValueTask`1 task)
at ReversingMill1CommsService.Worker.ConnectAndSend() in Worker.cs:line 153
System.Net.Sockets.SocketException (995): The I/O operation has been aborted because of either a thread exit or an application request.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Net.Sockets.Socket>.GetResult(Int16 token)
at System.Net.Sockets.TcpListener.<AcceptTcpClientAsync>g__WaitAndWrap|31_0(ValueTask`1 task)
at ReversingMill1CommsService.Worker.ConnectAndSend() in Worker.cs:line 153
and then eventually:
System.InvalidOperationException: Not listening. You must call the Start() method before calling this method.
at ReversingMill1CommsService.Worker.ConnectAndSend() in Worker.cs:line 0
System.InvalidOperationException: Not listening. You must call the Start() method before calling this method.
at ReversingMill1CommsService.Worker.ConnectAndSend() in Worker.cs:line 0
https://hastebin.com/depiviqoci.csharp
4 replies
CC#
Created by Determinism on 8/15/2022 in #help
WriteAsync doesn't always send data to all connected clients
I am making an application that has a TCP client that listens for messages from a TCP server, then puts those messages in a queue, then sends all of the queued messages to the connected TCP clients of the server started. The application is working, but sometimes WriteAsync doesn't send the same amount of messages to all clients. Any ideas of what the issues is, and also what can I improve on in this code? https://hastebin.com/fejosepufi.csharp Thanks
18 replies