feat: Algorithm Config agile JSON Setting v2/v3

master
Tongg 3 months ago
parent 1810207d79
commit 1a07ec4997
  1. 105
      Model/Entity/AgileJsonConfigEntity.cs
  2. 13
      Model/Extension/CommonExtension.cs
  3. BIN
      SparkDB.db
  4. 225
      ViewModel/Configuration/AlgorithmConfigVM.cs
  5. 54
      Views/Configuration/AlgorithmConfigPage.xaml
  6. 30
      Views/Configuration/AlgorithmConfigPage.xaml.cs

@ -6,34 +6,34 @@ namespace SparkClient.Model.Entity;
public class AgileJsonConfigEntity
{
private readonly AlgorithmConfigVM _vm;
private readonly List<string> _keys;
public AgileJsonConfigEntity(AlgorithmConfigVM vm, List<string> keys)
public readonly List<string> Keys;
public AgileJsonConfigEntity(List<string> keys)
{
_vm = vm;
_mode = 0;
Shape = "圆形";
Spec = _vm.GetSpecOptions(_mode).FirstOrDefault();
_keys = keys;
Keys = keys;
JsonKeys = keys;
ModeList = GetRunModelList();
SpceList = GetRunSpecList();
_mode = ModeList.FirstOrDefault();
_spec = SpceList.FirstOrDefault();
}
private int _mode;
public int Mode
private Param _mode;
public Param Mode
{
get => _mode;
set
{
if (_mode == value) return;
_mode = value;
OnPropertyChanged();
// 自动更新规格
Spec = _vm.GetSpecOptions(value).FirstOrDefault();
OnPropertyChanged(nameof(Mode));
}
}
private string _spec;
public string Spec
private Param _spec;
public Param Spec
{
get => _spec;
set => SetField(ref _spec, value);
@ -43,7 +43,7 @@ public class AgileJsonConfigEntity
public string Shape
{
get => _shape;
private set => SetField(ref _shape, value);
set => SetField(ref _shape, value);
}
@ -54,7 +54,6 @@ public class AgileJsonConfigEntity
set
{
SetField(ref _jsonKey, value);
FilterItems(value);
}
}
@ -73,15 +72,21 @@ public class AgileJsonConfigEntity
set => SetField(ref _jsonKeys, value);
}
private string GetDefaultSpec(int mode)
private List<Param> _modeList;
public List<Param> ModeList
{
return mode switch
{
0 => "p8-p8",
1 => "p8-p8-s1",
_ => null
};
get => _modeList;
set => SetField(ref _modeList, value);
}
private List<Param> _specList;
public List<Param> SpceList
{
get => _specList;
set => SetField(ref _specList, value);
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
@ -96,17 +101,57 @@ public class AgileJsonConfigEntity
OnPropertyChanged(name);
return true;
}
private void FilterItems(string key)
public List<Param> GetRunModelList()
{
JsonKeys.Clear();
return new List<Param>
{
new Param()
{
Value = "0",
Name = "实验室模式"
},
new Param()
{
Value = "1",
Name = "工厂模式"
}
};
}
foreach (var data in _keys)
public List<Param> GetRunSpecList()
{
return new List<Param>
{
if (data.ToLower().Contains(key.ToLower()))
new Param()
{
Value = "P8-P8",
Name = "P8-P8"
},
new Param()
{
Value = "P8-P8-S1",
Name = "P8-P8-S1"
},
new Param()
{
JsonKeys.Add(data);
Value = "P8-P8-S2",
Name = "P8-P8-S2"
},
new Param()
{
Value = "P8-P8-S3",
Name = "P8-P8-S3"
},
new Param()
{
Value = "P8-P8-S4",
Name = "P8-P8-S4"
}
}
};
}
}
public class Param
{
public string Value { get; set; }
public string Name { get; set; }
}

@ -17,4 +17,17 @@ public static class CommonExtension
{
return String.IsNullOrEmpty(str);
}
public static string toMD5Code(this object obj)
{
if (null == obj)
{
return Helper.Common.GenerateMd5Hash(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff"));
}
else
{
var str = $"{DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff")}-{obj.GetHashCode()}-{Helper.Common.AesKey}";
return Helper.Common.GenerateMd5Hash(str);
}
}
}

Binary file not shown.

@ -13,6 +13,7 @@ using SparkClient.Model.Helper;
using SparkClient.ViewModel.Configuration.SettingsPages;
using MessageBox = SparkClient.Views.Dialog.MessageBox;
using SparkClient.Model.Attributes;
using SparkClient.Model.Extension;
namespace SparkClient.ViewModel.Configuration;
@ -23,11 +24,19 @@ public class AlgorithmConfigVM : BaseViewModel
public ICommand BeautifyJsonCommand { get; }
public ICommand UglifyJsonCommand { get; }
public List<AgileJsonConfigEntity> AgileJsonConfigEntities { get; set; }
private ObservableCollection<AgileJsonConfigEntity> _agileJsonConfigEntities;
public ObservableCollection<AgileJsonConfigEntity> AgileJsonConfigEntities
{
get => _agileJsonConfigEntities;
set
{
_agileJsonConfigEntities = value;
OnPropertyChanged(nameof(AgileJsonConfigEntities));
}
}
public List<string> JsonKeysBak = new List<string>();
public List<Param> ModeList { get; set; }
public List<string> _jsonKeysBak;
private bool _isEnabled;
public bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; OnPropertyChanged(nameof(IsEnabled)); } }
@ -41,16 +50,93 @@ public class AlgorithmConfigVM : BaseViewModel
UglifyJsonCommand = new RelayCommand(UglifyJson);
InitAlgorithmData(null);
IsEnabledByRole();
JsonKeysBak = GetNestedKeys(JObject.Parse(AlgorithmConfigJson));
ModeList = GetRunModelList();
AgileJsonConfigEntities = new List<AgileJsonConfigEntity>();
AgileJsonConfigEntities.Add(new AgileJsonConfigEntity(this, JsonKeysBak) {
Mode = 0,
Spec = "p8-p8",
_jsonKeysBak = GetNestedKeys(JObject.Parse(AlgorithmConfigJson));
InitAgileJsonConfig();
});
}
private void InitAgileJsonConfig()
{
AgileJsonConfigEntities = new ObservableCollection<AgileJsonConfigEntity>();
string sql = @"SELECT Mode, Shape, Spec, JsonKey, Value FROM AGILE_ALGORITHM_CONFIG";
DataTable dataTable = DataBaseHelper.ExecuteQuery(sql);
var baseData = new AgileJsonConfigEntity(_jsonKeysBak);
if (dataTable != null && dataTable.Rows.Count >= 0)
{
foreach (DataRow row in dataTable.Rows)
{
try
{
AgileJsonConfigEntities.Add(new AgileJsonConfigEntity(_jsonKeysBak)
{
Mode = baseData.ModeList.Find(e => e.Value.Equals(row["Mode"].ToSafeString())),
Spec = baseData.SpceList.Find(e => e.Value.Equals(row["Spec"].ToSafeString())),
Shape = row["Shape"].ToSafeString(),
JsonKey = row["JsonKey"].ToSafeString(),
Value = row["Value"].ToSafeString()
});
} catch { }
}
}
}
private bool CheckAndSaveAgileJson()
{
var finalSaveData = new ObservableCollection<AgileJsonConfigEntity>();
var insertSql = new List<string>();
foreach (var row in AgileJsonConfigEntities)
{
if (string.IsNullOrWhiteSpace(row.JsonKey) || string.IsNullOrWhiteSpace(row.Value) ||
string.IsNullOrWhiteSpace(row.Shape))
continue;
if (row.Mode == null || row.Spec == null)
continue;
insertSql.Add($"INSERT INTO AGILE_ALGORITHM_CONFIG (GUID, Mode, Spec, Shape, JsonKey, Value)" +
$@"VALUES ('{row.toMD5Code()}',{row.Mode.Value},'{row.Spec.Value}','{row.Shape}','{row.JsonKey}','{row.Value}');");
finalSaveData.Add(row);
}
AgileJsonConfigEntities = finalSaveData;
var deleteSql = $"DELETE FROM AGILE_ALGORITHM_CONFIG;";
try
{
DataBaseHelper.BeginTransaction();
DataBaseHelper.ExecuteNonQuery(deleteSql);
insertSql.ForEach(e => DataBaseHelper.ExecuteNonQuery(e));
DataBaseHelper.commit();
}
catch (Exception e)
{
Logger.Error($"灵活配置存储异常:{e.Message}\r\n {e.StackTrace}");
new MessageBox().Show($"灵活配置存储异常:{e.Message}");
DataBaseHelper.rollback();
return false;
}
return true;
}
public string GetAlgorithmConfig(string param)
{
string sql = @"SELECT Mode, Shape, Spec, JsonKey, Value FROM AGILE_ALGORITHM_CONFIG";
DataTable dataTable = DataBaseHelper.ExecuteQuery(sql);
if (dataTable != null && dataTable.Rows.Count >= 0)
{
var jsonAlgorithm = JToken.Parse(_AlgorithmConfigJson);
foreach (DataRow row in dataTable.Rows)
{
//只对当前运行环境有效
if (Common.RunMode == int.Parse(row["Mode"].ToSafeString()))
{
}
}
return jsonAlgorithm.ToString();
}
return _AlgorithmConfigJson;
}
/// <summary>
/// 初始化算法数据
@ -61,68 +147,20 @@ public class AlgorithmConfigVM : BaseViewModel
{
try
{
if (param == null)
AlgorithmConfigJson = "{}";
string sql = @"SELECT JSON as json FROM ALGORITHM_CONFIG ORDER BY JSON_ORDER";
DataTable dataTable = DataBaseHelper.ExecuteQuery(sql);
StringBuilder sb = new StringBuilder();
if (dataTable != null)
{
AlgorithmConfigJson = "{}";
string sql = @"SELECT JSON as json FROM ALGORITHM_CONFIG ORDER BY JSON_ORDER";
DataTable dataTable = DataBaseHelper.ExecuteQuery(sql);
StringBuilder sb = new StringBuilder();
if (dataTable != null)
foreach (DataRow row in dataTable.Rows)
{
foreach (DataRow row in dataTable.Rows)
{
sb.Append(row["json"].ToString());
}
}
if (sb.Length > 0)
{
AlgorithmConfigJson = JToken.Parse(sb.ToString()).ToString();
sb.Append(row["json"].ToString());
}
}
else
if (sb.Length > 0)
{
string[] types = param.ToString().Split(" ");
string filename = string.Empty;
if (types.Last().Equals("S4"))
{
filename = "p8p8s4.config";
}else if (types.Last().Equals("S3"))
{
filename = "p8p8s3.config";
}else if (types.Last().Equals("S2"))
{
filename = "p8p8s2.config";
}else if (types.Last().Equals("S1"))
{
filename = "p8p8s1.config";
}else
{
filename = "p8p8.config";
}
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SparkCore", "config",filename);
if (!File.Exists(filePath))
{
AlgorithmConfigJson = "{}";
string sql = @"SELECT JSON as json FROM ALGORITHM_CONFIG ORDER BY JSON_ORDER";
DataTable dataTable = DataBaseHelper.ExecuteQuery(sql);
StringBuilder sb = new StringBuilder();
if (dataTable != null)
{
foreach (DataRow row in dataTable.Rows)
{
sb.Append(row["json"].ToString());
}
}
if (sb.Length > 0)
{
AlgorithmConfigJson = JToken.Parse(sb.ToString()).ToString();
}
}
else
{
string content = File.ReadAllText(filePath);
AlgorithmConfigJson = JToken.Parse(content).ToString();
}
AlgorithmConfigJson = JToken.Parse(sb.ToString()).ToString();
}
}
catch (Exception ex)
@ -135,32 +173,10 @@ public class AlgorithmConfigVM : BaseViewModel
// 命令实现
public ICommand AddCommand => new RelayCommand((param) =>
{
AgileJsonConfigEntities.Add(new AgileJsonConfigEntity(this, JsonKeysBak)
{
Mode = 0,
Spec = "p8-p8",
});
AgileJsonConfigEntities.Add(new AgileJsonConfigEntity(_jsonKeysBak));
});
private static readonly Dictionary<int, List<string>> SpecOptions = new()
{
[0] = new List<string> { "p8-p8" },
[1] = new List<string> {
"p8-p8", "p8-p8-s1", "p8-p8-s2",
"p8-p8-s3", "p8-p8-s4"
}
};
public List<string> GetSpecOptions(int mode)
{
return SpecOptions.TryGetValue(mode, out var options)
? options
: new List<string>();
}
private List<string> GetNestedKeys(JToken token, string prefix = "")
{
var keys = new List<string>();
@ -177,8 +193,6 @@ public class AlgorithmConfigVM : BaseViewModel
}
return keys;
}
/// <summary>
/// 保存数据
/// </summary>
@ -188,6 +202,11 @@ public class AlgorithmConfigVM : BaseViewModel
{
try
{
if (!CheckAndSaveAgileJson())
{
return;
}
DataBaseHelper.BeginTransaction();
string temp = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(AlgorithmConfigJson));
string deleteSql = @"DELETE FROM ALGORITHM_CONFIG";
@ -290,26 +309,6 @@ public class AlgorithmConfigVM : BaseViewModel
return AlgorithmConfigJson;
}
public List<Param> GetRunModelList()
{
return new List<Param>
{
new Param()
{
Value = "0",
Name = "实验室模式"
},
new Param()
{
Value = "1",
Name = "工厂模式"
}
};
}
}
public class Param
{
public string Value { get; set; }
public string Name { get; set; }
}

@ -88,8 +88,9 @@
<TextBlock Text="{ DynamicResource UglifyJson}" TextAlignment="Center" Foreground="#ffffff" FontSize="16"></TextBlock>
</Border>
</Button>
<Button Grid.Column="1" Width="100" Margin="10 5 0 5 " Padding="0" Height="50"
BorderThickness="0" Background="Transparent" FocusVisualStyle="{x:Null}" Command="{Binding UglifyJsonCommand}">
<!-- Command="{Binding UglifyJsonCommand}" -->
<Button Grid.Column="1" Width="100" Margin="10 5 0 5 " Padding="0" Height="50" x:Name="ButtonDelRow"
BorderThickness="0" Background="Transparent" FocusVisualStyle="{x:Null}" Click="ButtonDelRow_OnClick">
<Border HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="0 0 0 0"
@ -106,8 +107,9 @@
<TextBlock Text="删除行" TextAlignment="Center" Foreground="#ffffff" FontSize="16"></TextBlock>
</Border>
</Button>
<Button Grid.Column="2" Width="100" Margin="10 5 0 5 " Padding="0" Height="50"
BorderThickness="0" Background="Transparent" FocusVisualStyle="{x:Null}" Command="{Binding AddCommand}">
<!-- Command="{Binding AddCommand}" -->
<Button Grid.Column="2" Width="100" Margin="10 5 0 5 " Padding="0" Height="50" x:Name="ButtonAddRow" Command="{Binding AddCommand}"
BorderThickness="0" Background="Transparent" FocusVisualStyle="{x:Null}" Click="ButtonAddRow_OnClick" >
<Border HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="0 0 0 0"
@ -129,53 +131,51 @@
<Grid Grid.Row="1" Grid.Column="0" >
<DataGrid x:Name="AgileJsonDataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding AgileJsonConfigEntities,Mode=TwoWay}"
ItemsSource="{Binding AgileJsonConfigEntities}"
SelectionUnit="FullRow">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="运行模式" SelectedValueBinding="{Binding Mode}" Width="*"
ItemsSource="{Binding ModeList}"
DisplayMemberPath="Name"/>
<DataGridTemplateColumn Header="形状" Width="*">
<DataGridTemplateColumn Header="运行模式" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="圆形" />
<ComboBox ItemsSource="{Binding ModeList}"
SelectedValue="{Binding Mode.Value}"
DisplayMemberPath="Name"
SelectedIndex="1"
SelectedValuePath="Value"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="形状" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox IsEnabled="False"
SelectedItem="圆形"
ItemsSource="{Binding Source={StaticResource ShapeList}}" />
SelectedItem="圆形"
ItemsSource="{Binding Source={StaticResource ShapeList}}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- 规格列修正为模板列 -->
<DataGridTemplateColumn Header="规格" Width="2*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="p8-p8" />
<ComboBox ItemsSource="{Binding SpceList}"
SelectedValue="{Binding Spec.Value}"
DisplayMemberPath="Name"
SelectedIndex="1"
SelectedValuePath="Value"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox SelectedItem="{Binding Spec}">
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!-- JSON Key列(带自动完成) -->
<DataGridTemplateColumn Header="JSON Key" Width="3*" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding JsonKey}" />
<hc:AutoCompleteTextBox IsTextSearchEnabled="True" Text="{Binding JsonKey, Mode=TwoWay}"
ItemsSource="{Binding JsonKeys}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<hc:AutoCompleteTextBox Text="{Binding JsonKey}" ItemsSource="{Binding JsonKeys}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!-- 动态Value列 -->

@ -1,4 +1,5 @@
using System.IO;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
@ -7,6 +8,7 @@ using HandyControl.Controls;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
using SparkClient.Model.Entity;
using SparkClient.ViewModel.Configuration;
namespace SparkClient.Views.Configuration;
@ -51,4 +53,30 @@ public partial class AlgorithmConfigPage
vm.AlgorithmConfigJson = TextEditor.Text;
}
private void ButtonAddRow_OnClick(object sender, RoutedEventArgs e)
{
// List<string> jKeys = new List<string>();
// if (AgileJsonDataGrid.ItemsSource is List<AgileJsonConfigEntity> entities)
// {
// jKeys = entities.FirstOrDefault().JsonKeys;
// entities.Add(new AgileJsonConfigEntity(jKeys));
// AgileJsonDataGrid.ItemsSource = entities;
// }
}
private void ButtonDelRow_OnClick(object sender, RoutedEventArgs e)
{
if (AgileJsonDataGrid.ItemsSource is ObservableCollection<AgileJsonConfigEntity> entities)
{
if (AgileJsonDataGrid.SelectedItem is AgileJsonConfigEntity entity)
{
entities.Remove(entity);
}
AgileJsonDataGrid.ItemsSource = entities;
}
}
}

Loading…
Cancel
Save