Compare commits

..

2 Commits

Author SHA1 Message Date
tayttt db5afffa63 为DAL项目添加log4net引用以支持数据库异常日志记录
- 在Txgy.EWS.Client.DAL项目中添加log4net程序集引用
- 添加using System.Reflection指令以支持MethodBase
- 修复RemoteMySQLDataAccess.cs中的日志记录代码
- 更新packages.config添加log4net 2.0.15包引用

现在DAL项目可以成功编译,数据库操作的异常将被详细记录到日志文件中

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
3 months ago
tayttt 25b333ceb9 增强数据库操作日志记录和异常捕获
主要更改:
- 修改log4net配置文件,增加异常堆栈信息和线程ID输出
- 在RemoteMySQLDataAccess中添加详细的异常日志记录
- 为所有数据库操作方法的catch块添加错误日志
- 日志包含方法参数信息,便于定位问题

详情:
1. log4net.config
   - ErrorAppender增加线程ID和异常详情输出
   - DebugAppender增加线程ID和异常详情输出

2. RemoteMySQLDataAccess.cs
   - 添加日志记录器实例
   - 18个catch块添加详细错误日志
   - 日志包含操作参数(时间范围、ID、路径等)
   - 保留原有异常处理逻辑

这将帮助快速定位和重现数据库相关bug。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
3 months ago

@ -12,6 +12,7 @@ namespace Txgy.Controls
public class myListBox : System.Windows.Controls.ListBox
{
private ListBoxItem _lastSelectedItem;
protected override DependencyObject GetContainerForItemOverride()
{
return new myListBoxItem();

@ -44,6 +44,8 @@ namespace Txgy.EWS.Client.Common.Helpers
double yDrawUnit = 1;
double drawUnit = 1;
Point _downPoint = new Point(0, 0);
bool _isMoving = false;
double left = 0, top = 0;
public bool IsShowGridText = true;
public bool IsShowGrid = true;
public System.Windows.Media.Color BackGroundColor = System.Windows.Media.Colors.White;

@ -20,6 +20,7 @@ namespace Txgy.EWS.Client.Common.Helpers
public class ReportStereogramImage : IDisposable
{
string stereoImagePath;
List<PointLineSeries3D> eventList;
public LightningChart lightChart = new LightningChart();
View3D view3D = new View3D();
@ -29,6 +30,8 @@ namespace Txgy.EWS.Client.Common.Helpers
double _sideRotationRS = 0;
double _horizontalRotationRS = -30;
double _verticalRotationRS = 30;
double _distanceRS = 150;
bool _clipDispaly = false;
WallXZ _topWall;
WallYZ _leftWall;
WallYZ _rightWall;
@ -38,6 +41,7 @@ namespace Txgy.EWS.Client.Common.Helpers
AxisX3D _axisXPri3D;
AxisY3D _axisYPri3D;
AxisZ3D _axisZPri3D;
ProjectionType _projectionTypeRS = ProjectionType.Perspective;
public double _scale = 1;
SizeDoubleXYZ eventSize;

@ -25,7 +25,7 @@ namespace Txgy.EWS.Client.Common.Helpers
//CommonLogHelper.Debug("XML文件读取成功。");
}
catch (Exception)
catch (Exception ex)
{
//CommonLogHelper.log.Error(string.Format("XML文件读取失败。{0}", ex));
}

@ -7,11 +7,13 @@ using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Txgy.EWS.Client.Common;
using Txgy.EWS.Client.Common.Helpers;
using Txgy.EWS.Client.IDAL;
using Txgy.EWS.Client.Models;
using Txgy.Microseismic.BaseLib.Common;
@ -23,6 +25,7 @@ namespace Txgy.EWS.Client.DAL
{
public class RemoteMySQLDataAccess : IRemoteMySQLDataAccess
{
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
IFreeSql fsql = FreeSqlTencent.tencentRemoteMySQL;
public string saveWavePath = "";
public MySqlConnection RemoteConn { get; set; }
@ -69,8 +72,9 @@ namespace Txgy.EWS.Client.DAL
}
return true;
}
catch
catch (Exception ex)
{
logger.Error("数据库连接失败", ex);
return false;
}
}
@ -129,8 +133,9 @@ namespace Txgy.EWS.Client.DAL
// //result.Data = Newtonsoft.Json.JsonConvert.SerializeObject(v.ToList());
//}
}
catch (Exception)
catch (Exception ex)
{
logger.Error($"获取事件列表失败 - 开始时间:{startTime}, 结束时间:{endTime}, 页码:{pageIndex}, 每页数量:{perPageCount}", ex);
return null;
}
}
@ -178,7 +183,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
throw ex;
logger.Error($"获取事件列表失败 - 开始时间:{startTime}, 结束时间:{endTime}", ex);
throw;
}
finally
{
@ -229,9 +235,9 @@ namespace Txgy.EWS.Client.DAL
return list;
}
}
catch (Exception)
catch (Exception ex)
{
//messagebox.show
logger.Error($"获取事件列表失败 - 开始时间:{startTime}, 结束时间:{endTime}, minML:{minML}, maxML:{maxML}", ex);
}
finally
{
@ -307,9 +313,9 @@ namespace Txgy.EWS.Client.DAL
return resultlist;
}
}
catch (Exception)
catch (Exception ex)
{
//throw ex;
logger.Error($"根据SQL查询事件失败 - QueryStr:{QueryStr}, SortTarget:{ssm}, SortMode:{sm}", ex);
}
finally
{
@ -376,7 +382,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
throw ex;
logger.Error($"获取最新事件失败 - MaxCnt:{MaxCnt}, PreCnt:{PreCnt}", ex);
throw;
}
finally
{
@ -442,7 +449,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
throw ex;
logger.Error($"下载波形数据失败 - 事件时间:{eventTime}, 保存路径:{savePath}, 保存名称:{saveName}, 表名:{tableName}", ex);
throw;
}
finally
{
@ -496,9 +504,9 @@ namespace Txgy.EWS.Client.DAL
}
}
}
catch (Exception)
catch (Exception ex)
{
//messagebox.show
logger.Error($"获取事件详情失败 - 事件ID:{eventID}", ex);
}
finally
{
@ -551,7 +559,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
throw ex;
logger.Error($"获取事件详情失败 - 事件时间:{eventTime}", ex);
throw;
}
finally
{
@ -604,7 +613,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
throw ex;
logger.Error("获取最新事件失败", ex);
throw;
}
finally
{
@ -658,7 +668,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
throw ex;
logger.Error($"获取最新事件失败 - 截止时间:{deadline}", ex);
throw;
}
finally
{
@ -764,9 +775,10 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
logger.Error($"统计事件数量失败 - 开始时间:{startTime}, 结束时间:{endTime}", ex);
// 异常处理代码
Console.WriteLine($"DownloadDataAsync error: {ex.StackTrace}");
throw ex;
throw;
}
// 如果没有查询到数据,则返回空引用
return 0;
@ -837,9 +849,10 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
logger.Error($"异步下载波形数据失败 - 事件时间:{gier.EventTime}, 保存路径:{savePath}", ex);
// 异常处理代码
Console.WriteLine($"DownloadDataAsync error: {ex.StackTrace}");
throw ex;
throw;
}
finally
{
@ -906,9 +919,10 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
logger.Error($"异步下载JSON数据失败 - 事件时间:{gier.EventTime}, 保存路径:{savePath}", ex);
// 异常处理代码
Console.WriteLine($"DownloadDataAsync error: {ex.StackTrace}");
throw ex;
throw;
}
finally
{
@ -975,9 +989,10 @@ namespace Txgy.EWS.Client.DAL
catch (Exception ex)
{
_semaphore.Release();
logger.Error($"查询和下载数据失败 - 事件ID:{eventID}, 保存路径:{savePath}", ex);
// 异常处理代码
Console.WriteLine($"QueryAndDownloadDataAsync error: {ex.StackTrace}");
throw ex;
throw;
}
}
@ -1043,9 +1058,10 @@ namespace Txgy.EWS.Client.DAL
catch (Exception ex)
{
_semaphore.Release();
logger.Error($"按ID查询和下载数据失败 - 事件ID:{eventID}, 保存路径:{savePath}", ex);
// 异常处理代码
Console.WriteLine($"QueryAndDownloadDataAsync error: {ex.StackTrace}");
throw ex;
throw;
}
}
public async Task QueryEventByIDAsync(int eventID, string savePath, Action<GridItemEventResult> callback)
@ -1110,9 +1126,10 @@ namespace Txgy.EWS.Client.DAL
catch (Exception ex)
{
_semaphore.Release();
logger.Error($"按ID查询事件失败 - 事件ID:{eventID}, 保存路径:{savePath}", ex);
// 异常处理代码
Console.WriteLine($"QueryAndDownloadDataAsync error: {ex.StackTrace}");
throw ex;
throw;
}
}
public List<GridItemEventResult> GetLastEvents(int lastEventID)
@ -1205,7 +1222,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
throw ex;
logger.Error($"获取最新事件失败 - 数量:{QueryCount}", ex);
throw;
}
finally
{
@ -1261,8 +1279,8 @@ namespace Txgy.EWS.Client.DAL
}
catch (Exception ex)
{
//messagebox.show
throw ex;
logger.Error($"获取网格事件失败 - 开始时间:{startTime}, 结束时间:{endTime}, minML:{minML}, maxML:{maxML}", ex);
throw;
}
finally
{

@ -62,6 +62,9 @@
<Reference Include="K4os.Hash.xxHash, Version=1.0.6.0, Culture=neutral, PublicKeyToken=32cd54395057cec3, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Hash.xxHash.1.0.6\lib\net46\K4os.Hash.xxHash.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="MySql.Data, Version=8.0.30.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.8.0.30\lib\net48\MySql.Data.dll</HintPath>
</Reference>

@ -22,4 +22,5 @@
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.2" targetFramework="net48" />
<package id="log4net" version="2.0.15" targetFramework="net48" />
</packages>

@ -34,8 +34,10 @@
<conversionPattern value="
%n【日志级别】%-5level
%n【记录时间】%date
%n【线程ID】[%thread]
%n【错误位置】%logger 属性[%property{NDC}]
%n【错误描述】%message
%n【异常详情】%exception
%n【错误详情】%newline"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter,log4net">
@ -62,8 +64,7 @@
<layout type="log4net.Layout.PatternLayout">
<!--输出格式 模板-->
<!--样例INFO 2008-03-26 13:42:32, Log4NetDemo.MainClass [(null)] - info-->
<!--<conversionPattern value="%newline %n记录时间%date %n线程ID:[%thread] %n日志级别 %-5level %n错误描述%message%newline %n"/>-->
<conversionPattern value="%[-2level] %date %logger 属性[%property{NDC}] %message %n"/>
<conversionPattern value="%[-2level] %date [%thread] %logger 属性[%property{NDC}] %message %exception %n"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter,log4net">
<levelMin value="DEBUG" />

@ -934,7 +934,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
}
}
}
catch (Exception)
catch (Exception ex)
{
return 0;
//throw ex;

@ -193,6 +193,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
}
}
private Fill _chartBackGround = new Fill();
private IEventAggregator _ea;
public Fill ChartBackGround
{

@ -75,23 +75,6 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
public int dayFreqImageHeight = 585;
public int reportDayListFirstRow = 35;
public int reportEventListCols = 10;
private class SearchProgressInfo
{
public int CompletedCount { get; set; }
public int TotalCount { get; set; }
public string Message { get; set; }
public double? Percent { get; set; }
public bool IsIndeterminate { get; set; }
public bool ShowCount { get; set; }
}
private const double SearchProgressQueryComplete = 5;
private const double SearchProgressComputeComplete = 80;
private const double SearchProgressListComplete = 84;
private const double SearchProgressEnergyComplete = 87;
private const double SearchProgressDayFreqComplete = 90;
private const double SearchProgressPlanComplete = 95;
private const double SearchProgressComplete = 100;
/// <summary>
/// 查询模式0自定义查询1日报2周报3月报
/// </summary>
@ -103,6 +86,8 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
double _sideRotationRS = 0;
double _horizontalRotationRS = -30;
double _verticalRotationRS = 30;
double _distanceRS = 150;
bool _clipDispaly = false;
WallXZ _topWall;
WallYZ _leftWall;
WallYZ _rightWall;
@ -112,6 +97,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
AxisX3D _axisXPri3D;
AxisY3D _axisYPri3D;
AxisZ3D _axisZPri3D;
ProjectionType _projectionTypeRS = ProjectionType.Perspective;
public double _scale = 1;
SizeDoubleXYZ eventSize;
#endregion
@ -244,110 +230,6 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
SetProperty(ref _searchCount, value);
}
}
private double _totalEnergy = 0;
public double TotalEnergy
{
get { return _totalEnergy; }
set
{
SetProperty(ref _totalEnergy, value);
}
}
private double _averageEnergy = 0;
public double AverageEnergy
{
get { return _averageEnergy; }
set
{
SetProperty(ref _averageEnergy, value);
}
}
private double _maxEnergy = 0;
public double MaxEnergy
{
get { return _maxEnergy; }
set
{
SetProperty(ref _maxEnergy, value);
}
}
private bool _isSearching;
public bool IsSearching
{
get { return _isSearching; }
set
{
if (SetProperty(ref _isSearching, value))
{
SearchProgressVisibility = value ? Visibility.Visible : Visibility.Collapsed;
RaisePropertyChanged(nameof(IsSearchEnabled));
}
}
}
public bool IsSearchEnabled
{
get { return !IsSearching; }
}
private Visibility _searchProgressVisibility = Visibility.Collapsed;
public Visibility SearchProgressVisibility
{
get { return _searchProgressVisibility; }
set
{
SetProperty(ref _searchProgressVisibility, value);
}
}
private bool _searchProgressIndeterminate = true;
public bool SearchProgressIndeterminate
{
get { return _searchProgressIndeterminate; }
set
{
SetProperty(ref _searchProgressIndeterminate, value);
}
}
private double _searchProgressValue;
public double SearchProgressValue
{
get { return _searchProgressValue; }
set
{
SetProperty(ref _searchProgressValue, value);
}
}
private string _searchProgressText = "";
public string SearchProgressText
{
get { return _searchProgressText; }
set
{
SetProperty(ref _searchProgressText, value);
}
}
private string _searchProgressPercentText = "";
public string SearchProgressPercentText
{
get { return _searchProgressPercentText; }
set
{
SetProperty(ref _searchProgressPercentText, value);
}
}
private string _likeCondition;
public string LikeCondition
@ -413,240 +295,78 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
}
public ICommand SelectEventListCommand
{
get => new DelegateCommand<ReportView>(async (rView) => await ExecuteSelectEventListAsync(rView));
}
public ICommand SelectDayCommand
{
get => new DelegateCommand<ReportView>(async (rView) => await ExecuteSelectDayAsync(rView));
}
private async Task ExecuteSelectEventListAsync(ReportView rView)
{
if (IsSearching)
{
return;
}
SelectType = 0;
DateTime st = TimeFC.Cond1;
DateTime et = TimeFC.Cond2;
await ExecuteSearchAsync(rView, st, et, false);
}
private async Task ExecuteSelectDayAsync(ReportView rView)
{
if (IsSearching)
{
return;
}
SelectType = 1;
DateTime drstarttime = GlobalConfig.DailyReportStartTime;
DateTime st = new DateTime(TimeFC.Cond1.Year, TimeFC.Cond1.Month, TimeFC.Cond1.Day,
drstarttime.Hour, drstarttime.Minute, drstarttime.Second);
await ExecuteSearchAsync(rView, st, st.AddSeconds(86399), true);
}
private async Task ExecuteSearchAsync(ReportView rView, DateTime st, DateTime et, bool createDayFreq)
{
try
{
IsSearching = true;
ResetSearchProgress("正在查询事件数据...");
var progress = new Progress<SearchProgressInfo>(UpdateSearchProgress);
var results = await SearchEventsAsync(st, et, progress);
await ApplySearchResultsAsync(rView, results, st, createDayFreq, progress);
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Show("查询失败:" + ex.Message);
}
finally
{
IsSearching = false;
}
}
private async Task ApplySearchResultsAsync(ReportView rView, List<GridItemEventResult> results, DateTime st, bool createDayFreq, IProgress<SearchProgressInfo> progress)
{
if (results == null)
{
return;
}
await RefreshResultListAsync(results, progress);
progress.Report(CreateStageProgress("正在统计能量", SearchProgressListComplete));
await YieldToUiAsync();
UpdateEnergyStats(results);
if (createDayFreq)
{
progress.Report(CreateStageProgress("正在生成频度图", SearchProgressEnergyComplete));
await YieldToUiAsync();
FreqChart = CreateDayFreqImage(results, st, st.ToString("D", culture));
}
progress.Report(CreateStageProgress("正在筛选中等能量事件", SearchProgressDayFreqComplete));
await YieldToUiAsync();
var mes = results.Where(rs => rs.Energy >= MiddleEnergy).ToList();
MiddleEnergyEvents = mes;
MiddleEventCount = mes.Count();
if (mes.Count > 0 && rView != null)
{
progress.Report(CreateStageProgress("正在绘制平面图", SearchProgressDayFreqComplete));
await YieldToUiAsync();
ReportPlanImage rpi = new ReportPlanImage();
rpi.Draw(mes, rView.canvasPlan.ActualWidth, rView.canvasPlan.ActualHeight);
rView.canvasPlan.Children.Clear();
rView.canvasPlan.Children.Add(rpi.host);
progress.Report(CreateStageProgress("正在生成三维图", SearchProgressPlanComplete));
await YieldToUiAsync();
CreateStereoChart(mes);
}
progress.Report(CreateStageProgress("查询完成", SearchProgressComplete));
await YieldToUiAsync();
}
private async Task RefreshResultListAsync(List<GridItemEventResult> results, IProgress<SearchProgressInfo> progress)
{
SelectResult = new ObservableCollection<GridItemEventResult>();
SearchCount = results.Count;
if (results.Count == 0)
get => new DelegateCommand<ReportView>((rView) =>
{
progress.Report(CreateStageProgress("正在刷新事件列表", SearchProgressListComplete));
await YieldToUiAsync();
return;
}
SelectType = 0;
DateTime st = TimeFC.Cond1;
DateTime et = TimeFC.Cond2;
var results = SearchEvents(st, et);
const int batchSize = 50;
for (int i = 0; i < results.Count; i++)
{
SelectResult.Add(results[i]);
if ((i + 1) % batchSize == 0 || i == results.Count - 1)
if (results != null)
{
double percent = SearchProgressComputeComplete
+ ((i + 1) / (double)results.Count) * (SearchProgressListComplete - SearchProgressComputeComplete);
progress.Report(new SearchProgressInfo
SelectResult = new ObservableCollection<GridItemEventResult>(results);
//FreqChart = CreateDayFreqImage(results, st, st.ToString("D", culture));
//freqBytes = BitmapHelper.ConvertToBytes(ExportToBitmap(FreqChart, dayFreqImageWidth, dayFreqImageHeight));
var mes = results.Where(rs => rs.Energy >= MiddleEnergy).ToList();
//new ReportPlanImage().DrawPlanClipToFile(mes);
MiddleEnergyEvents = mes;
MiddleEventCount = mes.Count();
if (mes.Count > 0)
{
CompletedCount = i + 1,
TotalCount = results.Count,
Message = "正在刷新事件列表",
Percent = percent,
IsIndeterminate = false,
ShowCount = true
});
await YieldToUiAsync();
ReportPlanImage rpi = new ReportPlanImage();
//rpi.DrawPlanClipToDrawVisual(mes, (int)rView.canvasPlan.ActualWidth, (int)rView.canvasPlan.ActualHeight);
rpi.Draw(mes, rView.canvasPlan.ActualWidth, rView.canvasPlan.ActualHeight);
//rView.canvasPlan = rpi.host;
rView.canvasPlan.Children.Clear();
rView.canvasPlan.Children.Add(rpi.host);
CreateStereoChart(mes);
}
}
}
}
private void ResetSearchProgress(string message)
{
SearchProgressIndeterminate = true;
SearchProgressValue = 0;
SearchProgressPercentText = "";
SearchProgressText = message;
});
}
private void UpdateSearchProgress(SearchProgressInfo progress)
public ICommand SelectDayCommand
{
if (progress == null)
get => new DelegateCommand<ReportView>((rView) =>
{
return;
}
SelectType = 1;
//日报起始时刻
DateTime drstarttime = GlobalConfig.DailyReportStartTime;
Console.WriteLine(GlobalConfig.DailyReportStartTime.ToString());
DateTime st = new DateTime(TimeFC.Cond1.Year, TimeFC.Cond1.Month, TimeFC.Cond1.Day,
drstarttime.Hour, drstarttime.Minute, drstarttime.Second);
if (progress.Percent.HasValue)
{
double explicitPercent = Math.Max(0, Math.Min(100, progress.Percent.Value));
SearchProgressIndeterminate = progress.IsIndeterminate;
SearchProgressValue = explicitPercent;
SearchProgressPercentText = progress.IsIndeterminate ? "" : explicitPercent.ToString("F0") + "%";
SearchProgressText = BuildSearchProgressText(progress);
if (progress.TotalCount > 0)
{
SearchCount = progress.TotalCount;
}
return;
}
var results = SearchEvents(st, st.AddSeconds(86399));
if (progress.TotalCount <= 0)
{
SearchProgressIndeterminate = progress.IsIndeterminate || progress.Message != "未查询到事件";
SearchProgressValue = 0;
SearchProgressPercentText = progress.Message == "未查询到事件" ? "0%" : "";
SearchProgressText = progress.Message;
if (progress.Message == "未查询到事件")
if (results != null)
{
SearchCount = 0;
}
return;
}
SelectResult = new ObservableCollection<GridItemEventResult>(results);
double percent = Math.Round(progress.CompletedCount * 100.0 / progress.TotalCount, 0);
SearchCount = progress.TotalCount;
SearchProgressIndeterminate = false;
SearchProgressValue = percent;
SearchProgressPercentText = percent.ToString("F0") + "%";
SearchProgressText = BuildSearchProgressText(progress);
}
FreqChart = CreateDayFreqImage(results, st, st.ToString("D", culture));
//freqBytes = BitmapHelper.ConvertToBytes(ExportToBitmap(FreqChart, dayFreqImageWidth, dayFreqImageHeight));
private string BuildSearchProgressText(SearchProgressInfo progress)
{
if (progress.ShowCount && progress.TotalCount > 0)
{
return progress.Message + " " + progress.CompletedCount + "/" + progress.TotalCount;
}
return progress.Message;
}
private SearchProgressInfo CreateStageProgress(string message, double percent, bool isIndeterminate = false)
{
return new SearchProgressInfo
{
CompletedCount = 0,
TotalCount = 0,
Message = message,
Percent = percent,
IsIndeterminate = isIndeterminate,
ShowCount = false
};
}
private SearchProgressInfo CreateEventProgress(int completedCount, int totalCount, int stageIndex, int stageCount, string message)
{
if (totalCount <= 0)
{
return CreateStageProgress(message, SearchProgressQueryComplete);
}
var mes = results.Where(rs => rs.Energy >= MiddleEnergy).ToList();
//new ReportPlanImage().DrawPlanClipToFile(mes);
MiddleEnergyEvents = mes;
MiddleEventCount = mes.Count();
if (mes.Count > 0)
{
ReportPlanImage rpi = new ReportPlanImage();
//rpi.DrawPlanClipToDrawVisual(mes, (int)rView.canvasPlan.ActualWidth, (int)rView.canvasPlan.ActualHeight);
rpi.Draw(mes, rView.canvasPlan.ActualWidth, rView.canvasPlan.ActualHeight);
//rView.canvasPlan = rpi.host;
rView.canvasPlan.Children.Clear();
rView.canvasPlan.Children.Add(rpi.host);
int safeStageIndex = Math.Max(0, Math.Min(stageIndex, stageCount));
double eventProgress = (completedCount + safeStageIndex / (double)stageCount) / totalCount;
double percent = SearchProgressQueryComplete + eventProgress * (SearchProgressComputeComplete - SearchProgressQueryComplete);
int displayCount = Math.Min(completedCount + 1, totalCount);
CreateStereoChart(mes);
return new SearchProgressInfo
{
CompletedCount = displayCount,
TotalCount = totalCount,
Message = message,
Percent = percent,
IsIndeterminate = false,
ShowCount = true
};
}
}
//rView.canvasPlan.
//dayMiddleEventPlanBytes = new ReportPlanImage().DrawPlanClipToFile(mes);
private void ReportSearchProgress(IProgress<SearchProgressInfo> progress, SearchProgressInfo progressInfo)
{
if (progress != null)
{
progress.Report(progressInfo);
}
}
private static async Task YieldToUiAsync()
{
await Task.Delay(1);
}
});
}
/// <summary>
@ -833,25 +553,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
StereoChart.View3D.PointLineSeries3D.Add(plsEvent3d);
stereoChart.EndUpdate();
}
private Task<List<GridItemEventResult>> SearchEventsAsync(DateTime searchStartTime, DateTime searchEndTime, IProgress<SearchProgressInfo> progress)
{
return SearchEventsCoreAsync(searchStartTime, searchEndTime, progress);
}
public List<GridItemEventResult> SearchEvents(DateTime searchStartTime, DateTime searchEndTime)
{
var results = SearchEventsCore(searchStartTime, searchEndTime, null);
SearchCount = results.Count;
UpdateEnergyStats(results);
return results;
}
private List<GridItemEventResult> SearchEventsCore(DateTime searchStartTime, DateTime searchEndTime, IProgress<SearchProgressInfo> progress)
{
return SearchEventsCoreAsync(searchStartTime, searchEndTime, progress).GetAwaiter().GetResult();
}
private async Task<List<GridItemEventResult>> SearchEventsCoreAsync(DateTime searchStartTime, DateTime searchEndTime, IProgress<SearchProgressInfo> progress)
{
List<GridItemEventResult> results = new List<GridItemEventResult>();
string findStr = "select * from " + GlobalConfig.UseResultTable;
@ -892,23 +594,12 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
{
}
}
if (progress != null)
{
progress.Report(CreateStageProgress("正在查询事件数据...", 0, true));
}
var list = await Task.Run(() => fsqlTencent.Select<RemoteRealtimeResultEntity>()
.WithSql(findStr).ToList()).ConfigureAwait(false);
int totalCount = list == null ? 0 : list.Count;
ReportSearchProgress(progress, totalCount == 0
? CreateStageProgress("未查询到事件", 0)
: CreateEventProgress(0, totalCount, 0, 4, "正在准备事件"));
var list = fsqlTencent.Select<RemoteRealtimeResultEntity>()
.WithSql(findStr).ToList();
if (list != null)
{
int completedCount = 0;
const int eventStageCount = 4;
foreach (var item in list)
{
ReportSearchProgress(progress, CreateEventProgress(completedCount, totalCount, 0, eventStageCount, "正在准备事件"));
GridItemEventResult se = new GridItemEventResult(item, true);
string eventTimeStr = se.EventTime;
string datePath = eventTimeStr.Substring(0, 4) + eventTimeStr.Substring(5, 2) + eventTimeStr.Substring(8, 2);
@ -917,49 +608,39 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
+ eventTimeStr.Substring(8, 2) + eventTimeStr.Substring(10, 3)
+ eventTimeStr.Substring(14, 2) + eventTimeStr.Substring(17, 2) + ".01" + GlobalConfig.DataTypeString;
string jsonStr = ".json";
string jsonFilePath = dataFilePath + dataFileName + jsonStr;
MmEvent curMmEvent = new MmEvent();
curMmEvent.EventTimeStr = eventTimeStr;
curMmEvent.X = se.X;
curMmEvent.Y = se.Y;
curMmEvent.RMS = se.RMS;
curMmEvent.DominantFreq = 15;
bool canComputeWaveform = false;
//查询事件Json文件是否已下载
if (File.Exists(jsonFilePath))
if (File.Exists(dataFilePath + dataFileName + jsonStr))
{
FileInfo fileInfo = new FileInfo(jsonFilePath);
FileInfo fileInfo = new FileInfo(dataFilePath + dataFileName + jsonStr);
if (fileInfo.Length > 1024)
{
canComputeWaveform = true;
ComputeFM(curMmEvent);
//目前提取的为半周期
curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr);
}
}
else
{
#region 同步方式
ReportSearchProgress(progress, CreateEventProgress(completedCount, totalCount, 1, eventStageCount, "正在下载波形JSON"));
int res = await DownloadJsonFile.DownloadAsync(eventTimeStr, dataFilePath, dataFileName + jsonStr, GlobalConfig.UseWaveDataTable).ConfigureAwait(false);
int res = new DownloadJsonFile().Download(eventTimeStr, dataFilePath, dataFileName + jsonStr, GlobalConfig.UseWaveDataTable);
if (res > -1)
{
FileInfo fileInfo2 = new FileInfo(jsonFilePath);
FileInfo fileInfo2 = new FileInfo(dataFilePath + dataFileName + jsonStr);
if (fileInfo2.Length > 2000)
{
canComputeWaveform = true;
ComputeFM(curMmEvent);
//目前提取的为半周期
curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr);
}
}
#endregion
}
if (canComputeWaveform)
{
ReportSearchProgress(progress, CreateEventProgress(completedCount, totalCount, 1, eventStageCount, "正在读取波形JSON"));
JObject eventJson = ReadEventJsonRoot(jsonFilePath);
ReportSearchProgress(progress, CreateEventProgress(completedCount, totalCount, 2, eventStageCount, "正在计算震源机制"));
ComputeFM(curMmEvent, eventJson, jsonFilePath);
ReportSearchProgress(progress, CreateEventProgress(completedCount, totalCount, 3, eventStageCount, "正在计算主频"));
//目前提取的为半周期
curMmEvent.DominantFreq = GetDominFreq(eventJson);
}
Random dominRnd = new Random((int)DateTime.Parse(curMmEvent.EventTimeStr).Ticks);
int dominFreq = (int)curMmEvent.DominantFreq;
@ -972,62 +653,11 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
se.Direction = curMmEvent.Direction;
se.SetEnergy();
results.Add(se);
ReportSearchProgress(progress, CreateEventProgress(completedCount, totalCount, eventStageCount, eventStageCount, "正在整理事件结果"));
completedCount++;
}
}
SearchCount = results.Count;
return results;
}
private void UpdateEnergyStats(List<GridItemEventResult> results)
{
if (results == null || results.Count == 0)
{
TotalEnergy = 0;
AverageEnergy = 0;
MaxEnergy = 0;
return;
}
TotalEnergy = Math.Round(results.Sum(rs => rs.Energy), 2);
AverageEnergy = Math.Round(results.Average(rs => rs.Energy), 2);
MaxEnergy = Math.Round(results.Max(rs => rs.Energy), 2);
}
private JObject ReadEventJsonRoot(string jsonFilePath)
{
using (StreamReader sr = System.IO.File.OpenText(jsonFilePath))
{
JsonTextReader reader = new JsonTextReader(sr);
JArray jArray = (JArray)JToken.ReadFrom(reader);
return (JObject)jArray[0];
}
}
private int GetDominFreq(JObject eventJson)
{
int dominantFreq = 0;
List<double> dominantFreqList = new List<double>();
JArray phaseArr = JArray.FromObject(eventJson["phases"]);
for (int i = 0; i < phaseArr.Count; i++)
{
if (phaseArr[i]["zcr"] != null)
{
dominantFreqList.Add(double.Parse(phaseArr[i]["zcr"].ToString()));
}
}
if (dominantFreqList.Count > 3)
{
double min = dominantFreqList.Min();
double max = dominantFreqList.Max();
dominantFreqList.Remove(min);
dominantFreqList.Remove(max);
dominantFreq = (int)(dominantFreqList.Sum() / dominantFreqList.Count);
}
return dominantFreq;
}
public void ExportEventListReport(ReportView rView)
{
@ -1511,30 +1141,6 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
mmEvent.FocalType = cr.FocalType;
mmEvent.Direction = cr.Direction;
}
public void ComputeFM(MmEvent mmEvent, JObject eventJson, string jsonFilePath)
{
mmEvent.JsonFile = jsonFilePath;
mmEvent.SetEnergy();
mmEvent.Phases = new Dictionary<string, int>();
JArray phaseArr = JArray.FromObject(eventJson["phases"]);
for (int i = 0; i < phaseArr.Count; i++)
{
if (phaseArr[i]["first_motion_direct"] != null)
{
mmEvent.Phases.Add(phaseArr[i]["id"].ToString().Substring(3, 3),
int.Parse(phaseArr[i]["first_motion_direct"].ToString()));
}
}
FMMap fmMap = CreateFM(mmEvent, GlobalConfig.ProjectConfig.WorkArea.EMin, GlobalConfig.ProjectConfig.WorkArea.NMin);
ComputationResult cr = GlobalConfig.fmCore.ComputeResult(fmMap);
if (cr == null)
return;
mmEvent.FocalType = cr.FocalType;
mmEvent.Direction = cr.Direction;
}
public FMMap CreateFM(MmEvent mmEvent, double BaseX, double BaseY)
{
FMMap fmMap = new FMMap();

@ -43,6 +43,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
/// 当前采样数
/// </summary>
public int CurPoints;
private DispatcherTimer _fitYTimer;
private readonly IEventAggregator _ea;
private readonly ISearchMsEventBLL _searchMsEventBLL;
private int _selectResult = 0;
@ -57,12 +58,17 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
}
int _channelCount = 60; // Channel count.
double _samplingFrequency = 500; // Sampling frequency (Hz).
double _xLength = 10; // X axis length.
double _previousX = 0; // Latest X value on axis.
long _now; // Latest time stamp.
long _startTicks = DateTime.Now.Ticks; // Controls timing.
long _startTicks; // Controls timing.
long _samplesOutput; // Generated samples quantity.
private volatile bool _stop = false; // Stops thread work.
// Constants
const double YMin = 30000; // Minimal y-value.
const double YMax = 33000; // Maximal y-value.
private volatile bool _stop; // Stops thread work.
internal bool IsRunning
{
get
@ -76,12 +82,15 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
/// Thread.
/// </summary>
private Thread _thread;
private Thread _threadWrite;
private delegate void ChartUpdateFromThreadHandler(double[][] samples);
private ChartUpdateFromThreadHandler _chartUpdate;
private Random _rand = new Random((int)DateTime.Now.Ticks);
#region "属性"
private int _lChartCount = 1;
/// <summary>
@ -183,6 +192,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
/// 文件数据位置
/// </summary>
public string FileDataPath { get; set; } = @"D:\TaySystemPath\Downloads";
private string _cachePath;
private int _cacheSize;
/// <summary>
@ -255,6 +265,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
set { gridChart = value; }
}
private string _btnContrlContent = "开始";
private int channelCount;
public string BtnContrlContent
{
@ -270,7 +281,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
SetProperty(ref _showEvents, value);
}
}
StationWorkModel _stationWorker = new StationWorkModel();
StationWorkModel _stationWorker;
public List<StationModel> smList;
//public static readonly DependencyProperty XAxesProperty =
@ -444,6 +455,8 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
}
private void UpdateChartData()
{
double yRange = YMax - YMin;
double[][] multiChannelData = new double[smList.Count * 3][];
try
{
@ -467,6 +480,10 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
public void UpdateWavesFromTxt(string fn)
{
string allStr;
string sn = "";//0
int points = 0;//1
int samp = 500;//2
string startTime = "";//3;4,5,6=null
smList = new List<StationModel>();
using (StreamReader streamReader = new StreamReader(fn))
@ -476,6 +493,9 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
if (allStr.Length > 0)
{
string[] strLines = allStr.Trim().Split(new char[] { '\n' });
List<string> strList = strLines.ToList();
int cnt = strList.Count;
int num = 0;
string[] snStr = strLines[0].Trim().Split(',');
string tmpName = snStr[0].Substring(14, 3);
CurPoints = int.Parse(snStr[1].Trim().Split(' ')[0]);
@ -893,6 +913,8 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
}
private void ThreadLoop()
{
int sm = 0;
while (_stop == false)
{
@ -919,6 +941,7 @@ namespace Txgy.EWS.Client.PageModule.ViewModels
if (sampleBundleToGenerate > 0)
{
//YMax = tmps.Max();
double yRange = YMax - YMin;
double[][] multiChannelData = new double[_channelCount][];

@ -36,7 +36,7 @@ namespace Txgy.EWS.Client.PageModule.Views
{
Dispatcher _dispatcher;
private readonly IEventAggregator _ea;
private readonly VisualHost host = new VisualHost();
private VisualHost host;
public TransformGroup transGroup;
private delegate void HandleDataGeneratedDelegate(List<GridItemEventResult> results, double dw, double dh, int ts, DateTime inTime);
/// <summary>
@ -67,6 +67,7 @@ namespace Txgy.EWS.Client.PageModule.Views
double drawUnit = 1;
Point _downPoint = new Point(0, 0);
bool _isMoving = false;
double left = 0, top = 0;
public bool IsShowGridText = true;
public bool IsShowGrid = true;
public System.Windows.Media.Color BackGroundColor = System.Windows.Media.Colors.White;
@ -108,7 +109,6 @@ namespace Txgy.EWS.Client.PageModule.Views
rpi.Draw(null, canvas.Width, canvas.Height);
//host = new VisualHost();
canvas.Children.Add(rpi.host);
canvas.Children.Add(host);
baseX = GlobalConfig.ProjectConfig.WorkArea.EMin;
baseY = GlobalConfig.ProjectConfig.WorkArea.NMin;
@ -1034,6 +1034,8 @@ namespace Txgy.EWS.Client.PageModule.Views
transform.Y += position.Y - this.previousMousePoint.Y;
this.previousMousePoint = position;
}
private ListBoxItem _lastSelectedItem;
private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//if (ReceivedEventListBox.SelectedItem == null && _lastSelectedItem != null)

@ -35,7 +35,7 @@ namespace Txgy.EWS.Client.PageModule.Views
{
Dispatcher _dispatcher;
private readonly IEventAggregator _ea;
private readonly VisualHost host = new VisualHost();
private VisualHost host;
public TransformGroup transGroup;
private delegate void HandleDataGeneratedDelegate(List<GridItemEventResult> results, double dw, double dh,int ts,DateTime inTime);
/// <summary>
@ -65,6 +65,7 @@ namespace Txgy.EWS.Client.PageModule.Views
double drawUnit = 1;
Point _downPoint = new Point(0, 0);
bool _isMoving = false;
double left = 0, top = 0;
public bool IsShowGridText = true;
public bool IsShowGrid = true;
public System.Windows.Media.Color BackGroundColor = System.Windows.Media.Colors.White;
@ -104,7 +105,6 @@ namespace Txgy.EWS.Client.PageModule.Views
rpi.Draw(null, canvas.Width, canvas.Height);
//host = new VisualHost();
canvas.Children.Add(rpi.host);
canvas.Children.Add(host);
baseX = GlobalConfig.ProjectConfig.WorkArea.EMin;
baseY = GlobalConfig.ProjectConfig.WorkArea.NMin;

@ -68,6 +68,7 @@ namespace Txgy.EWS.Client.PageModule.Views
double drawUnit = 1;
Point _downPoint = new Point(0, 0);
bool _isMoving = false;
double left = 0, top = 0;
public bool IsShowGridText = true;
public bool IsShowGrid = true;
public System.Windows.Media.Color BackGroundColor = System.Windows.Media.Colors.White;

@ -56,6 +56,7 @@ namespace Txgy.EWS.Client.PageModule.Views
{
Dispatcher _dispatcher;
private readonly IEventAggregator _ea;
private readonly ISearchMsEventBLL searchMsEventBLL;
IFreeSql fsqlSqLite = FreeSqlLocalSqLite.freeLocalSqLite;
//private readonly IRemoteDownloadDataBLL remoteDownloadDataBLL;
@ -64,7 +65,7 @@ namespace Txgy.EWS.Client.PageModule.Views
/// Delegate for data generation.
/// </summary>
private HandleDataGeneratedDelegate _handleDataGenerated;
private readonly VisualHost host = new VisualHost();
private VisualHost host;
public TransformGroup transGroup;
double width = 700;
double height = 700;
@ -82,9 +83,12 @@ namespace Txgy.EWS.Client.PageModule.Views
public double stationFontSize = 10;
double baseX = 39701000;
double baseY = 4352000;
double xDrawUnit = 1;
double yDrawUnit = 1;
double drawUnit = 1;
Point _downPoint = new Point(0, 0);
bool _isMoving = false;
double left = 0, top = 0;
public bool IsShowGridText = true;
public bool IsShowGrid = true;
public System.Windows.Media.Color BackGroundColor = System.Windows.Media.Colors.White;
@ -126,7 +130,6 @@ namespace Txgy.EWS.Client.PageModule.Views
//rpi.DrawPlanClipToDrawVisual(mes, (int)rView.canvasPlan.ActualWidth, (int)rView.canvasPlan.ActualHeight);
rpi.DrawGier(null, width, height);
canvas.Children.Add(rpi.host);
canvas.Children.Add(host);
_handleDataGenerated = new HandleDataGeneratedDelegate(rpi.DrawGier);

@ -37,6 +37,9 @@ namespace Txgy.EWS.Client.PageModule.Views
IFreeSql fsqlTencent = FreeSqlTencent.tencentRemoteMySQL;
ReportFreqImage reportImage = new ReportFreqImage();
CultureInfo culture = new CultureInfo("zh-CN");
byte[] dayFreqBytes = null;
byte[] dayMiddleEventPlanBytes = null;
byte[] dayMiddleEventStereoBytes = null;
public string dayFreqImagePath;
public int dayFreqImageWidth = 1485;
public int dayFreqImageHeight = 585;

File diff suppressed because it is too large Load Diff

@ -19,9 +19,7 @@ namespace Txgy.EWS.Client.SysModule.ViewModels
{
public string Title => "系统更新文件上传";
#pragma warning disable CS0067
public event Action<IDialogResult> RequestClose;
#pragma warning restore CS0067
public bool CanCloseDialog() => true;

@ -50,7 +50,7 @@ namespace Txgy.EWS.Client.Upgrade.DAL
return true;
}
catch (Exception)
catch (Exception ex)
{
return false;
}

Loading…
Cancel
Save