Skip to content

Commit

Permalink
Convert to use nullable datatypes in project
Browse files Browse the repository at this point in the history
  • Loading branch information
jdahlblom committed Mar 5, 2024
1 parent f1d4408 commit e404ac5
Show file tree
Hide file tree
Showing 19 changed files with 227 additions and 127 deletions.
11 changes: 9 additions & 2 deletions src/client/DCSInsight/Communication/TCPClientHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ internal class TCPClientHandler : IDisposable, ICommandListener
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly Channel<DCSAPI> _asyncCommandsChannel = Channel.CreateUnbounded<DCSAPI>();
private TcpClient _tcpClient;
private Thread _clientThread;
private TcpClient? _tcpClient;
private Thread? _clientThread;
private bool _isRunning;
private readonly string _host;
private readonly string _port;
Expand Down Expand Up @@ -50,6 +50,8 @@ public void Dispose()

private async void ClientThread()
{
if (_tcpClient == null) return;

ICEventHandler.SendConnectionStatus(_isRunning);
_responseReceived = true;
while (_isRunning)
Expand Down Expand Up @@ -83,6 +85,7 @@ private async void ClientThread()
_metaDataPollCounter++;
_tcpClient.GetStream().Write(Encoding.ASCII.GetBytes("SENDAPI\n"));
Thread.Sleep(1000);
_requestAPIList = false;
}

if (_asyncCommandsChannel.Reader.Count > 0 && _responseReceived)
Expand Down Expand Up @@ -128,6 +131,8 @@ private void HandleMessage(string str)
if (str.Contains("\"returns_data\":") && str.EndsWith("}")) // regex?
{
var dcsApi = JsonConvert.DeserializeObject<DCSAPI>(_currentMessage + str);
if (dcsApi == null) return;

_currentMessage = "";
ICEventHandler.SendData(dcsApi);
_responseReceived = true;
Expand All @@ -148,6 +153,8 @@ private void HandleAPIMessage(string str)
try
{
var dcsAPIList = JsonConvert.DeserializeObject<List<DCSAPI>>(str);
if (dcsAPIList == null) return;

ICEventHandler.SendData(dcsAPIList);
_responseReceived = true;
_apiListReceived = true;
Expand Down
8 changes: 4 additions & 4 deletions src/client/DCSInsight/CustomControls/TextBlockSelectable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ namespace ControlReference.CustomControls
{
internal class TextBlockSelectable : TextBlock
{
TextPointer _startSelectPosition;
TextPointer _endSelectPosition;
private TextPointer? _startSelectPosition;
private TextPointer? _endSelectPosition;
public string SelectedText = "";

public delegate void TextSelectedHandler(string selectedText);
public event TextSelectedHandler TextSelected;
private TextRange _selectedTextRange;
public event TextSelectedHandler? TextSelected;
private TextRange? _selectedTextRange;

public static Color SelectedBackgroundColor { get; set; } = Color.FromRgb(187, 191, 189);
public static Color TextBackgroundColor { get; set; } = Colors.WhiteSmoke;
Expand Down
2 changes: 1 addition & 1 deletion src/client/DCSInsight/DCSInsight.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>disable</Nullable>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
<!-- for WinForms -->
Expand Down
31 changes: 23 additions & 8 deletions src/client/DCSInsight/Events/EventArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,42 @@ namespace DCSInsight.Events
{
public class SendCommandEventArgs : EventArgs
{
public object Sender { get; set; }
public DCSAPI APIObject { get; set; }
public SendCommandEventArgs(DCSAPI apiObject)
{
APIObject = apiObject;
}

public DCSAPI APIObject { get; }
}

public class ErrorEventArgs : EventArgs
{
public object Sender { get; set; }
public string Message { get; set; }
public ErrorEventArgs(string message, Exception ex)
{
Message = message;
Ex = ex;
}

public string Message { get; }

public Exception Ex { get; set; }
public Exception Ex { get; }
}

public class ConnectionEventArgs : EventArgs
{
public bool IsConnected { get; set; }
public bool IsConnected { get; init; }
}

public class DataEventArgs : EventArgs
{
public DCSAPI DCSApi { get; set; }
public DataEventArgs(DCSAPI? dcsApi, List<DCSAPI>? dcsapis)
{
DCSApi = dcsApi;
DCSAPIS = dcsapis;
}

public DCSAPI? DCSApi { get; }

public List<DCSAPI> DCSAPIS { get; set; }
public List<DCSAPI>? DCSAPIS { get; }
}
}
19 changes: 10 additions & 9 deletions src/client/DCSInsight/Events/ICEventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace DCSInsight.Events
internal static class ICEventHandler
{
public delegate void SendCommandEventHandler(SendCommandEventArgs e);
public static event SendCommandEventHandler OnSendCommand;
public static event SendCommandEventHandler? OnSendCommand;

public static void AttachCommandListener(ICommandListener listener)
{
Expand All @@ -24,15 +24,16 @@ public static void DetachCommandListener(ICommandListener listener)
public static void SendCommand(DCSAPI api)
{
// remove earlier result, no need to send that to server
var command = api.CloneJson();
var command = api.CloneJson() ?? throw new Exception("Failed to clone DCSAPI");

command.Result = "";
OnSendCommand?.Invoke(new SendCommandEventArgs {APIObject = command});
OnSendCommand?.Invoke(new SendCommandEventArgs(command));
}
/*
*
*/
public delegate void ErrorEventHandler(ErrorEventArgs e);
public static event ErrorEventHandler OnError;
public static event ErrorEventHandler? OnError;

public static void AttachErrorListener(IErrorListener listener)
{
Expand All @@ -46,13 +47,13 @@ public static void DetachErrorListener(IErrorListener listener)

public static void SendErrorMessage(string message, Exception ex)
{
OnError?.Invoke(new ErrorEventArgs { Message = message, Ex = ex});
OnError?.Invoke(new ErrorEventArgs (message, ex));
}
/*
*
*/
public delegate void ConnectionStatusEventHandler(ConnectionEventArgs e);
public static event ConnectionStatusEventHandler OnConnection;
public static event ConnectionStatusEventHandler? OnConnection;

public static void AttachConnectionListener(IConnectionListener listener)
{
Expand All @@ -72,7 +73,7 @@ public static void SendConnectionStatus(bool isConnected)
*
*/
public delegate void DataEventHandler(DataEventArgs e);
public static event DataEventHandler OnData;
public static event DataEventHandler? OnData;

public static void AttachDataListener(IDataListener listener)
{
Expand All @@ -86,11 +87,11 @@ public static void DetachDataListener(IDataListener listener)

public static void SendData(List<DCSAPI> dcsAPIs)
{
OnData?.Invoke(new DataEventArgs { DCSAPIS = dcsAPIs });
OnData?.Invoke(new DataEventArgs(null, dcsAPIs ));
}
public static void SendData(DCSAPI dcsAPI)
{
OnData?.Invoke(new DataEventArgs { DCSApi = dcsAPI });
OnData?.Invoke(new DataEventArgs (dcsAPI, null));
}
}
}
40 changes: 36 additions & 4 deletions src/client/DCSInsight/JSON/DCSAPI.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;

namespace DCSInsight.JSON
{
[Serializable]
public class DCSAPI
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
[JsonConstructor]
public DCSAPI(int id,
bool returns_data,
string api_syntax,
int parameter_count,
List<ParameterInfo> parameter_defs,
bool error_thrown,
string? error_message,
string? result,
string? result_type)
{
Id = id;
ReturnsData = returns_data;
Syntax = api_syntax;
ParamCount = parameter_count;
Parameters = parameter_defs;
ErrorThrown = error_thrown;
ErrorMessage = error_message;
Result = result;
ResultType = result_type;
}

/// <summary>
/// This is a base class for the DCS-BIOS Control as specified in lua / JSON.
/// This class is used when reading the JSON.
Expand All @@ -32,13 +56,13 @@ public class DCSAPI
public bool ErrorThrown { get; set; }

[JsonProperty("error_message", Required = Required.Default)]
public string ErrorMessage { get; set; }
public string? ErrorMessage { get; set; }

[JsonProperty("result", Required = Required.Default)]
public string Result { get; set; }
public string? Result { get; set; }

[JsonProperty("result_type", Required = Required.Default)]
public string ResultType { get; set; }
public string? ResultType { get; set; }
}


Expand All @@ -59,14 +83,22 @@ public enum ParamNameEnum

public class ParameterInfo
{
public ParameterInfo(int id, string parameterName, string? value, ParameterTypeEnum type)
{
Id = id;
ParameterName = parameterName;
Value = value;
Type = type;
}

[JsonProperty("id", Required = Required.Default)]
public int Id { get; set; }

[JsonProperty("name", Required = Required.Default)]
public string ParameterName { get; set; }

[JsonProperty("value", Required = Required.Default)]
public string Value { get; set; }
public string? Value { get; set; }

[JsonProperty("type", Required = Required.Default)]
public ParameterTypeEnum Type { get; set; }
Expand Down
9 changes: 5 additions & 4 deletions src/client/DCSInsight/Lua/LuaAssistant.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ internal static class LuaAssistant
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly object LockObject = new();
private static string _dcsbiosAircraftLuaLocation;
private static string _dcsbiosModuleLuaFilePath;
private static string? _dcsbiosAircraftLuaLocation;
private static string? _dcsbiosModuleLuaFilePath;
private static readonly List<KeyValuePair<string, string>> LuaControls = new();
private static readonly List<string> LuaModuleSignatures = new();
private static string _aircraftId = "";
private const string DCSBIOS_LUA_NOT_FOUND_ERROR_MESSAGE = "Error loading DCS-BIOS lua.";
private const string DCSBIOSLuaNotFoundErrorMessage = "Error loading DCS-BIOS lua.";

internal static List<KeyValuePair<string, string>> GetLuaControls(string aircraftId)
{
Expand Down Expand Up @@ -168,12 +168,13 @@ private static void ReadLuaCommandsFromFile(string aircraftId)
}
catch (Exception ex)
{
throw new Exception($"{DCSBIOS_LUA_NOT_FOUND_ERROR_MESSAGE} ==>[{_dcsbiosAircraftLuaLocation}]<=={Environment.NewLine}{ex.Message}{Environment.NewLine}{ex.StackTrace}");
throw new Exception($"{DCSBIOSLuaNotFoundErrorMessage} ==>[{_dcsbiosAircraftLuaLocation}]<=={Environment.NewLine}{ex.Message}{Environment.NewLine}{ex.StackTrace}");
}
}

internal static List<string> GetModuleFunctionSignatures()
{
if (string.IsNullOrEmpty(_dcsbiosModuleLuaFilePath)) return new List<string>();
if (LuaModuleSignatures.Count > 0) return LuaModuleSignatures;

LuaModuleSignatures.Clear();
Expand Down
16 changes: 8 additions & 8 deletions src/client/DCSInsight/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ public partial class MainWindow : Window, IErrorListener, IConnectionListener, I
private List<DCSAPI> _dcsAPIList = new();
private readonly List<UserControlAPIBase> _loadedAPIUserControls = new();
private bool _formLoaded;
private TCPClientHandler _tcpClientHandler;
private TCPClientHandler? _tcpClientHandler;
private bool _isConnected;
private bool _rangeTesting;
private LuaWindow _luaWindow;
private LuaWindow? _luaWindow;

public MainWindow()
{
Expand Down Expand Up @@ -155,13 +155,13 @@ public void ConnectionStatus(ConnectionEventArgs args)
_isConnected = args.IsConnected;
if (!_isConnected)
{
Dispatcher?.BeginInvoke((Action)(Disconnect));
Dispatcher?.BeginInvoke((Action)(SetFormState));
Dispatcher?.BeginInvoke((Action)Disconnect);
Dispatcher?.BeginInvoke((Action)SetFormState);
return;
}

Dispatcher?.BeginInvoke((Action)(() => SetConnectionStatus(args.IsConnected)));
Dispatcher?.BeginInvoke((Action)(SetFormState)); ;
Dispatcher?.BeginInvoke((Action)SetFormState); ;
}
catch (Exception ex)
{
Expand Down Expand Up @@ -225,7 +225,7 @@ private void HandleMessage(DCSAPI dcsApi)
}
}

Dispatcher?.BeginInvoke((Action)(SetFormState));
Dispatcher?.BeginInvoke((Action)SetFormState);
}
catch (Exception ex)
{
Expand All @@ -240,7 +240,7 @@ private void HandleAPIMessage(List<DCSAPI> dcsApis)
_dcsAPIList = dcsApis;
//Debug.WriteLine("Count is " + _dcsAPIList.Count);
Dispatcher?.BeginInvoke((Action)(() => ShowAPIs()));
Dispatcher?.BeginInvoke((Action)(SetFormState));
Dispatcher?.BeginInvoke((Action)SetFormState);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -317,7 +317,7 @@ private static string GetLogFilePathByTarget(string targetName)
Target target = LogManager.Configuration.FindTargetByName(targetName);
if (target != null)
{
FileTarget fileTarget;
FileTarget? fileTarget;

// Unwrap the target if necessary.
if (target is not WrapperTargetBase wrapperTarget)
Expand Down
Loading

0 comments on commit e404ac5

Please sign in to comment.