refactor: 将Framework库和RT、UI放在同一个解决方案中。

This commit is contained in:
SL
2026-06-01 17:48:28 +08:00
parent 1948f4290d
commit b73d39a6b1
4331 changed files with 506148 additions and 49363 deletions
@@ -0,0 +1,264 @@
<UserControl
x:Class="MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory.DataView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converter="clr-namespace:MECF.Framework.UI.Client.Ctrlib.Converter"
xmlns:cv="clr-namespace:MECF.Framework.UI.Core.Converters;assembly=MECF.Framework.UI.Core"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:forms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:micro="clr-namespace:Caliburn.Micro"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:userControls="clr-namespace:MECF.Framework.UI.Client.CenterViews.Core.UserControls"
xmlns:userControls1="clr-namespace:Sicentury.Core.UserControls;assembly=Sicentury.Core"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:lex="http://wpflocalizeextension.codeplex.com"
d:DesignHeight="450"
d:DesignWidth="1500"
mc:Ignorable="d"
lex:LocalizeDictionary.DesignCulture="en"
lex:ResxLocalizationProvider.DefaultAssembly="Sicentury.Localization"
lex:ResxLocalizationProvider.DefaultDictionary="lang_common">
<UserControl.Resources>
<cv:BoolVisibilityConverter x:Key="BoolVisibilityConverter" />
<cv:BoolReverseConverter x:Key="BoolReverseConverter" />
<system:Boolean x:Key="True">True</system:Boolean>
<system:Boolean x:Key="False">False</system:Boolean>
</UserControl.Resources>
<Grid IsEnabled="{Binding IsPermission}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="200" />
</Grid.RowDefinitions>
<Grid Grid.RowSpan="2" Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="80" />
<RowDefinition Height="0" />
<RowDefinition Height="1" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border
Grid.Row="0"
Padding="5,1"
Background="{StaticResource Table_BG_Content}"
BorderBrush="{StaticResource Table_BD}"
BorderThickness="1,0,1,1"
IsEnabled="{Binding IsBusy, Converter={StaticResource BoolReverseConverter}}">
<StackPanel Orientation="Horizontal">
<StackPanel Width="260" Margin="0,15">
<StackPanel.Resources>
<Style TargetType="xctk:DateTimeUpDown">
<Setter Property="Width" Value="180" />
<Setter Property="Format" Value="Custom" />
<Setter Property="FormatString" Value="yyyy/MM/dd HH:mm:ss" />
</Style>
</StackPanel.Resources>
<StackPanel Orientation="Horizontal">
<TextBlock
Width="70"
VerticalAlignment="Center"
FontFamily="Arial"
FontSize="14"
Foreground="{StaticResource FG_Black}"
Text="{lex:Loc ID_TXT_StartTime}" />
<WindowsFormsHost
Width="170"
Height="22"
Margin="5,0,0,0"
VerticalAlignment="Center"
FontFamily="Arial"
FontSize="14">
<forms:DateTimePicker
x:Name="wfTimeFrom"
CustomFormat="yyyy/MM/dd HH:mm:ss"
Format="Custom"
Value="2011-8-1" />
</WindowsFormsHost>
</StackPanel>
<StackPanel Margin="0,5,0,0" Orientation="Horizontal">
<TextBlock
Width="70"
VerticalAlignment="Center"
FontFamily="Arial"
FontSize="14"
Foreground="{StaticResource FG_Black}"
Text="{lex:Loc ID_TXT_EndTime}" />
<WindowsFormsHost
Width="170"
Height="22"
Margin="5,0,0,0"
VerticalAlignment="Center"
FontFamily="Arial"
FontSize="14">
<forms:DateTimePicker
x:Name="wfTimeTo"
CustomFormat="yyyy/MM/dd HH:mm:ss"
Format="Custom"
Value="2011-8-1" />
</WindowsFormsHost>
</StackPanel>
</StackPanel>
<StackPanel>
<Button
Width="100"
Height="30"
Margin="0,5,5,0"
HorizontalAlignment="Right"
Content="{lex:Loc ID_BTN_Query_Content}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<micro:ActionMessage MethodName="Query">
<micro:ActionMessage.Parameters>
<micro:Parameter Value="{StaticResource False}" />
</micro:ActionMessage.Parameters>
</micro:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button
Width="100"
Height="30"
Margin="0,5,5,0"
HorizontalAlignment="Right"
Content="{lex:Loc ID_BTN_Append_Content}"
ToolTip="Append selected items to current chart">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<micro:ActionMessage MethodName="Query">
<micro:ActionMessage.Parameters>
<micro:Parameter Value="{StaticResource True}" />
</micro:ActionMessage.Parameters>
</micro:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
</StackPanel>
</Border>
<Border
Grid.Row="3"
Padding="5"
Background="{StaticResource Tab_BG}"
BorderBrush="{StaticResource Tab_BD}"
BorderThickness="1"
IsEnabled="{Binding IsBusy, Converter={StaticResource BoolReverseConverter}}"
SnapsToDevicePixels="True">
<userControls1:ParameterNodeTreeViewControl
x:Name="tvParameterNodes"
PresetGroupsFolderName="DataHistory"
TreeRoot="{Binding ParameterNodes}" />
</Border>
</Grid>
<GridSplitter
Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Width="5"
Margin="0,0,2,0"
HorizontalAlignment="Left"
VerticalAlignment="Stretch"
Background="LightBlue"
IsEnabled="{Binding IsBusy, Converter={StaticResource BoolReverseConverter}}" />
<userControls:DataViewDataGrid
x:Name="dataGrid"
Grid.Row="1"
Grid.Column="2"
Margin="0,5,0,0"
IsEnabled="{Binding IsBusy, Converter={StaticResource BoolReverseConverter}}"
IsShowStatisticColumn="True"
ItemsSource="{Binding Path=SelectedData}">
<i:Interaction.Behaviors>
<userControls:PhotoShotBehavior Target2="{Binding ElementName=chart}"/>
</i:Interaction.Behaviors>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Deleted">
<micro:ActionMessage MethodName="Deleted">
<micro:Parameter Value="$source" />
<micro:Parameter Value="$eventargs" />
</micro:ActionMessage>
</i:EventTrigger>
<i:EventTrigger EventName="Exporting">
<micro:ActionMessage MethodName="Exporting">
<micro:Parameter Value="$source" />
<micro:Parameter Value="$eventargs" />
</micro:ActionMessage>
</i:EventTrigger>
<i:EventTrigger EventName="Exported">
<micro:ActionMessage MethodName="Exported">
<micro:Parameter Value="$source" />
<micro:Parameter Value="$eventargs" />
</micro:ActionMessage>
</i:EventTrigger>
<i:EventTrigger EventName="ProgressMessageUpdating">
<micro:ActionMessage MethodName="ProgressUpdating">
<micro:Parameter Value="$source" />
<micro:Parameter Value="$eventargs" />
</micro:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</userControls:DataViewDataGrid>
<!-- data chart -->
<Grid
Grid.Row="0"
Grid.Column="2"
Margin="5,0,0,0">
<userControls:DataViewChart
x:Name="chart"
AutoRange="{Binding ChartAutoRange}"
IsEnabled="{Binding IsBusy, Converter={StaticResource BoolReverseConverter}}"
RenderableSeries="{Binding SelectedData}"
VisibleRangeTime="{Binding VisibleRangeTime}"
VisibleRangeValue="{Binding VisibleRangeValue}"/>
<userControls1:BusyIndicator
Width="Auto"
Height="Auto"
Padding="20,10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="{StaticResource Tab_BG}"
BorderBrush="Gray"
BorderThickness="3"
Message="{Binding BusyIndicatorContent}"
Visibility="{Binding IsBusy, Converter={StaticResource BoolVisibilityConverter}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Canceled">
<micro:ActionMessage MethodName="CancelQuery" />
</i:EventTrigger>
</i:Interaction.Triggers>
</userControls1:BusyIndicator>
</Grid>
<GridSplitter
Grid.Row="1"
Grid.Column="2"
Height="5"
Margin="0,0,2,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Background="LightBlue"
IsEnabled="{Binding IsBusy, Converter={StaticResource BoolReverseConverter}}" />
</Grid>
</UserControl>
@@ -0,0 +1,15 @@
using System.Windows.Controls;
namespace MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory
{
/// <summary>
/// RealtimeView.xaml 的交互逻辑
/// </summary>
public partial class DataView : UserControl
{
public DataView()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,723 @@
/************************************************************************
*@file FrameworkLocal\UIClient\CenterViews\DataLogs\DataHistory\DataViewModel.cs
* @author Su Liang
* @Date 2022-08-01
*
* @copyright &copy Sicentury Inc.
*
* @brief Reconstructed to optimize the performance.
*
* @details
* 1. 2-STAGE PIPELINE are introduced to separate the 'querying' and 'rendering' operations.
* 2. Querying day by day in separate thread.
* *****************************************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using Aitex.Core.RT.Log;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.UI.Client.CenterViews.Core;
using MECF.Framework.UI.Client.CenterViews.Core.Charting;
#if !EXPORT_TO_CSV
using MECF.Framework.Common.Utilities;
#endif
using MECF.Framework.UI.Client.CenterViews.Operations.RealTime;
using SciChart.Charting.Model.DataSeries;
using SciChart.Charting.Visuals.Axes;
using SciChart.Charting.Visuals.RenderableSeries;
using SciChart.Core.Extensions;
using SciChart.Core.Framework;
using SciChart.Data.Model;
using Sicentury.Core;
using Sicentury.Core.EventArgs;
using Sicentury.Core.Pipelines;
using Sicentury.Core.Tree;
using Cali = Caliburn.Micro;
using DateRange = SciChart.Data.Model.DateRange;
using MessageBox = System.Windows.MessageBox;
using TreeNode = Sicentury.Core.Tree.TreeNode;
namespace MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory
{
public class DataViewModel : BusyIndicateableUiViewModelBase
{
#region Variables
/// <summary>
/// 一次最多查询的项目数。
/// </summary>
private const int MAX_ITEMS_PER_QUERY = 50;
private IRange _timeRange;
private IRange _visibleRangeValue;
private AutoRange _autoRange;
private CancellationTokenSource _cancellationTokenSource;
/// <summary>
/// 更新报告导出信息。
/// </summary>
private readonly IProgress<ProgressUpdatingEventArgs> _progCsvExport;
/// <summary>
/// 查询进度信息更新。
/// </summary>
private IProgress<ProgressUpdatingEventArgs> _progQueryUpdate;
/// <summary>
/// 挂起或恢复Chart更新
/// </summary>
private readonly IProgress<bool> _progChartSuspendUpdating;
private IUpdateSuspender _suspender;
/// <summary>
/// 打开错误消息对话框。
/// </summary>
private readonly IProgress<string> _progShowErrorMessageBox;
#endregion
#region Constructors
public DataViewModel()
{
DisplayName = "Data History";
SelectedData = new ChartingLineSeriesCollection(DisplayName);
var provider = new RealtimeProvider();
ParameterNodes = new TreeNode(DisplayName)
{
MaxTerminalSelectionAllowed = MAX_ITEMS_PER_QUERY
};
ParameterNodes.ChildNodes.AddRange( provider.GetParameters());
VisibleRangeTime = new DateRange(DateTime.Now.AddMinutes(-60), DateTime.Now.AddMinutes(60));
VisibleRangeValue = new DoubleRange(0, 10);
_progQueryUpdate = new Progress<ProgressUpdatingEventArgs>(e =>
{
if (e.CurrentProgress == e.TotalProgress)
{
IsBusy = false;
if (_cancellationTokenSource?.Token.IsCancellationRequested == false)
{
foreach (var renderableSeries in SelectedData)
{
var series = renderableSeries as SicFastLineSeries;
var dataSeries = series?.GetDataSeries();
try
{
if (series != null && dataSeries != null)
{
var node = series.BackendParameterNode;
if (double.IsInfinity((double)dataSeries.YRange.Diff))
{
node.ClearStatistic();
}
else
{
var min = ((double)dataSeries.YMin);
var max = ((double)dataSeries.YMax);
var average =
dataSeries.Metadata.Cast<ParameterNodePoint>().Average(x => x.Value);
node.SetStatistic(min, max, average);
}
}
}
catch (Exception ex)
{
var err = $"It's failed to load data of {series?.DataName ?? "Unknown"}, {ex.Message}";
LOG.Error(err, ex);
}
}
}
ChartAutoRange = AutoRange.Never;
((DataView)View).chart.ZoomExtents();
}
BusyIndicatorContent = e.Message;
});
_progCsvExport = new Progress<ProgressUpdatingEventArgs>(e =>
{
BusyIndicatorContent = e.Message;
});
_progChartSuspendUpdating = new Progress<bool>(isSuspend =>
{
if (isSuspend)
_suspender = ((DataView)View).chart.SuspendSuspendUpdates();
else
{
try
{
if (_suspender?.IsSuspended == true)
_suspender?.SafeDispose();
}
catch (Exception)
{
// 查询过程最后会强制恢复挂起一次,可能引发异常,忽略此异常。
}
}
});
_progShowErrorMessageBox = new Progress<string>((error =>
{
System.Windows.Forms.MessageBox.Show(error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}));
}
#endregion
#region Property
public TreeNode ParameterNodes { get; }
public ChartingLineSeriesCollection SelectedData { get; set; }
public AutoRange ChartAutoRange
{
get => _autoRange;
set
{
_autoRange = value;
NotifyOfPropertyChange(nameof(ChartAutoRange));
}
}
public IRange VisibleRangeTime
{
get => _timeRange;
set
{
_timeRange = value;
NotifyOfPropertyChange(nameof(VisibleRangeTime));
}
}
public IRange VisibleRangeValue
{
get => _visibleRangeValue;
set
{
_visibleRangeValue = value;
NotifyOfPropertyChange(nameof(VisibleRangeValue));
}
}
public DateTime StartDateTime
{
get => ((DataView)View).wfTimeFrom.Value;
set
{
((DataView)View).wfTimeFrom.Value = value;
NotifyOfPropertyChange(nameof(StartDateTime));
}
}
public DateTime EndDateTime
{
get => ((DataView)View).wfTimeTo.Value;
set
{
((DataView)View).wfTimeTo.Value = value;
NotifyOfPropertyChange(nameof(EndDateTime));
}
}
#endregion
#region Methods
protected override void OnViewLoaded(object view)
{
base.OnViewLoaded(view);
StartDateTime = DateTime.Now.Date;
EndDateTime = DateTime.Now.Date.AddDays(1).AddTicks(-1);
}
/// <summary>
/// 查询数据。
/// </summary>
/// <exception cref="Exception"></exception>
public void Query(bool isAppend = false)
{
if (StartDateTime > EndDateTime)
{
MessageBox.Show("time range invalid, start time should be early than end time.", "Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
return;
}
// 哪些模组(TreeView的顶层Nodes)有选中项。
var selectedModules = ParameterNodes.ChildNodes.Where(x => x.HasTerminalSelected).ToList();
if (!selectedModules.Any())
{
MessageBox.Show($"No item(s) are selected to query.", "Warning", MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}
VisibleRangeTime = new DateRange(StartDateTime.AddHours(-1), EndDateTime.AddHours(1));
ChartAutoRange = AutoRange.Always;
BusyIndicatorContent = "Preparing list ...";
IsBusy = true;
_cancellationTokenSource = new CancellationTokenSource();
#region 生成曲线列表
var selectedTerminal =
selectedModules.SelectMany(x => x.Flatten(true).Where(p => p.IsSelected == true)).ToList();
List<IRenderableSeries> appendedSeries = null;
if (isAppend)
appendedSeries = SelectedData.Append(selectedTerminal);
else
{
SelectedData.ReArrange(selectedTerminal);
appendedSeries = SelectedData.ToList();
}
SelectedData.ResetColors();
#endregion
var dataSeriesList = appendedSeries.Select(x => x.DataSeries).ToList();
Task.Run( async() =>
{
// 延时启动,等待UI准备好
await Task.Delay(500);
var pipeline = new TwoStagePipelineBasedTaskExecutor<DataSet, object>();
pipeline.Stage2ActionStarted += (s, e) =>
{
// 挂起Chart
_progChartSuspendUpdating.Report(true);
};
pipeline.Stage2ActionFinished += (s, e) =>
{
// 挂起刷新
_progChartSuspendUpdating.Report(false);
};
pipeline.Stage1Finished += (s, e) =>
{
// 查询完毕,Chart可能仍在渲染。
_progQueryUpdate?.Report(new ProgressUpdatingEventArgs(50, 100, "Still rendering chart ..."));
};
using (pipeline)
{
var plTasks = pipeline.Start(null);
try
{
//! 按时间分段查询,解决查询速度慢导致卡后台业务的问题。
/*var ts = EndDateTime - StartDateTime;
if (ts.Days <= 1)
{
Query(pipeline, selectedModules, dataSeriesList, StartDateTime, EndDateTime,
_cancellationTokenSource, _progQueryUpdate);
// 结束流水线
pipeline.AppendFunc1(null);
pipeline.AppendFunc2(null);
}
else
{*/
var daySlices =
DateRangeHelper.SplitInToHours(new DateRangeHelper(StartDateTime, EndDateTime), 12);
foreach (var range in daySlices)
{
Query(pipeline, selectedModules, dataSeriesList, range.Start, range.End,
_cancellationTokenSource, _progQueryUpdate);
if (_cancellationTokenSource.Token.IsCancellationRequested)
break;
await Task.Delay(1);
}
// 结束流水线
pipeline.AppendFunc1(null);
pipeline.AppendFunc2(null);
//}
await Task.WhenAll(plTasks.ToArray());
}
catch (ThreadAbortException ex)
{
Thread.Sleep(500);
// 查询操作被取消。
Debug.WriteLine(ex);
}
catch (AggregateException ae)
{
var errs = new StringBuilder();
foreach (var ex in ae.Flatten().InnerExceptions)
{
LOG.Error(ex.Message, ex);
errs.AppendLine(ex.Message);
}
var errMsg = $"It's failed to query data, {errs}";
_progShowErrorMessageBox.Report(errMsg);
LOG.Error(errMsg, ae);
}
catch (Exception ex)
{
var errMsg = $"It's failed to query data, {ex.Message}";
_progShowErrorMessageBox.Report(errMsg);
LOG.Error(errMsg, ex);
}
finally
{
// 等待一下UI
Thread.Sleep(100);
_progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
// 强制恢复Chart刷新,避免异常情况导致的Chart挂起。
_progChartSuspendUpdating.Report(false);
}
}
});
}
/// <summary>
/// 查询数据
/// </summary>
private static void Query(TwoStagePipelineBasedTaskExecutor<DataSet, object> pipeline, IEnumerable<TreeNode> selectedModules, List<IDataSeries> dataSeriesList, DateTime startTime, DateTime endTime,
CancellationTokenSource cancellation, IProgress<ProgressUpdatingEventArgs> progressReporter = null)
{
pipeline.AppendFunc1(()=>
SearchDataBaseAsync(
selectedModules,
new DateRangeHelper(startTime, endTime),
cancellation,
progressReporter));
pipeline.AppendFunc2(ds =>
{
RenderChartAndTable(ds, dataSeriesList, cancellation, progressReporter);
return null;
});
}
/// <summary>
/// 取消查询。
/// </summary>
public void CancelQuery()
{
Task.Run(() =>
{
if (_cancellationTokenSource?.Token.CanBeCanceled == true)
{
_cancellationTokenSource.Cancel();
}
Thread.Sleep(100);
_progQueryUpdate.Report(new ProgressUpdatingEventArgs(100, 100, ""));
_progChartSuspendUpdating.Report(false);
});
if (View is DataView view)
view.dataGrid.CancelOperation();
}
/// <summary>
/// 检查指定的表名是否存在。
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
private static bool CheckTableExists(string tableName)
{
var sql =
$"SELECT EXISTS ( SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename = '{tableName}' );";
var table = QueryDataClient.Instance.Service.QueryData(sql);
if (table == null)
return false;
if (table.Rows.Count <= 0)
return false;
var value = table.Rows[0][0].ToString();
if (value.ToLower() == "true")
return true;
return false;
}
/// <summary>
/// 根据DataLog界面左侧项目树中选择的项目查询数据
/// </summary>
/// <returns></returns>
private static DataSet SearchDataBaseAsync(
IEnumerable<TreeNode> modules, DateRangeHelper dateRange,
CancellationTokenSource cancellation = null,
IProgress<ProgressUpdatingEventArgs> progressReporter = null)
{
var ds = new DataSet();
using (cancellation?.Token.Register(Thread.CurrentThread.Abort, true))
{
// 遍历模组
foreach (var module in modules)
{
// 如果当前根节点下没有被选中的终端节点,则忽略
if (module.ChildNodes.FirstOrDefault(x => (bool)x.HasTerminalSelected) == null)
continue;
string tblNameWithoutDay;
if (module.Name.StartsWith("IO"))
{
tblNameWithoutDay = $"{module.Name}";
}
else if (module.Name.StartsWith("PM"))
{
tblNameWithoutDay = $"{module.Name}";
}
else
{
tblNameWithoutDay = $"System";
}
if (module.Name.StartsWith("IO"))
{
foreach (var subIo in module.ChildNodes)
{
if(!subIo.HasTerminalSelected)
continue;
tblNameWithoutDay = subIo.FullName;
// 如果不是IO节点,则根节点名即为数据库名=
var dt = SearchSingleDbTable(tblNameWithoutDay, subIo, dateRange, cancellation, progressReporter);
if (dt != null)
ds.Tables.Add(dt);
}
}
else
{
if (module.ChildNodes.FirstOrDefault(x => (bool)x.HasTerminalSelected) == null)
continue;
var dt = SearchSingleDbTable(tblNameWithoutDay, module, dateRange, cancellation,
progressReporter);
if (dt != null)
ds.Tables.Add(dt);
}
}
}
return ds;
}
/// <summary>
/// IO节点在数据库中的表名比较特殊,需要特殊处理。
/// </summary>
/// <param name="module"></param>
/// <param name="dateRange"></param>
/// <param name="cancellation"></param>
/// <param name="progressReporter"></param>
/// <returns></returns>
private static DataTable SearchSingleDbTable(string tableName, TreeNode module, DateRangeHelper dateRange,
CancellationTokenSource cancellation = null,
IProgress<ProgressUpdatingEventArgs> progressReporter = null)
{
var sql = new StringBuilder();
//! 因为数据库中按天拆表,无法一次性查询数据,需使用UNION合并多表查询,因此此处按天拼接SQL表达式
// 最终SQL表达式结构为:
// (select xx from date1.xx) union (select xx from date2.xx) union (select xx from date3.xx)
// where time between xxx and xxx
// order by time asc
var ts = dateRange.Diff;
for (var day = 0; day <= ts.Days; day++)
{
var tblName = $"{dateRange.Start.AddDays(day):yyyyMMdd}.{tableName}";
// 检查表名是否存在,否则SQL执行出错。
if (CheckTableExists(tblName))
{
sql.Append("select \"time\" AS InternalTimeStamp");
var selectedParams = module.Flatten(true)
.Where(x => x.IsSelected == true);
// 添加待查询的列
foreach (var item in selectedParams)
{
sql.Append("," + $"\"{item}\"");
}
sql.Append($" from \"{tblName}\" ");
if (day < ts.Days)
sql.Append(" UNION ");
}
}
// 所有表名不可用,可能是日期范围错误
if (sql.Length <= 0)
{
return null;
}
sql.Append(
$" where \"time\" between {dateRange.Start.Ticks} and {dateRange.End.Ticks} order by InternalTimeStamp asc");
progressReporter?.Report(new ProgressUpdatingEventArgs(20, 100,
$"Querying {dateRange}..."));
if (cancellation?.Token.IsCancellationRequested == true)
return null;
// 查询数据并将返回的结果存储在DataSet中
var dataTable = QueryDataClient.Instance.Service.QueryData(sql.ToString());
if (cancellation?.Token.IsCancellationRequested == true)
return null;
//! 返回的 DataTable 可能不存在,原因是上述代码自动生成的表明可能不存在。
if (dataTable == null)
return null;
dataTable.TableName = module.FullName;
return dataTable;
}
/// <summary>
/// 渲染图表。
/// </summary>
/// <param name="ds"></param>
/// <param name="dataSeriesList"></param>
/// <param name="cancellation"></param>
/// <param name="progressReporter"></param>
/// <exception cref="Exception"></exception>
private static void RenderChartAndTable(
DataSet ds, List<IDataSeries> dataSeriesList,
CancellationTokenSource cancellation = null,
IProgress<ProgressUpdatingEventArgs> progressReporter = null)
{
if (ds == null || ds.Tables.Count <= 0)
return;
// 一个Table一个模组
foreach (var table in ds.Tables.Cast<DataTable>())
{
if (table.Rows.Count <= 0)
continue;
// 一列对应模组中的某个数据记录点
foreach (var col in table.Columns.Cast<DataColumn>())
{
// 忽略时间列
if (col.Ordinal == 0)
continue;
var fullName = col.ColumnName;
var dataSeries =
dataSeriesList.FirstOrDefault(x => x.SeriesName == fullName) as XyDataSeries<DateTime, double>;
if (dataSeries == null)
continue;
var rows = table.Rows;
var dateList = new List<DateTime>();
var valueList = new List<double>();
var metaList = new List<ParameterNodePoint>();
for (var i = 0; i < rows.Count; i++)
{
var date = new DateTime(long.Parse(rows[i][0].ToString()));
var cellValue = rows[i][col];
var value = double.NaN;
if (cellValue is bool b)
value = b ? 1 : 0;
else if (double.TryParse(cellValue.ToString(), out var num))
value = num;
else
value = 0;
dateList.Add(date);
valueList.Add(value);
metaList.Add(new ParameterNodePoint(date, value));
if (cancellation?.Token.IsCancellationRequested == true)
return;
}
if (cancellation?.Token.IsCancellationRequested == true)
return;
dataSeries.Append(dateList, valueList, metaList);
if(dataSeries is SicFastLineDataSeries ss)
ss.UpdateChartSeriesValue(); // 应用Factor和Offset
}
if (cancellation?.Token.IsCancellationRequested == true)
return;
// 每一轮更新完毕后会恢复Chart刷新,
// 数据量太小时会频繁挂起和恢复Chart,导致Chart不刷新,需要稍等一下UI。
Thread.Sleep(50);
}
}
public void Exporting(object sender, EventArgs e)
{
BusyIndicatorContent = "Exporting Start ...";
IsBusy = true;
}
public void Exported(object sender, EventArgs e)
{
IsBusy = false;
}
public void Deleted(object sender, EventArgs e)
{
((DataView)View).tvParameterNodes.ClearPresetGroupSelectionOnly();
}
public void ProgressUpdating(object sender, ProgressUpdatingEventArgs e)
{
_progCsvExport.Report(e);
}
#endregion
}
}
@@ -0,0 +1,215 @@
<UserControl
x:Class="MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory.SelectUserDefineView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="clr-namespace:Caliburn.Micro"
xmlns:ctrl="http://OpenSEMI.Ctrlib.com/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolkit="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:wf="[wf ]clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:wfi="[wfi ]clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
d:DesignHeight="600"
d:DesignWidth="1200"
mc:Ignorable="d">
<UserControl.Resources>
<Style TargetType="{x:Type ListBox}">
<Setter Property="Foreground" Value="{DynamicResource FG_Black}" />
<Setter Property="FontFamily" Value="Arial" />
<Setter Property="FontSize" Value="12" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
<Setter Property="ScrollViewer.CanContentScroll" Value="False" />
<Setter Property="VerticalContentAlignment" Value="top" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<Border x:Name="Bd" SnapsToDevicePixels="true">
<ScrollViewer Padding="{TemplateBinding Padding}" Focusable="false">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</ScrollViewer>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false" />
<Trigger Property="IsGrouping" Value="true">
<Setter Property="ScrollViewer.CanContentScroll" Value="false" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Margin" Value="10,5,0,0" />
<Setter Property="Padding" Value="0" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Rectangle.StrokeThickness" Value="1" />
<Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" />
<Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd" SnapsToDevicePixels="true">
<Grid>
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Cursor="Hand"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<Rectangle
x:Name="Highlight"
Opacity="0"
StrokeThickness="{TemplateBinding Rectangle.StrokeThickness}" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Highlight" Property="Stroke" Value="Blue" />
<Setter TargetName="Highlight" Property="Opacity" Value="1" />
<Setter Property="Foreground" Value="{DynamicResource FG_Black}" />
<Setter Property="Background" Value="Blue" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid Width="1200" Height="600">
<Border
Padding="10"
Background="White"
BorderBrush="Gray"
BorderThickness="1">
<Border.Effect>
<DropShadowEffect
BlurRadius="5"
ShadowDepth="5"
Color="#3F000000" />
</Border.Effect>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border
Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="10,5,0,0"
Padding="5"
BorderBrush="Gray"
BorderThickness="1">
<TreeView x:Name="ParameterTreeView" ItemsSource="{Binding ParameterNodes}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TreeView.SelectedItemChanged">
<cal:ActionMessage MethodName="OnTreeSelectedChanged">
<cal:Parameter Value="{Binding ElementName=ParameterTreeView, Path=SelectedItem}" />
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding ChildNodes}">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Selected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="ParameterCheck">
<cal:Parameter Value="{Binding}" />
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Border>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="10,5,0,5"
FontFamily="Arial"
FontSize="14"
Text="Selected Parameter" />
<Border
Grid.Row="1"
Grid.Column="0"
Margin="10,0,0,0"
Padding="5"
BorderBrush="Gray"
BorderThickness="1">
<ListBox
x:Name="_selectListBox"
FontFamily="Arial"
FontSize="14"
ItemsSource="{Binding SelectedParameters}"
SelectedItem="{Binding SelectedItem}"
SelectionMode="Multiple" />
</Border>
<StackPanel
Grid.Row="2"
Grid.ColumnSpan="2"
Margin="0,10,0,0"
HorizontalAlignment="Center"
Orientation="Horizontal">
<Button
Width="100"
Height="30"
Content="Delete">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="Delete" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button
Width="100"
Height="30"
Margin="20,0,20,0"
Content="Delete All">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="DeleteAll" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button
Width="100"
Height="30"
Content="OK">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="OK" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button
Width="100"
Height="30"
Margin="20,0,0,0"
Content="Cancel">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:ActionMessage MethodName="Cancel" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
</Grid>
</Border>
</Grid>
</UserControl>
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory
{
/// <summary>
/// SelectUserDefineView.xaml 的交互逻辑
/// </summary>
public partial class SelectUserDefineView : UserControl
{
public SelectUserDefineView()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,219 @@
using MECF.Framework.UI.Client.ClientBase;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using MECF.Framework.UI.Client.CenterViews.DataLogs.ProcessHistory;
using Sicentury.Core.Collections;
using Sicentury.Core.Tree;
namespace MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory
{
public class SelectUserDefineViewModel : UiViewModelBase
{
#region
private const int MAX_PARAMETERS = 50;
public ObservableRangeCollection<TreeNode> ParameterNodes { get; }
public ObservableRangeCollection<string> SelectedParameters { get; set; }
public ObservableRangeCollection<TreeNode> ParameterNodes1 = new ObservableRangeCollection<TreeNode>();
object _lockSelection = new object();
public ObservableRangeCollection<string> SourcePM { get; set; }
public string SelectedValuePM { get; set; }
public string SelectedItem { get; set; }
#endregion
#region Popup window
public SelectUserDefineViewModel()
{
SelectedParameters = new ObservableRangeCollection<string>();
ParameterNodes = new ObservableRangeCollection<TreeNode>(ProcessHistoryProvider.Instance.GetParameters());
SourcePM = new ObservableRangeCollection<string>(new[] { "PMA", "PMB" });
}
protected override void OnViewLoaded(object _view)
{
base.OnViewLoaded(_view);
this.view = (SelectUserDefineView)_view;
}
protected override void OnActivate()
{
base.OnActivate();
ParameterNodes.Clear();
ParameterNodes.AddRange(ProcessHistoryProvider.Instance.GetParameters());
SetParameterNode(ParameterNodes, true);
}
private void SetParameterNode(ObservableCollection<TreeNode> nodes, bool isCheck)
{
foreach (TreeNode n in nodes)
{
if (isCheck)
{
if (SelectedParameters.Any(x => x == n.Name))
n.IsSelected = true;
}
else
n.IsSelected = false;
SetParameterNode(n.ChildNodes, isCheck);
}
}
private SelectUserDefineView view;
public void Preset()
{
}
public void UnSelect()
{
}
//public void ParameterCheck(TreeNode node)
//{
// bool result = RefreshTreeStatusToChild(node);
// if (!result)
// node.Selected = !node.Selected;
// else
// RefreshTreeStatusToParent(node);
//}
///// <summary>
///// Refresh tree node status from current to children, and add data to SelectedData
///// </summary>
//private bool RefreshTreeStatusToChild(TreeNode node)
//{
// if (node.ChildNodes.Count > 0)
// {
// for (int i = 0; i < node.ChildNodes.Count; i++)
// {
// TreeNode n = node.ChildNodes[i];
// n.Selected = node.Selected;
// //for (int j = 0; j < SelectedParameters.Count; j++)
// //{
// // if ((SelectedParameters[j].Contains("PMA.") && node.Name.Contains("PMB")) || (SelectedParameters[j].Contains("PMB.") && node.Name.Contains("PMA")))
// // {
// // n.Selected = !node.Selected;
// // DialogBox.ShowWarning("PMA,PMB you can only choose one or the other");
// // return false;
// // }
// //}
// if (!RefreshTreeStatusToChild(n))
// {
// //uncheck left node
// for (int j = i; j < node.ChildNodes.Count; j++)
// {
// node.ChildNodes[j].Selected = !node.Selected;
// }
// node.Selected = !node.Selected;
// return false;
// }
// }
// }
// else //leaf node
// {
// lock (_lockSelection)
// {
// bool flag = SelectedParameters.Contains(node.Name);
// if (node.Selected && !flag)
// {
// if (SelectedParameters.Count < MAX_PARAMETERS)
// {
// SelectedParameters.Add(node.Name);
// }
// else
// {
// DialogBox.ShowWarning($"The max number of parameters is {MAX_PARAMETERS}.");
// return false;
// }
// }
// else if (!node.Selected && flag)
// {
// SelectedParameters.Remove(node.Name);
// }
// }
// }
// return true;
//}
///// <summary>
///// Refresh tree node status from current to parent
///// </summary>
///// <param name="node"></param>
///// <returns></returns>
//private void RefreshTreeStatusToParent(TreeNode node)
//{
// if (node.ParentNode != null)
// {
// if (node.Selected)
// {
// bool flag = true;
// for (int i = 0; i < node.ParentNode.ChildNodes.Count; i++)
// {
// if (!node.ParentNode.ChildNodes[i].Selected)
// {
// flag = false; //as least one child is unselected
// break;
// }
// }
// if (flag)
// node.ParentNode.Selected = true;
// }
// else
// {
// node.ParentNode.Selected = false;
// }
// RefreshTreeStatusToParent(node.ParentNode);
// }
//}
public void OnTreeSelectedChanged(object obj)
{
}
public void OK()
{
this.TryClose(true);
}
public void DeleteAll()
{
SelectedParameters.Clear();
SetParameterNode(ParameterNodes, false);
}
public void Delete()
{
if (view._selectListBox.SelectedItems != null)
{
List<object> temp = new List<object>();
foreach (var item in view._selectListBox.SelectedItems)
{
temp.Add(item.ToString());
}
foreach (var item in temp)
{
SelectedParameters.Remove(item.ToString());
}
SetParameterNode(ParameterNodes, false);
SetParameterNode(ParameterNodes, true);
}
}
public void Cancel()
{
this.TryClose(false);
}
#endregion
}
}
@@ -0,0 +1,31 @@
using System;
using MECF.Framework.Common.ControlDataContext;
namespace MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory
{
public class TimeChartDataLine : ChartDataLine
{
public string Module { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public DateTime TokenTime { get; set; }
private string[] _dbModules = { "PM1", "PM2", "PM3", "PM4" };
public TimeChartDataLine(string dataName, DateTime startTime, DateTime endTime) : base(dataName)
{
StartTime = startTime;
EndTime = endTime;
TokenTime = startTime;
Module = "System";
foreach (var dbModule in _dbModules)
{
if (dataName.StartsWith(dbModule) || dataName.StartsWith("IO." + dbModule))
{
Module = dbModule;
break;
}
}
}
}
}