You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2681 lines
104 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// <copyright file="FormMain.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
#define WELLPOLE_MODULE
using DevExpress.Mvvm.Native;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraBars.Docking2010.Views;
using DevExpress.XtraBars.Docking2010.Views.Tabbed;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using FlexenabledLic;
using GeoSigma.SigmaDrawerUtil;
using GeoSigma.UCDraw;
using GeoSigma.UCDraw.WellAndSection;
using GeoSigmaDrawLib;
using InterfaceWorkAreaData;
using IPCLib;
using Newtonsoft.Json;
using NPOI.HPSF;
using SigmaDrawerElement;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Xml;
using UCDraw;
using WellWorkDataUI;
using WorkData;
using WorkData.Entity;
namespace PcgDrawR
{
/// <summary>
/// 软件主窗体.
/// </summary>
public partial class FormMain : RibbonForm
{
/// <summary>
/// Tab 页签最长长度
/// </summary>
private const int TABMAXLENGTH = 10;
private readonly string fileLayout = Path.Combine(Application.StartupPath, "WellSectionlayout.xml");
private readonly string workspaceName1 = "MyLayout";
private readonly LicHelp licHelp;
// 启动参数
private readonly string startFile = string.Empty;
private readonly List<string> lstArgs = new List<string>();
private bool batchSetZColorFlag = false;
private Security security;
private bool isDQLogin = false;
private bool isLogin = false;
/// <summary>
/// Gets or sets the z color width.
/// </summary>
public double ZColorWidth { get; set; } = 25;
private RecentFileConfig recentConfig = null;
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", EntryPoint = "FreeLibrary", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
public TabbedView tabbedView { get => tabbedView1; }
private static void ValidateDll(string dllName)
{
string dllPath = Path.Combine(Application.StartupPath, dllName);
IntPtr hModule = IntPtr.Zero;
try
{
hModule = LoadLibrary(dllPath);
if (hModule == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (hModule != IntPtr.Zero)
{
FreeLibrary(hModule);
}
}
}
private string lastOpenProjectFile = string.Empty;
private string currentProjectFile = string.Empty;
string m_workAreaPath = "";
public static bool s_bOpenWorkArea = false;
public bool m_IsOpenWorkArea
{
set
{
//m_IsOpenWorkArea = value;
s_bOpenWorkArea = value;
}
get
{
return s_bOpenWorkArea;
}
}
/// <summary>
///
/// Initializes a new instance of the <see cref="FormMain"/> class.
/// </summary>
///
//public TcpManager m_KepServer;
// public PipeManager m_KepPipe;
//public string m_KepPipeId = "";
// public int m_KepPort = 0;
public MmfCommunication m_Mmf;
public string m_KepMmfId = "";
public bool m_bSlave = false; //是否作为子进程启动
string m_newWellName = "";
string m_newWellsSection = "";
private DevExpress.XtraBars.BarStaticItem CommnicationInfo;
private DevExpress.XtraBars.BarStaticItem dbInfo;
public FormMain()
{
InitializeComponent();
CommnicationInfo = new BarStaticItem();
CommnicationInfo.Id = 1001;
CommnicationInfo.Name = "Info1";
this.ribbonStatusBar1.ItemLinks.Add(this.CommnicationInfo, true);
CommnicationInfo.Caption = "状态:";
dbInfo = new BarStaticItem();
dbInfo.Id = 1002;
dbInfo.Name = "dbInfo";
this.ribbonStatusBar1.ItemLinks.Add(this.dbInfo, true);
dbInfo.Caption = "当前工区:";
//#if !DEBUG // 或更安全的方式
// if (!DesignMode)
//#endif
{
this.imageCollectionWellMapTree.Images.SetKeyName(0, "tableofcontent_32x32.png");
this.imageCollectionWellMapTree.Images.SetKeyName(1, "alignfloatingobjecttopleft_32x32.png");
this.imageCollectionWellMapTree.Images.SetKeyName(2, "article_32x32.png");
this.imageCollectionWellMapTree.Images.SetKeyName(3, "open_32x32.png");
}
// this.imageCollectionWellMapTree.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("imageCollectionWellMapTree.ImageStream")));
btnNewWellSection.Enabled = false;
m_IsOpenWorkArea = false;
GeoSigmaWellPoleXY.ReadParamsFile();
this.wellDataTreeList.OnNewWellCreated += CreateNewWell;
this.WellMaptreeList.m_ParentForm = this;
tabbedView1.Ribbon = this.ribbonControl1;
tabbedView1.InvalidDocumentTypes.Add(
typeof(DevExpress.XtraBars.Docking.FloatForm));
licHelp = new LicHelp("KEPlatform");
// 属性面板关闭时,将主菜单开关闭“属性”按钮设置为 unchecked
dckPanelProperty.ClosedPanel += (sender, e) =>
{
btnViewProperty.Checked = false;
};
// 关闭图层时把对应属性改为 unchecked
dockPaneWellTableTree.ClosedPanel += (sender, e) =>
{
btnViewWorkArea.Checked = true;
dockPanelMapLib.Visibility = DockVisibility.Hidden;
};
dockPanelMapLib.ClosedPanel += (sender, e) =>
{
btnViewWorkArea.Checked = true;
dockPaneWellTableTree.Visibility = DockVisibility.Hidden;
};
// 关闭统计元素时把对应属性改为 unchecked
//dckPanelStatic.ClosedPanel += (sender, e) =>
//{
// btnViewStatic.Checked = false;
//};
ribbonControl1.OptionsMenuMinWidth = 0;
KeyPreview = true;
//m_workAreaPath = "D:\\kev\\20250330";
workAreaDb.Instance.Connected("", eDataSourceType.empty);
this.wellDataTreeList.ParentForm = this;
this.wellDataTreeList.tabbedView = this.tabbedView;
// Batteries.Init();
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.S && e.Modifiers == Keys.Control)
{
CurrentForm.SaveFile();
}
else if (e.KeyCode == Keys.O && e.Modifiers == Keys.Control)
{
btnFileOpen_ItemClick(this, null);
}
else if (e.KeyCode == Keys.N && e.Modifiers == Keys.Control)
{
btnFileNew_ItemClick(this, null);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="FormMain"/> class.
/// </summary>
/// <param name="args">参数 /ZC-按块显示散点Z值</param>
public FormMain(string[] args)
: this()
{
//if (args.Length > 0)
//{
// this.startFile = args[0].Trim();
//}
bbtnMeshAntiAlias.Checked = DrawerGlobalConfig.Instance.MeshNode.AntiAliasingEnable;
ribbonControl1.OptionsMenuMinWidth = 0;
//string executablePath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
//string vtkPath = "vtk";
//string combinedPath = Path.Combine(executablePath, vtkPath);
//GeoSigmaLib.SetDllDirectory(combinedPath);
DrawerConfig.Instance.SetConfigValue("MultiView", "OnSynchronize", false);
string workAreaPath = "";
// m_KepPort = 0;
if (args.Length > 1)
{
lstArgs.Clear();
for (int i = 0; i < args.Length; i++)
{
lstArgs.Add(args[i]);
string[] tstrs = args[i].Split('=');
if(tstrs.Length == 2)
{
if (tstrs[0] == "workAreaPath")
{
workAreaPath = tstrs[1];
OpenWorkData(workAreaPath);
m_bSlave = true;
}
else if (tstrs[0] == "port")
{
//if(Int32.TryParse(tstrs[1],out m_KepPort))
//{
// m_bSlave = true;
//}
}
else if (tstrs[0] == "newWell")
{
m_newWellName = tstrs[1];
}
else if (tstrs[0] == "newWellsSection")
{
m_newWellsSection = tstrs[1];
}
else if (tstrs[0] == "PipeId")
{
//m_KepPipeId = tstrs[1];
//m_bSlave = true;
}
else if (tstrs[0] == "MemoryId")
{
m_KepMmfId = tstrs[1];
}
}
}
}
if(m_bSlave)
{
//ribbonPageWorkArea.ItemLinks.Add(barBtnItemNewWorkArea);
//ribbonPageWorkArea.ItemLinks.Add(barBtnItemOpenWorkArea);
ribbonPageWorkArea.ItemLinks.Remove(barBtnItemNewWorkArea);
ribbonPageWorkArea.ItemLinks.Remove(barBtnItemOpenWorkArea);
dockPaneWellTableTree.Visibility = DockVisibility.Hidden;
//panelContainer2.Controls.Remove(dockPaneWellTableTree);
//panelContainer1.Controls.Add(dockPaneWellTableTree);
//dockManager1.RootPanels.RemoveAt(0);
}
}
async void StartConnectKep()
{
try
{
//m_KepServer = new TcpManager { LocalIdentity = "WellPole" };
//m_KepServer.PacketReceived += OnPacketReceived;
//m_KepServer.Connected += OnConnected;
//m_KepServer.Disconnected += OnDisconnected;
//m_KepServer.ErrorOccurred += OnErrorOccurred;
//await m_KepServer.StartClientAsync("127.0.0.1", m_KepPort);
//m_KepPipe = new PipeManager(m_KepPipeId, false);
//m_KepPipe.MessageReceived += OnPipeMessageReceived;
//m_KepPipe.ConnectionStatusChanged += OnPipeStatusChanged;
//m_KepPipe.HeartbeatTimeout += OnPipeHeartbeatTimeout;
//m_KepPipe.StartAsync();
m_Mmf = new MmfCommunication(m_KepMmfId, false, "WellPole");
m_Mmf.DataReceived += OnMmfDataReceived;
m_Mmf.Connected += OnMmfConnected;
m_Mmf.Disconnected += OnMmfDisconnected;
m_Mmf.ErrorOccurred += OnMmfError;
await m_Mmf.StartAsync();
}
catch(Exception ex)
{
}
}
/// <summary>
/// 当前激活的文档
/// </summary>
private WellPoleUCDrawEdit CurrentForm
{
get
{
if (this.tabbedView1.ActiveDocument != null)
{
return tabbedView1.ActiveDocument.Control as WellPoleUCDrawEdit;
}
else if (this.tabbedView1.ActiveFloatDocument != null)
{
return tabbedView1.ActiveFloatDocument.Control as WellPoleUCDrawEdit;
}
return null;
}
}
/// <summary>
/// DrawerGlobalConfig
/// </summary>
public DrawerGlobalConfig DrawerGlobalConfig { get; set; } = DrawerGlobalConfig.Instance;
private FileDropHandler fileDroper;
/// <summary>
/// Forms the main_ load.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private async void FormMain_Load(object sender, EventArgs e)
{
try
{
if (Security.CurentLicenseInfo.IsNetServer == true)
{
this.isLogin = false;
await this.setLoginStatusAsync();
}
else
{
this.isLogin = true;
}
this.security = new Security();
this.security.LicenseInvalidateEvent += async (status, message) =>
{
this.isLogin = status == 1;
await this.setLoginStatusAsync();
};
this.security.CheckLicense(this); //ggff1974
}
catch
{
MessageBox.Show(" lic error 请联系服务人员!"); ////ggff1974
Application.Exit();
}
fileDroper = new FileDropHandler(this);
try
{
// Disable layout load animation effects
workspaceManager1.AllowTransitionAnimation = DevExpress.Utils.DefaultBoolean.False;
WorkspaceManager.SetSerializationEnabled(this.ribbonControl1, false);
// Load DevExpress controls' layouts from a file
if (workspaceManager1.LoadWorkspace(workspaceName1, fileLayout, true))
{
workspaceManager1.ApplyWorkspace(workspaceName1);
// this.dckPanelLayer.Text = "图层";
}
InitRecentConfig();
}
finally
{
this.licHelp.DoLogin();
}
CheckEnvironment();
}
private async Task setLoginStatusAsync()
{
bool isLoggedIn = this.isDQLogin && this.isLogin;
string tooltipText = isLoggedIn ? "已登录" : "未登录";
string resourceName = isLoggedIn
? "bsiLoginInfo.ImageOptions.SvgImage"
: "bsiLoginInfo.ImageOptions.DisabledSvgImage";
// 更新非资源依赖的UI部分
this.bsiLoginInfo.Enabled = true;
// ((ToolTipItem)this.bsiLoginInfo.SuperTip.Items[0]).Text = tooltipText; //ggff
// 异步加载资源
var resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
var svgImage = await Task.Run(() => resources.GetObject(resourceName));
// 回到UI线程更新图像实际上await会自动回到UI线程
this.bsiLoginInfo.ImageOptions.SvgImage = (DevExpress.Utils.Svg.SvgImage)svgImage;
}
/// <summary>
/// Forms the main_ shown.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void FormMain_Shown(object sender, EventArgs e)
{
LoadStartFile();
//SplashScreenManager.CloseForm(true);
ribbonStatusBar1.Visible = true;
}
/// <summary>
/// Inits the recent config.
/// </summary>
private void InitRecentConfig()
{
recentConfig = new RecentFileConfig();
this.ResetOpenMenu();
}
/// <summary>
/// 加载启动参数指定的文件async
/// </summary>
private void LoadStartFile()
{
if (string.IsNullOrEmpty(this.startFile))
{
return;
}
string ext = Path.GetExtension(this.startFile);
if (this.lstArgs.Count > 0)
{
string strVtk = this.lstArgs.Find(it => { return it.ToUpper().StartsWith("/VTK"); });
if (ext == ".xyz" && !string.IsNullOrEmpty(strVtk))
{
//OpenVtkView();
return;
}
string strZC = this.lstArgs.Find(it => { return it.ToUpper().StartsWith("/ZC"); });
if (!string.IsNullOrEmpty(strZC))
{
int nSizeIndex = strZC.IndexOf(':');
if (nSizeIndex > 0)
{
ZColorWidth = Convert.ToInt32(strZC.Substring(nSizeIndex + 1));
}
//string ext = Path.GetExtension(this.startFile);
//if(ext == ".xyz")
//{
batchSetZColorFlag = true;
//}
OpenFile(this.startFile, true);
this.lstArgs.Clear();
}
}
else
{
OpenFile(this.startFile);
}
}
/// <summary>
/// Forms the main_ form closed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
{
//Save DevExpress controls' layouts to a file
workspaceManager1.CaptureWorkspace(workspaceName1, true);
workspaceManager1.SaveWorkspace(workspaceName1, fileLayout, true);
licHelp.LogOut();
}
/// <summary>
/// 合并子窗体控件
/// </summary>
/// <param name="sender">ribbon控件</param>
/// <param name="e">事件参数</param>
private void ribbonControl1_Merge(object sender, DevExpress.XtraBars.Ribbon.RibbonMergeEventArgs e)
{
//RibbonControl parentRRibbon = sender as RibbonControl;
RibbonControl childRibbon = e.MergedChild;
childRibbon.Dock = DockStyle.None;
if (childRibbon.Parent is WellPoleUCDrawEdit)
{
WellPoleUCDrawEdit child = childRibbon.Parent as WellPoleUCDrawEdit;
child.ViewGroupVisible = false;
child.MergePanels();
if (btnViewProperty.Checked != child.PropertyPanelVisible)
{
btnViewProperty.Checked = child.PropertyPanelVisible;
}
//if (btnViewWorkArea.Checked != child.PropertyPanelVisible)
//{
// btnViewWorkArea.Checked = child.PropertyPanelVisible;
//}
//if (btnViewStatic.Checked != child.StatisticPanelVisible)
//{
// btnViewStatic.Checked = child.StatisticPanelVisible;
//}
}
}
/// <summary>
/// ribbons the control1_ un merge.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void ribbonControl1_UnMerge(object sender, RibbonMergeEventArgs e)
{
try
{
RibbonControl childRibbon = e.MergedChild;
if (childRibbon.Parent is WellPoleUCDrawEdit)
{
WellPoleUCDrawEdit child = childRibbon.Parent as WellPoleUCDrawEdit;
child.UnMergePanels();
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}
/// <summary>
/// ribbons the control1_ show customization menu.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void ribbonControl1_ShowCustomizationMenu(object sender, RibbonCustomizationMenuEventArgs e)
{
e.ShowCustomizationMenu = false;
}
/// <summary>
/// 激活图件
/// </summary>
/// <param name="fullFile">名称</param>
private bool ActiveDoc(string fullFile)
{
BaseDocument frmDoc =
this.docManager.View.Documents.FirstOrDefault(it =>
{
if (it.Control is WellPoleUCDrawEdit child)
{
if (fullFile.Equals(child.FileFullName, StringComparison.CurrentCultureIgnoreCase))
{
return true;
}
}
return false;
});
if (frmDoc != null)
{
this.docManager.View.Controller.Activate(frmDoc);
return true;
}
return false;
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="sender">事件按钮</param>
/// <param name="e">事件参数</param>
private void btnFileOpen_ItemClick(object sender, ItemClickEventArgs e)
{
string[] fileNames = DocHelper.SelectMutiFiles();
foreach (var item in fileNames)
{
if (!string.IsNullOrEmpty(item))
{
OpenFile(item);
}
}
}
private void TryRecoverFileWhenUnexpectedShutdown(WellPoleUCDrawEdit drawEdit, string filePath)
{
if (GeoSigmaXY.SigmaDocBackupExists(filePath))
{
var result = MessageBox.Show("检测到文件异常关闭,是否恢复?", "恢复选项"
, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result == DialogResult.OK)
{
drawEdit.DrawerView.ViewControl.Drawer.RecoverMode = true;
}
}
}
public static XmlDocument SafeLoadXml(string filePath)
{
try
{
// 方法 1优先让 XmlReader 自动处理(推荐)
var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var reader = XmlReader.Create(fs, new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit, // 安全起见禁用 DTD
IgnoreWhitespace = true
});
var doc = new XmlDocument();
doc.Load(reader);
return doc;
}
catch (XmlException ex)
{
// 如果自动检测失败,尝试 GB2312备用方案
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var sr = new StreamReader(filePath, Encoding.GetEncoding("GB2312"));
var doc = new XmlDocument();
doc.Load(sr);
return doc;
}
catch
{
throw new InvalidOperationException($"无法解析 XML 文件: {ex.Message}", ex);
}
}
return null;
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="strFile">文件路径</param>
/// <param name="setZColor">是否以方块方式显示散点数据</param>
//private Task<bool> OpenFile(string strFile, bool setZColor = false)
public bool OpenFile(string strFile, bool bInMapLib = false, bool setZColor = false)
{
// 已存在的文件仅激活
if (this.ActiveDoc(strFile))
{
return true;
//return Task.FromResult(true);
}
try
{
bool bOpend = false;
GeoSigmaXY.eViewType tType = GeoSigmaXY.eViewType.plane;
try
{
XmlDocument xmldoc = SafeLoadXml(strFile);
// XmlDocument xmldoc = new XmlDocument();
// xmldoc.Load(strFile);
if (xmldoc != null)
{
XmlNode wellNode = xmldoc.SelectSingleNode("Pcg/WellColumn");
XmlNode wellSectionNode = xmldoc.SelectSingleNode("Pcg/CrossSection");
if (wellNode != null)
tType = GeoSigmaXY.eViewType.wellpole;
if (wellSectionNode != null)
tType = GeoSigmaXY.eViewType.wellsection;
}
}
catch
{
tType = GeoSigmaXY.eViewType.plane;
}
WellPoleUCDrawEdit drawerChild = new WellPoleUCDrawEdit(tType);
drawerChild.bMapLibDoc = bInMapLib;
drawerChild.OnSaveFileToWorkArea += this.SaveFileToWorkArea;
drawerChild.OpenNewFile += OnOpenNewFile;
if (batchSetZColorFlag)
{
drawerChild.BatchSetZColorFlag = batchSetZColorFlag;
batchSetZColorFlag = !batchSetZColorFlag;
}
// drawerChild.LayerPanel = this.dckPanelLayer;
drawerChild.PropertyPanel = this.dckPanelProperty; //属性面板替换
drawerChild.ElePropertyPanel = this.dockElePanel;
// drawerChild.CreateMapPanel = this.dcpCreateMap;
// drawerChild.StatisticPanel = this.dckPanelStatic;
drawerChild.DrawerStatusBar = this.ribbonControl1.StatusBar;
TryRecoverFileWhenUnexpectedShutdown(drawerChild, strFile);
splashScreenManager1.ShowWaitForm();
splashScreenManager1.SetWaitFormDescription("正在打开文件...");
this.SuspendLayout();
// drawerChild.ribbonMain.Visible = false;
drawerChild.ZColorWidth = this.ZColorWidth;
drawerChild.EnableMeshPack = DrawerGlobalConfig.Instance.MeshNode.AntiAliasingEnable;
bOpend = drawerChild.OpenFile(strFile, setZColor, tType);
if (bOpend == false)
{
splashScreenManager1.CloseWaitForm();
// frmChild.Close();
MessageBox.Show($"打开文件{strFile}失败", "打开");
//return Task.FromResult(false);
return false;
}
var doc = this.tabbedView1.AddDocument(drawerChild);
// 标签页上显示短名称
doc.Caption = TabName(drawerChild.Text);
// 光标移动上去时显示全名
if (doc is Document document)
{
document.Tooltip = drawerChild.Text;
}
this.ribbonControl1.MergeRibbon(drawerChild.ribbonMain, false);
drawerChild.NewFileSavedEvent += new NewFileSavedHandler((fileName) =>
{
SetRecent(fileName);
});
// drawerChild.DrawerView.ViewControl.Drawer.SetVtkMainMeshEvent += new SetVtkMainMeshHandler((filePath, pMesh) =>
//{
// SetVtkMainMesh(filePath, pMesh);
//});
// drawerChild.ShowVtkEvent += new ShowVtkEventHandler(ShowVtkHandler);
// drawerChild.CloseVtkEvent = new CloseVtkHandler(CloseVtkHandler);
SetRecent(strFile);
splashScreenManager1.CloseWaitForm();
#if DEBUG
this.TestEventHandler(drawerChild);
#endif
//return Task.FromResult(true);
// drawerChild.DrawerView.ViewControl.InitStratumDivisionData(); //ggff 先这样
return true;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
//return Task.FromResult(false);
return false;
}
finally
{
this.ResumeLayout();
}
}
/// <summary>
/// 获取 Tab 页显示名称,如果太长会被截断,防止一个标签页占非常长的位置
/// </summary>
/// <param name="caption">要显示的目标名称</param>
/// <returns>最终会被显示的名称</returns>
private string TabName(string caption)
{
return caption.Length > TABMAXLENGTH ? caption.Substring(0, TABMAXLENGTH) : caption;
}
/// <summary>
/// Tests the event handler.
/// </summary>
/// <param name="editor">The editor.</param>
private void TestEventHandler(WellPoleUCDrawEdit editor)
{
editor.DrawerView.InsertCommonCommand("克隆到其它井组",
new EventHandler((obj, args) =>
{
SelectedElementsArgs selArgs = args as SelectedElementsArgs;
if (selArgs == null)
{ return; }
List<SigmaDrawerElement.DrawerElementProperty> elements = selArgs.Elements;
if (elements != null)
{
//editor.DrawerView.GetSelectedElements()[0];
foreach (DrawerElementProperty ele in elements)
{
//ele.Element
//strbContent.AppendLine(ele.Element.ToDfdString());
}
}
}), true, DrawElementType.ELEMENT_WELL_GROUP);
}
private int documentIndex = 0;
/// <summary>
/// 新建文件
/// </summary>
/// <param name="sender">按钮</param>
/// <param name="e">事件参数</param>
private void btnFileNew_ItemClick(object sender, ItemClickEventArgs e)
{
CreateNewWell("");
}
/// <summary>
/// Files the closed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void FileClosed(object sender, EventArgs e)
{
if (sender is WellPoleUCDrawEdit child)
{
child.ShowStatisticResult -= ShowStatic;
}
}
/// <summary>
/// 显示统计面板.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void ShowStatic(object sender, EventArgs e)
{
try
{
// this.dckPanelStatic.Visibility = DockVisibility.Visible;
}
finally
{
}
}
/// <summary>
/// Sets the recent.
/// </summary>
/// <param name="file">The file.</param>
private void SetRecent(string file)
{
if (string.IsNullOrEmpty(file))
{
return;
}
if (this.recentConfig.AddTop(file) == false)
{
return;
}
ResetOpenMenu();
this.recentConfig.Save();
}
/// <summary>
/// Resets the open menu.
/// </summary>
private void ResetOpenMenu()
{
this.ppmOpen.ClearLinks();
for (int i = 0; i < this.recentConfig.Files.Count; i++)
{
string strFile = this.recentConfig.Files[i];
BarButtonItem item = new BarButtonItem();
item.Caption = strFile;
item.ImageOptions.Image = imgsMain.Images["fileNew"];
item.ItemClick += new ItemClickEventHandler(async (object sender, ItemClickEventArgs e) =>
{
OpenFile(strFile);
});
this.ppmOpen.AddItem(item);
}
}
/// <summary>
/// 保存文件
/// </summary>
/// <param name="sender">按钮</param>
/// <param name="e">事件参数</param>
private void btnSaveMain_ItemClick(object sender, ItemClickEventArgs e)
{
if (CurrentForm == null)
{
return;
}
if (CurrentForm.SaveFile())
{
SetRecent(CurrentForm.FileFullName);
}
}
/// <summary>
/// 另存为
/// </summary>
/// <param name="sender">事件按钮</param>
/// <param name="e">事件参数</param>
private void btnSaveAs_ItemClick(object sender, ItemClickEventArgs e)
{
if (CurrentForm == null)
{
return;
}
if (CurrentForm.SaveAs())
{
SetRecent(CurrentForm.FileFullName);
}
}
/// <summary>
/// 符号管理
/// </summary>
/// <param name="sender">按钮</param>
/// <param name="e">事件参数</param>
private void btnSymbolManager_ItemClick(object sender, ItemClickEventArgs e)
{
DirectoryInfo symbolFilePath = Directory.GetParent(Application.StartupPath);
string symbolFile = Path.Combine(symbolFilePath.FullName, "Symbol");
if (CurrentForm == null)
{
SymbolLibInterface.SymbolHelp.ShowSymbolUI(null, symbolFile);
}
else
{
SymbolLibInterface.SymbolHelp.ShowSymbolUI(CurrentForm.DrawerView, symbolFile);
}
}
/// <summary>
/// 选项按纽
/// </summary>
/// <param name="sender">菜单项</param>
/// <param name="e">事件参数</param>
private void btnSetting_Clicked(object sender, ItemClickEventArgs e)
{
//FormGlobalOptions formGlobal = new FormGlobalOptions();
FrmOptions formGlobal = new FrmOptions();
formGlobal.ShowDialog(this);
}
/// <summary>
/// 图层面板
/// </summary>
/// <param name="sender">菜单项</param>
/// <param name="e">事件参数</param>
private void btnViewWorkArea_CheckedChanged(object sender, ItemClickEventArgs e)
{
try
{
if (btnViewWorkArea.Checked)
{
this.dockPaneWellTableTree.Visibility = DockVisibility.Hidden;
this.dockPanelMapLib.Visibility = DockVisibility.Hidden;
}
else
{
//if (!this.dockManager1.AutoHideContainers[0].Controls.Contains(dockPaneWellTableTree))
//{
// //this.dockManager1.AutoHideContainers[0].Controls.Add(dckPanelLayer);
// this.dockManager1.AddPanel(DockingStyle.Left, dockPaneWellTableTree);
//}
this.dockPaneWellTableTree.Visibility = DockVisibility.Visible;
this.dockPanelMapLib.Visibility = DockVisibility.Visible;
}
}
finally
{
}
}
/// <summary>
/// 属性面板可见性设置
/// </summary>
/// <param name="sender">菜单项</param>
/// <param name="e">事件参数</param>
private void btnViewProperty_CheckedChanged(object sender, ItemClickEventArgs e)
{
//LayerPanelVIsible = btnViewProperty.Checked;
try
{
if (CurrentForm == null)
{
if (btnViewProperty.Checked)
{
this.dckPanelProperty.Visibility = DockVisibility.AutoHide;
}
else
{
this.dckPanelProperty.Visibility = DockVisibility.Visible;
this.dckPanelProperty.ParentPanel.ActiveChild = this.dckPanelProperty;
}
}
else
{
CurrentForm.PropertyPanelVisible = btnViewProperty.Checked;
}
}
catch
{
}
}
/// <summary>
/// 统计面板
/// </summary>
/// <param name="sender">菜单项</param>
/// <param name="e">事件参数</param>
private void btnViewStatic_CheckedChanged(object sender, ItemClickEventArgs e)
{
//try
//{
// if (CurrentForm == null)
// {
// if (btnViewStatic.Checked)
// {
// this.dckPanelStatic.Visibility = DockVisibility.AutoHide;
// }
// else
// {
// this.dckPanelStatic.Visibility = DockVisibility.Visible;
// }
// }
// else
// {
// CurrentForm.StatisticPanelVisible = btnViewStatic.Checked;
// }
//}
//catch
//{
//}
}
/// <summary>
/// 默认消除网格锯齿
/// </summary>
/// <param name="sender">事件菜单</param>
/// <param name="e">事件参数</param>
private void bbtnMeshAntiAlias_CheckedChanged(object sender, ItemClickEventArgs e)
{
Task.Run(() =>
{
DrawerGlobalConfig.Instance.MeshNode.AntiAliasingEnable = bbtnMeshAntiAlias.Checked;
DrawerGlobalConfig.Instance.Save();
});
}
/// <summary>
/// 拖放文件
/// </summary>
/// <param name="sender">窗体</param>
/// <param name="e">事件参数</param>
private void FormMain_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
for (int i = 0; i < filePaths.Length; i++)
{
// 数组中的每个元素都是一个文件或目录的完整路径
string path = filePaths[i];
if (File.Exists(path))
{
OpenFile(path, false);
}
}
}
}
/// <summary>
/// 拖放进入事件
/// </summary>
/// <param name="sender">窗体</param>
/// <param name="e">事件参数</param>
private void FormMain_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
// 管理员模式处理文件拖放,不要删除,有作用
string[] filePaths = (string[])e.Data.GetData(typeof(string[]));
for (int i = 0; i < filePaths.Length; i++)
{
// 数组中的每个元素都是一个文件或目录的完整路径
string path = filePaths[i];
if (File.Exists(path))
{
OpenFile(path, false);
}
}
}
/// <summary>
/// Gets the neighbor document.
/// </summary>
/// <param name="documents">The documents.</param>
/// <param name="document">The document.</param>
/// <returns>A BaseDocument.</returns>
protected BaseDocument GetNeighborDocument(BaseDocument[] documents, BaseDocument document)
{
int nLength = documents.Length;
if (nLength == 1)
{
return null;
}
int nIndex = System.Array.IndexOf<BaseDocument>(documents, document);
if (nIndex == nLength - 1)
{
return documents[nIndex - 1];
}
return documents[nIndex + 1];
}
private bool isCloseCanceled = false;
/// <summary>
/// tabbeds the view1_ document closing.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void tabbedView1_DocumentClosing(object sender, DocumentCancelEventArgs e)
{
BaseDocument doc = e.Document as BaseDocument;
if (doc.Control is WellPoleUCDrawEdit child)
{
FormClosingEventArgs ea = new FormClosingEventArgs(CloseReason.MdiFormClosing, false);
child.UCDrawEdit_FormClosing(sender, ea);
isCloseCanceled = e.Cancel = ea.Cancel;
if (e.Cancel)
{
if (doc.IsActive)
{
this.ribbonControl1.MergeRibbon(child.ribbonMain, false);
}
}
else
{
child.SaveLayout();
}
}
}
/// <summary>
/// 窗体关闭事件
/// </summary>
/// <param name="sender">窗体</param>
/// <param name="e">事件参数</param>
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
for (int i = 0; i < tabbedView1.Documents.Count; i++)
{
tabbedView1.Controller.Close(tabbedView1.Documents[i]);
if (isCloseCanceled == true)
{
e.Cancel = true;
break;
}
}
}
/// <summary>
/// 关于.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemClickEventArgs"/> instance containing the event data.</param>
private void btnAbout_ItemClick(object sender, ItemClickEventArgs e)
{
FrmAbout frmAbout = new FrmAbout();
frmAbout.Show(this);
}
private void OnOpenNewFile(string filePath)
{
foreach (var doc in tabbedView1.Documents)
{
if (doc.Control is WellPoleUCDrawEdit ucDrawEdit && ucDrawEdit.FileFullName == filePath)
{
ucDrawEdit.OpenFile(filePath);
return;
}
}
OpenFile(filePath);
}
/// <summary>
/// 检测运行环境
/// </summary>
private void CheckEnvironment()
{
try
{
CheckBaseDependencies();
//CheckGriddingDependencies(); //ggff1974
//CheckMeshProcessDependencies(); //ggff1974
CheckMeshSymbolLibManagerDependencies();
}
catch (Exception ex)
{
MessageBox.Show($"运行错误(E003){ex.Message}, 请联系服务人员!");
Application.Exit();
}
}
private void CheckBaseDependencies()
{
try
{
GeoSigmaLib.GeoSigmaLibInit();
}
catch
{
throw new DllNotFoundException("加载基础库失败");
}
}
private void CheckGriddingDependencies()
{
string[] griddingDependencies =
{
// 生成等值线,和 GridModel.exe 配合使用
"CurveModel.exe",
// 最小张力
"GridModel.exe",
// 最小曲率
"SurfaceGrid.exe",
// 快速网格化
"QuikGridCS.dll",
// 反距离加权
"ModelCreateIDW.dll",
// 自然临近
"NaturalNeighbor.dll",
};
foreach (string depend in griddingDependencies)
{
if (!File.Exists(Path.Combine(Application.StartupPath, depend)))
{
throw new FileNotFoundException($"依赖的 {depend} 文件未找到");
}
if (depend.EndsWith(".dll"))
{
ValidateDll(depend);
}
}
}
private void CheckMeshProcessDependencies()
{
string fileName = "MeshProcess.exe";
if (!File.Exists(Path.Combine(Application.StartupPath, fileName)))
{
throw new FileNotFoundException($"依赖的 {fileName} 文件未找到");
}
}
private void CheckMeshSymbolLibManagerDependencies()
{
string fileName = "SymbolLibManager.exe";
if (!File.Exists(Path.Combine(Application.StartupPath, fileName)))
{
throw new FileNotFoundException($"依赖的 {fileName} 文件未找到");
}
}
private void FormMain_MdiChildActivate(object sender, EventArgs e)
{
//string strText = this.Text;
}
private void barBtnItemOpenWorkArea_ItemClick(object sender, ItemClickEventArgs e)
{
//using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
//{
// folderDialog.Description = "选择目标目录";
// folderDialog.RootFolder = Environment.SpecialFolder.Desktop;
// // 如果文本框已有路径,设置为初始路径
// if (!string.IsNullOrEmpty(m_workAreaPath))
// {
// folderDialog.SelectedPath = m_workAreaPath;
// }
// if (folderDialog.ShowDialog() == DialogResult.OK)
// {
// m_workAreaPath = folderDialog.SelectedPath;
// workAreaDb.Instance.Connected(m_workAreaPath, eDataSourceType.kep);
// // workAreaDb.Instance.Connected("D:\\kev\\20250330", eDataSourceType.kep);
// // MessageBox.Show($"已选择目录: {folderDialog.SelectedPath}");
// }
//}
OpenFileDialog ofd = new OpenFileDialog() // XtraOpenFileDialog()
{
Filter = "项目文件(*.kep)|*.kep",
RestoreDirectory = false,
Multiselect = false,
InitialDirectory = WorkConfig.Data.LastProjDirectory,
};
if (ofd.ShowDialog() != DialogResult.OK)
{
return;
}
else
{
string filename = ofd.FileName;
this.OpenWorkData(ofd.FileName);
// this.wellDataTreeList.OpenWorkData(ofd.FileName);
}
//
}
private async Task OpenWorkData(string filename)
{
try
{
using (SplashHelper splash = SplashHelper.Create())
{
SplashHelper.SetCaption("正在打开项目");
this.lastOpenProjectFile = filename;
Config.ProjectPath = Path.GetDirectoryName(filename);
Config.ProjectName = Path.GetFileNameWithoutExtension(filename);
WorkConfig.Data.LastProjDirectory = Config.ProjectPath;
ConfigUtils.Load();
Dictionary<string, Func<Task>> mapFunc = new Dictionary<string, Func<Task>>();
bool isLoadOk = false;
try
{
this.wellDataTreeList.CloseAllData();
this.WellMaptreeList.CloseAllMaps();
this.Subscribe<WellDeflection>(() =>
{
DataHelp.Reset();
CalcDataHelp.Reset();
}, true);
DBHelp.ResetDB();
//更新套损数据
// DBHelp.NewDb.Updateable<WellCasingDamage>().SetColumns(x => new WellCasingDamage() { GROUP = "默认" }).Where(x => SqlFunc.IsNullOrEmpty(x.GROUP)).ExecuteCommand();
// 同步数据库定义
EntityHelp.SyncDatabase();
DBHelp.Db.Queryable<WellCurve>().Take(1).ToList();
DBHelp.Db.Queryable<HoriWellFracturParameter>().Take(1).ToList();
DBHelp.Db.Queryable<CcsjSyhd>().Take(1).ToList();
DBHelp.Db.Queryable<CcsjYxhd>().Take(1).ToList();
DBHelp.Db.Queryable<CcsjKxd>().Take(1).ToList();
DBHelp.Db.Queryable<CcsjBhd>().Take(1).ToList();
DBHelp.Db.Queryable<CcsjStl>().Take(1).ToList();
DBHelp.Db.Queryable<CcsjSyhd>().AS(DBHelp.GetTableOriginName<CcsjSyhd>()).Take(1).ToList();
DBHelp.Db.Queryable<CcsjYxhd>().AS(DBHelp.GetTableOriginName<CcsjYxhd>()).Take(1).ToList();
DBHelp.Db.Queryable<CcsjKxd>().AS(DBHelp.GetTableOriginName<CcsjKxd>()).Take(1).ToList();
DBHelp.Db.Queryable<CcsjBhd>().AS(DBHelp.GetTableOriginName<CcsjBhd>()).Take(1).ToList();
DBHelp.Db.Queryable<CcsjStl>().AS(DBHelp.GetTableOriginName<CcsjStl>()).Take(1).ToList();
DBHelp.Db.Queryable<InterpretDrillWellLayered>().AS(DBHelp.GetTableOriginName<InterpretDrillWellLayered>()).Take(1).ToList();
DBHelp.Db.Queryable<InterpretDrillWellLayered>().Take(1).ToList();
DBHelp.Db.Queryable<ConfigTable>().Take(1).ToList();
DBHelp.Db.Queryable<WellCasingDamage>().Take(1).ToList();
////套损目录迁移
//string casingNewPath = FileHelp.GetDirCasingDamagePath("默认");
//string casingOldPath = FileHelp.GetDirCasingDamagePath(string.Empty);
//var files = Directory.GetFiles(casingOldPath);
//for (int i = 0; i < files.Length; i++)
//{
// File.Move(files[i], Path.Combine(casingNewPath, Path.GetFileName(files[i])));
//}
this.CheckDataBase();
// 同步井索引
DataHelp.SyncSearchWellName();
await DataHelp.LoadData();
await this.wellDataTreeList.OpenWorkData(filename);
isLoadOk = true;
m_IsOpenWorkArea = true;
barBtnItemStrataSystem.Enabled = m_IsOpenWorkArea;
btnStratumDivision.Enabled = m_IsOpenWorkArea;
btnNewWellSection.Enabled = m_IsOpenWorkArea;
dbInfo.Caption = Config.ProjectPath;
}
catch (Exception ex)
{
//Console.WriteLine($"打开工区异常:{ex.Message}");
//this.RepairDataBase();
//SplashHelper.SetCaption("正在打开项目");
MessageBox.Show("打开数据库错误,请检查工区是否正常");
m_IsOpenWorkArea = false;
barBtnItemStrataSystem.Enabled = m_IsOpenWorkArea;
btnStratumDivision.Enabled = m_IsOpenWorkArea;
btnNewWellSection.Enabled = m_IsOpenWorkArea;
return;
}
//if (!isLoadOk)
//{
// mapFunc.Add("DataHelp", () => DataHelp.LoadData());
// mapFunc.Add("数据管理", () => this.ctDataInstance.OpenWorkData(filename));
//}
// mapFunc.Add("数据成图", () => this.ctChartInstance.OpenWorkData(filename));
//mapFunc.Add("水平井", () => this.ctHorizontalWellInstance.OpenWorkDataAsync());
//mapFunc.Add("成果管理", () => this.ctResultInstance.OpenWorkData(filename));
//mapFunc.Add("构造识别", () => this.ctIdentifyInstance.OpenWorkData(filename));
//mapFunc.Add("统计分析", () => this.ctAnalysisInstance.OpenWorkData(filename));
//mapFunc.Add("开采评价", () => this.ctCompacityInstance.OpenWorkData());
////mapFunc.Add("储层预测", () => this.ctReservoirPrediction.OpenWorkData());
//mapFunc.Add("断层分析", () => this.ctFaultAnalyzeInstance.OpenWorkData());
//mapFunc.Add("储量分析", () => this.ctReservoirAnalyzeInstance.OpenWorkData());
//mapFunc.Add("套损井", () => this.ctCasingDamageInstance.OpenWorkData(filename));
//mapFunc.Add("三维", () => this.ctThreeDimension.OpenWorkData());
this.WellMaptreeList.OpenWorkArea(filename);
try
{
var lstTask = new List<Task>();
foreach (var kv in mapFunc)
{
try
{
lstTask.Add(kv.Value());
}
catch (Exception ex)
{
MessageBox.Show($"打开失败, 模块: '{kv.Key}', 错误: '{ex.Message}'!", "打开");
return;
}
}
await Task.WhenAll(lstTask.ToArray());
}
catch (NotSupportedException ex)
{
Reporter.WriteMsg(ex.Message);
MessageBox.Show("打开失败,可能是项目数据库结构已变更!", "打开");
}
string folderPath = Path.GetDirectoryName(filename);
m_workAreaPath = folderPath;
workAreaDb.Instance.Connected(m_workAreaPath, eDataSourceType.kep);
try
{
////追加版本
//this.WriteVersion(filename);
//WorkConfig.VisitProject(filename);
//WorkConfig.SaveData();
//this.ctHomeInstance.ReloadData();
//LayerCreate.ExePath = WorkConfig.Data.ExeDirectory;
//this.barStaticTips.Caption = $"当前项目: {filename}";
//this.SetUIEnabled(true);
////打开项目后,启用各模块功能
//foreach (TabFormPage item in this.tabFormControl.Pages)
//{
// item.Enabled = true;
//}
//this.ChangePage<CtData>();
}
catch (Exception ex)
{
Trace.WriteLine(DateTime.Now + "OpenWorkData:" + ex.Message);
}
}
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
Reporter.WriteMsg(ex.Message);
MessageBox.Show("打开失败,可能是项目数据库结构已变更!", "打开");
}
}
private void barBtnItemNewWorkArea_ItemClick(object sender, ItemClickEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog
{
Title = "新建项目",
AddExtension = true,
RestoreDirectory = false,
Filter = "项目文件(*.kep)|*.kep",
OverwritePrompt = true,
FileName = "新建项目",
// InitialDirectory = WorkConfig.Data.LastProjDirectory,
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
// 确定项目路径
string strWorkDir = Path.Combine(Path.GetDirectoryName(sfd.FileName), Path.GetFileNameWithoutExtension(sfd.FileName));
string strWorkFile = Path.Combine(strWorkDir, Path.GetFileName(sfd.FileName));
if (Directory.Exists(strWorkDir))
{
if (MessageBox.Show("选择目录已存在同名项目,确认是否继续创建项目?", "确认", MessageBoxButtons.YesNo) == DialogResult.No)
{
return;
}
}
using (SplashHelper splash = SplashHelper.Create())
{
SplashHelper.SetCaption("正在创建项目");
if (!Directory.Exists(strWorkDir))
{
// 创建目录
Directory.CreateDirectory(strWorkDir);
}
Config.ProjectPath = strWorkDir;
// 初始化项目路径
string srcPath = Environment.CurrentDirectory + @"\WorkSpace\";
string destPath = Config.ProjectPath;
// 拷贝目录
Fk.Utils.WorkAreaDirectoryIO.CopyDirectory(srcPath, destPath);
// 测试codefirst
{
string file = Fk.Utils.WorkAreaDirectoryIO.CombinPath(Config.ProjectPath, "sys.db");
if (File.Exists(file))
{
File.Delete(file);
}
// 初始化数据库
DBHelp.ResetDB();
EntityHelp.InitDatabase();
}
WorkData.Entity.WorkArea wa = new WorkData.Entity.WorkArea();
string temp = strWorkFile.Substring(strWorkFile.LastIndexOf("\\") + 1);
wa.ID = 1;
wa.WORKNAME = temp.Substring(0, temp.Length - 4);
wa.PROJECTION = string.Empty;
DBHelp.NewDb.Insertable(wa).ExecuteCommand();
File.WriteAllText(strWorkFile, string.Empty);
// 打开项目
this.OpenWorkData(strWorkFile);
}
}
private void dckPanelLayer_Click(object sender, EventArgs e)
{
}
/// <summary>
/// 检测树是否存在节点总数
/// </summary>
private void CheckDataBase()
{
//List<TableInfoValue> tableInfoValues = DBHelp.NewDb.Queryable<TableInfoValue>().Take(1).ToList();
var lst = DBHelp.NewDb.Queryable<SysDataTree>().ToList();
var checkTreeTable = !lst.Any(x => x.NODE_NAME == "散点数据" && x.NODE_TYPE == 1);
bool isCreate = false;
try
{
var tableInfos = DBHelp.NewDb.DbMaintenance.GetTableInfoList(false);
foreach (var tb in tableInfos)
{
var dbColumns = DBHelp.NewDb.DbMaintenance.GetColumnInfosByTableName(tb.Name, false).ToList();
var entityType = EntityHelp.GetEntityTypeByName(tb.Name);
var properties = entityType.GetProperties();
foreach (var p in properties)
{
if (dbColumns.Any(x => x.DbColumnName == p.Name))
{
var col = dbColumns.FirstOrDefault(x => x.DbColumnName == p.Name);
SugarColumn attribute = p.GetCustomAttribute<SugarColumn>();
if (attribute != null && attribute.IsIgnore == false
&& col.IsPrimarykey == false && col.IsNullable != attribute.IsNullable)
{
isCreate = true;
break;
}
}
}
}
}
catch (Exception ex)
{
//用于字段类型及属性检查,未完
}
if (lst.Count() != 51 || checkTreeTable || isCreate)
{
EntityHelp.ClearSysDataTree();
EntityHelp.InitSysDataTree();
}
List<string> notTables = new List<string>() { DBHelp.GetTableName<TableInfoValue>() };
List<TableInfo> all_tableInfos = EntityHelp.GetTableInfos().Where(x => !notTables.Contains(x.TableName)).ToList();
List<TableInfo> db_tableInfos = DBHelp.NewDb.Queryable<TableInfo>().ToList().Where(x => !notTables.Contains(x.TableName)).ToList();
//查询未存在数据库得部分
var notInDbInfos = all_tableInfos.Where(x => !db_tableInfos.Any(c => c.ColumnName == x.ColumnName && c.ChineseName == x.ChineseName && c.TableName == x.TableName));
if (notInDbInfos != null && notInDbInfos.Count() > 0)
{
EntityHelp.InitTableInfo(notInDbInfos.Distinct().ToList());
}
//查询数据库多余部分
string[] notInTables = { "well_curve", "hori_well_fractur_parameter" }; //存在自定义列
var dbExccessInfos = db_tableInfos.Where(x => !notInTables.Contains(x.TableName) && !all_tableInfos.Any(c => c.ColumnName == x.ColumnName && c.ChineseName == x.ChineseName && c.TableName == x.TableName));
if (dbExccessInfos != null && dbExccessInfos.Count() > 0)
{
EntityHelp.DeleteTableInfo(dbExccessInfos.Distinct().ToList());
}
}
private void wellDataTreeList_CustomColumnDisplayText(object sender, DevExpress.XtraTreeList.CustomColumnDisplayTextEventArgs e)
{
if (e.Column.AbsoluteIndex == 0 && e.Node?.Tag is WellDataTreeList.NodeData nd && nd.SubCount > 0)
{
e.DisplayText = $"{e.Value}({nd.SubCount})";
}
}
// 树控件双击查看数据
private void wellDataTreeList_MouseDown(object sender, MouseEventArgs e)
{
TreeList treelist = sender as TreeList;
TreeListHitInfo hitInfo = treelist.CalcHitInfo(e.Location);
if (hitInfo.Node == null || hitInfo.Node.Level < 1)
{
return;
}
if (e.Clicks == 2 && hitInfo.InRow && hitInfo.Node.Tag is WellDataTreeList.NodeData nd)
{
// 双击查看数据
if (hitInfo.Column.AbsoluteIndex == 0)
{
this.OpenNodeDataChart(hitInfo.Node);
}
}
}
// 树控件右键菜单弹出
private void wellDataTreeList_MouseUp(object sender, MouseEventArgs e)
{
this.wellDataTreeList.wellDataTreeList_MouseUp(sender, e);
}
public void OpenNodeDataChart(TreeListNode node)
{
if (node.Tag is WellDataTreeList.NodeData nd)
{
string strNodeName = nd.Data.DATANAME;
string strShowName = nd.Data.NODE_NAME;
string strExtend = nd.GeoLevel.HasValue ? nd.GeoLevel.ToString() : string.Empty;
// 目录节点
if (nd.Data.DATANAME != EntityHelp.GetTableDescriptionByName("well_base")) //"井基础")
{
if (nd.Data.NODE_TYPE == 0 || nd.Data.NODE_TYPE == 1)
{
return;
}
}
if (string.IsNullOrWhiteSpace(strNodeName))
{
return;
}
string wellName = "";
string strEnTable = "";
string strChsTable = "";
string strPERMS = nd.Data.PERMS;
if (nd.Parent != null)
{
strChsTable = EntityHelp.GetTableDescriptionByName(strPERMS);
strEnTable = strPERMS;
wellName = strNodeName;
}
else
{
strChsTable = strNodeName;// GetTableName(strNodeName);
strEnTable = this.wellDataTreeList.GetTableName(strNodeName);
}
string strcaption = "";
if (wellName != "")
{
strcaption = strChsTable + "-" + wellName;
}
else
{
strcaption = strChsTable;
}
for (int i = 0; i < this.tabbedView1.Documents.Count; i++)
{
BaseDocument baseDoc = tabbedView1.Documents[i];
if (baseDoc.Control is WellDataTableControl wellEditor)
{
if (wellEditor.Text == strcaption)
{
this.tabbedView1.ActivateDocument(baseDoc.Control);
return;
}
}
}
WellDataTableControl wellDataCtl = new WellDataTableControl();
wellDataCtl.wellName = wellName;
wellDataCtl.tableName = strEnTable;
wellDataCtl.chsTableName = strChsTable;
wellDataCtl.nodeType = nd.Data.NODE_TYPE;
wellDataCtl.Text = strcaption;
var doc = this.tabbedView1.AddDocument(wellDataCtl);
// 标签页上显示短名称
doc.Caption = wellDataCtl.Text;// TabName(wellDataCtl.Text); //ggff1974 显示文档全名称
// 光标移动上去时显示全名
if (doc is Document document)
{
document.Tooltip = wellDataCtl.Text;
}
if (strChsTable == EntityHelp.GetTableDescriptionByName("well_base") && wellName != "")
wellDataCtl.AddWellDataView(false); //基础表单井节点不修改数据
else
wellDataCtl.AddWellDataView(true);
this.ribbonControl1.MergeRibbon(wellDataCtl.ribbonMain, false);
}
}
public void CloseData(string tablename)
{
for (int i = 0; i < this.tabbedView1.Documents.Count; i++)
{
BaseDocument baseDoc = tabbedView1.Documents[i];
if (baseDoc.Control is WellDataTableControl wellEditor)
{
if (wellEditor.tableName == tablename)
{
this.tabbedView1.RemoveDocument(wellEditor);
return;
}
}
}
}
private void barGeoStr_ItemClick(object sender, ItemClickEventArgs e)
{
this.wellDataTreeList.ShowStratSystem();
}
private void GetStrataSystem_ItemClick(object sender, ItemClickEventArgs e)
{
this.wellDataTreeList.RunGetStrataSystem();
}
public void CreateNewWell(string wellname)
{
GeoSigma.UCDraw.WellAndSection.FrmNewWellPole dlgNewWell = new GeoSigma.UCDraw.WellAndSection.FrmNewWellPole() { StartPosition = FormStartPosition.CenterScreen };
dlgNewWell.preSetWellName = wellname;
if(m_IsOpenWorkArea)
{
dlgNewWell.wellNodeNames = WellMapTreeList.GetWellNodeFileNames("单井剖面");
}
if (dlgNewWell.ShowDialog(this) == DialogResult.Cancel)
{
return;
}
splashScreenManager1.ShowWaitForm();
splashScreenManager1.SetWaitFormDescription("正在新建井...");
this.SuspendLayout();
WellPoleUCDrawEdit frmChild = new WellPoleUCDrawEdit(GeoSigmaXY.eViewType.wellpole);
frmChild.DrawerView.ViewControl.mNewWellInfo.ratio = dlgNewWell.mRatio;
frmChild.DrawerView.ViewControl.mNewWellInfo.templateFilePath = dlgNewWell.mTemplatefileNamePath;
frmChild.DrawerView.ViewControl.mNewWellInfo.wellName = dlgNewWell.mwellInfo.WellName;
frmChild.DrawerView.ViewControl.mNewWellInfo.welltop = dlgNewWell.mTop;
frmChild.DrawerView.ViewControl.mNewWellInfo.wellbottom = dlgNewWell.mBottom;
frmChild.DrawerView.ViewControl.mNewWellInfo.tid = dlgNewWell.mwellInfo.id;
frmChild.OnSaveFileToWorkArea += this.SaveFileToWorkArea;
frmChild.OpenNewFile += OnOpenNewFile;
frmChild.PropertyPanel = this.dckPanelProperty; ////属性面板替换
frmChild.ElePropertyPanel = this.dockElePanel;
frmChild.DrawerStatusBar = this.ribbonControl1.StatusBar;
frmChild.EnableMeshPack = DrawerGlobalConfig.Instance.MeshNode.AntiAliasingEnable;
frmChild.ZColorWidth = this.ZColorWidth;
documentIndex++;
string strFile = dlgNewWell.mFileName;//$"新建井_{frmChild.DrawerView.ViewControl.mNewWellInfo.wellName}{documentIndex}";
if (frmChild.CreateNewFile(strFile, GeoSigmaXY.eViewType.wellpole) == false)
{
documentIndex--;
splashScreenManager1.CloseWaitForm();
MessageBox.Show("创建失败");
this.ResumeLayout();
return;
}
frmChild.NewFileSavedEvent += new NewFileSavedHandler((fileName) =>
{
SetRecent(fileName);
});
// 加载子窗体布局
frmChild.Show();
var doc = this.tabbedView1.AddDocument(frmChild);
doc.Caption = frmChild.Text;
//frmChild.ShowVtkEvent += new ShowVtkEventHandler(ShowVtkHandler);
this.ribbonControl1.MergeRibbon(frmChild.ribbonMain);
splashScreenManager1.CloseWaitForm();
this.ResumeLayout();
if (m_IsOpenWorkArea && this.wellDataTreeList != null)
{
this.WellMaptreeList.SaveFileToTreeNode("单井剖面", strFile+".pcg", frmChild);
}
}
private void WellMaptreeList_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.WellMaptreeList.wellMapTreeList_DbClick(sender, e);
}
private void WellMaptreeList_MouseUp(object sender, MouseEventArgs e)
{
this.WellMaptreeList.wellMapTreeList_MouseUp(sender, e);
}
private void WellMaptreeList_MouseDown(object sender, MouseEventArgs e)
{
TreeList maptreelist = sender as TreeList;
TreeListHitInfo hitInfo = maptreelist.CalcHitInfo(e.Location);
if (hitInfo.Node == null)
{
return;
}
if (e.Clicks == 2 && hitInfo.InRow && hitInfo.Node.Tag is NodeDataFile)
{
// 双击查看数据
this.WellMaptreeList.OpenNodeFile(hitInfo.Node);
}
}
public void SaveFileToWorkArea(string fileName, WellPoleUCDrawEdit wellViewDoc)
{
this.WellMaptreeList.SaveFileToWorkArea(fileName, wellViewDoc);
}
private void WellMaptreeList_DragDrop(object sender, DragEventArgs e)
{
this.WellMaptreeList.DragDropNode(sender, e);
}
private void WellMaptreeList_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.None; //e.Effect = DragDropEffects.Copy;
}
}
private void WellMaptreeList_DragOver(object sender, DragEventArgs e)
{
this.WellMaptreeList.DragDropOver(sender, e);
}
private void WellMaptreeList_CalcNodeDragImageIndex(object sender, CalcNodeDragImageIndexEventArgs e)
{
this.WellMaptreeList.MyCalcNodeDragImageIndex(sender, e);
}
private void btnStratumDivision_ItemClick(object sender, ItemClickEventArgs e)
{
if (workAreaDb.Instance.workData.isConn() == false)
return;
var dataDlg = new FrmWellDataEdit() { StartPosition = FormStartPosition.CenterScreen };
List<cStratumDivision> stratums = workAreaDb.Instance.workData.getStratumDivisions();
string dataType = "StratumDivision";
string[] colsName = new string[5];
colsName[0] = "id";
colsName[1] = "name";
colsName[2] = "parentID";
colsName[3] = "classname";
colsName[4] = "orderID";
string[,] datas = new string[stratums.Count, 5];
int count = 0;
foreach (var sdata in stratums)
{
datas[count, 0] = sdata.id.ToString();
datas[count, 1] = sdata.name;
datas[count, 2] = sdata.parentID.ToString();
datas[count, 3] = sdata.classname;
datas[count, 4] = sdata.orderId.ToString();
count++;
}
string[] colsNameCH = new string[0];
GeoSigmaWellPoleXY.mWellTableInfos.GetTableColumnCHNames(dataType, colsName, ref colsNameCH);
dataDlg.SetData(colsName, colsNameCH, datas);
if (dataDlg.ShowDialog(this) == DialogResult.OK)
{
if (dataDlg.m_IsModified == true)
{
DBHelp.NewDb.Deleteable<StratumDivision>();
List<StratumDivision> newList = new List<StratumDivision>();
for (int i = 0; i < dataDlg.mDatas.Rows.Count; i++)
{
DataRow rw = dataDlg.mDatas.Rows[i];
StratumDivision sd = new StratumDivision();
sd.ID = Convert.ToInt32(rw[0].ToString());
sd.name = rw[1].ToString();
sd.parentID = Convert.ToInt32(rw[2].ToString());
sd.classname = rw[3].ToString();
sd.orderId = Convert.ToInt32(rw[4].ToString());
sd.code = "";
newList.Add(sd);
}
DBHelp.NewDb.BulkInsert(newList);
}
}
}
private void btnNewWellSection_ItemClick(object sender, ItemClickEventArgs e)
{
CreateNewWellSectionWithWells("");
}
public void CreateNewWellSectionWithWells(string newWellsName)
{
List<string> wellsName = new List<string>();
if(newWellsName != "")
{
wellsName = newWellsName.Split('|').ToList();
}
GeoSigma.UCDraw.WellAndSection.FrmNewWellSection dlgNew = new GeoSigma.UCDraw.WellAndSection.FrmNewWellSection() { StartPosition = FormStartPosition.CenterScreen };
if(wellsName.Count>0)
{
dlgNew.preSetWells = wellsName.ToList();
}
if (m_IsOpenWorkArea)
{
dlgNew.sectionNodeNames = WellMapTreeList.GetWellNodeFileNames("多井剖面");
}
if (dlgNew.ShowDialog(this) == DialogResult.Cancel)
{
return;
}
splashScreenManager1.ShowWaitForm();
splashScreenManager1.SetWaitFormDescription("正在新建...");
this.SuspendLayout();
createWellSection(dlgNew.retWellInfos, dlgNew.mTemplatefileNamePath, dlgNew.retLayers, dlgNew.m_fileName
, dlgNew.m_SelectLayersName, dlgNew.m_topExtent, dlgNew.m_bottomExtent);
splashScreenManager1.CloseWaitForm();
this.ResumeLayout();
}
public void createWellSection(List<cWellBaseInfo> wells, string mTemplatefileNamePath, List<string> linkTracks,string newfileName, List<string>selectLayerNames,double topExtent,double bottomExtent)
{
WellPoleUCDrawEdit frmChild = new WellPoleUCDrawEdit(GeoSigmaXY.eViewType.wellsection);
frmChild.OnSaveFileToWorkArea += this.SaveFileToWorkArea;
frmChild.OpenNewFile += OnOpenNewFile;
frmChild.PropertyPanel = this.dckPanelProperty; ////属性面板替换
frmChild.ElePropertyPanel = this.dockElePanel;
frmChild.DrawerStatusBar = this.ribbonControl1.StatusBar;
frmChild.EnableMeshPack = DrawerGlobalConfig.Instance.MeshNode.AntiAliasingEnable;
frmChild.ZColorWidth = this.ZColorWidth;
documentIndex++;
//string tstr = wells[0].WellName + "+" + wells[wells.Count - 1].WellName;
//string strFile = $"新建连层剖面_{tstr}{documentIndex}";
string strFile = newfileName;
if (frmChild.CreateNewFile(strFile, GeoSigmaXY.eViewType.wellsection) == false)
{
documentIndex--;
splashScreenManager1.CloseWaitForm();
MessageBox.Show("创建失败");
this.ResumeLayout();
return;
}
frmChild.NewFileSavedEvent += new NewFileSavedHandler((fileName) =>
{
SetRecent(fileName);
});
if (frmChild.DrawerView.ViewControl is WellSectionDrawViewer sectionView)
{
sectionView.createWellSection(wells, mTemplatefileNamePath, linkTracks,selectLayerNames, topExtent, bottomExtent);
frmChild.DrawerView.ToolViewAll();
}
frmChild.Show();
var doc = this.tabbedView1.AddDocument(frmChild);
doc.Caption = frmChild.Text;
//frmChild.ShowVtkEvent += new ShowVtkEventHandler(ShowVtkHandler);
this.ribbonControl1.MergeRibbon(frmChild.ribbonMain);
this.ResumeLayout();
if (m_IsOpenWorkArea && this.wellDataTreeList != null)
{
this.WellMaptreeList.SaveFileToTreeNode("多井剖面", strFile + ".pcg", frmChild);
}
}
private void RepairDataBase()
{
SplashHelper.SetCaption("正在处理兼容工区");
//关闭所有连接
int length = DBHelp.DbConns.Count;
for (int i = 0; i < length; i++)
{
DBHelp.DbConns[0].Close();
DBHelp.DbConns[0].Dispose();
DBHelp.DbConns.RemoveAt(0);
}
DBHelp.ResetDB();
//检测数据库文件
string fileName = "sys.db";
string file = IO.CombinPath(Config.ProjectPath, fileName);
string tmp_path = IO.CombinPath(Config.ProjectPath, "temp");
if (!Directory.Exists(tmp_path))
{
Directory.CreateDirectory(tmp_path);
}
string tmp_file = IO.CombinPath(tmp_path, fileName);
if (File.Exists(file))
{
string newFileName = $"{Path.GetFileNameWithoutExtension(fileName)}_{DateTime.Now:yyyyMMddHHmmss}_backup{Path.GetExtension(fileName)}";
try
{
if (File.Exists(tmp_file))
{
string newFilePath = Path.Combine(tmp_path, newFileName);
File.Move(tmp_file, newFilePath);
}
//复制临时数据库
File.Copy(file, tmp_file);
var tables = DBHelp.Db.DbMaintenance.GetTableInfoList(false);
//判断Table是否存在变化无变化不删除并且不导入数据
if (tables != null && tables.Count > 0)
{
foreach (var table in tables)
{
try
{
//string deleteSql = $"TRUNCATE TABLE {table.Name}";
//DBHelp.Db.Ado.ExecuteCommand(deleteSql);
string dropSql = $"DROP TABLE {table.Name}";
DBHelp.Db.Ado.ExecuteCommand(dropSql);
}
catch (Exception)
{
}
}
DBHelp.Db.Ado.ExecuteCommand("VACUUM");
}
SplashHelper.SetCaption("正在导入数据");
// 初始化数据库
EntityHelp.InitDatabase();
Type tIdentify = typeof(IIdentifierEntity);
Type tList = typeof(IList);
List<Type> must = new List<Type>()
{
typeof(InterpretLayer),
typeof(GeologicalStratification),
typeof(WellDocument),
typeof(WorkArea),
};
List<EntityInfo> list = EntityHelp.AllEntity
.Where(o => tIdentify.IsAssignableFrom(o.Type) || must.Contains(o.Type))
.ToList();
CustomSqlSugarClient localDb = DBHelp.NewDb;
CustomSqlSugarClient dynamicDb = DBHelp.DynamicDb(tmp_file);
MethodInfo miSqlQuery = dynamicDb.Ado.GetType()
.GetMethods()
.Where(o => o.Name == "SqlQuery")
.Where(o => tList.IsAssignableFrom(o.ReturnType))
.Where(o => o.GetParameters()[1].ParameterType == typeof(object)).FirstOrDefault();
MethodInfo miBulkInsert = localDb.GetType().GetMethod("BulkInsert");
string v_cjqx = DBHelp.GetTableName<WellCurve>();
string v_yld = DBHelp.GetTableName<HoriWellFracturParameter>();
int pageSize = 5000;
Stopwatch stopwatch = Stopwatch.StartNew();
ProgressCallbackThree progress = (name, percent, count) =>
{
if (!this.InvokeRequired && stopwatch.Elapsed.TotalMilliseconds >= 800)
{
stopwatch.Restart();
SplashHelper.SetDescriptionM("正在导入数据", $"总进度:{name},当前{percent}/{count}");
}
};
string title;
int p = 0;
try
{
int count = list.Count;
foreach (EntityInfo item in list)
{
p++;
title = $"{p}/{count}";
//读取一次总数
string sql = $"select * from {item.DbTableName}";
if (item.DbTableName == DBHelp.GetTableName<TableInfoValue>())
{
sql += $" where tablename!='{v_cjqx}' and tablename!='{v_yld}'";
}
int dCount = 0;
try
{
dCount = dynamicDb.Ado.GetInt($"select count(*) from {item.DbTableName}"); //旧数据不一定存在
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
int pageIndex = 0; // 当前页数
progress(title, 0, dCount);
if (dCount == 0)
{
continue;
}
while (true)
{
string newSql = sql + $" LIMIT {pageSize} OFFSET {pageIndex * pageSize}";
IList listResult = miSqlQuery.MakeGenericMethod(item.Type).Invoke(dynamicDb.Ado, new object[] { newSql, null }) as IList;
Console.WriteLine(listResult.Count + "读取" + newSql);
if (listResult.Count > 0)
{
miBulkInsert.MakeGenericMethod(item.Type).Invoke(localDb, new object[] { listResult, null });
Console.WriteLine("写入" + newSql);
progress(title, pageSize * pageIndex, dCount);
}
else
{
break;
}
pageIndex++; // 前往下一页
}
}
}
catch (Exception ex)
{
//还原数据
MessageBox.Show(ex.Message);
return;
}
finally
{
stopwatch.Stop();
}
//处理分层兼容性
try
{
progress("导入分层数据", 0, 0);
int old_count = localDb.Queryable<InterpretDrillWellLayered>().AS(DBHelp.GetTableOriginName<InterpretDrillWellLayered>()).Count();
int new_count = localDb.Queryable<InterpretDrillWellLayered>().Count();
if (new_count > 0 && old_count == 0)
{
localDb.Queryable<InterpretDrillWellLayered>().IntoTable<InterpretDrillWellLayered>(DBHelp.GetTableOriginName<InterpretDrillWellLayered>());
}
}
catch (Exception)
{ }
//储层兼容性
try
{
progress("导入砂岩数据", 0, 0);
int old_count = localDb.Queryable<CcsjSyhd>().AS(DBHelp.GetTableOriginName<CcsjSyhd>()).Count();
int new_count = localDb.Queryable<CcsjSyhd>().Count();
if (new_count > 0 && old_count == 0)
{
localDb.Queryable<CcsjSyhd>().IntoTable<CcsjSyhd>(DBHelp.GetTableOriginName<CcsjSyhd>());
}
}
catch (Exception)
{ }
////复算-砂岩数据
//try
//{
// progress("导入砂岩数据", 0, 0);
// int old_count = localDb.Queryable<CCSJ_SY_DATA>().AS(DBHelp.GetTableOriginName<CCSJ_SY_DATA>()).Count();
// int new_count = localDb.Queryable<CCSJ_SY_DATA>().Count();
// if (new_count > 0 && old_count == 0)
// {
// localDb.Queryable<CCSJ_SY_DATA>().IntoTable<CCSJ_SY_DATA>(DBHelp.GetTableOriginName<CCSJ_SY_DATA>());
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine($"导入复算-砂岩数据异常:{ex.Message}");
//}
////劈分数据
//try
//{
// progress("导入劈分数据", 0, 0);
// int old_count = localDb.Queryable<CCSJ_SY_PF_DATA>().AS(DBHelp.GetTableOriginName<CCSJ_SY_PF_DATA>()).Count();
// int new_count = localDb.Queryable<CCSJ_SY_PF_DATA>().Count();
// if (new_count > 0 && old_count == 0)
// {
// localDb.Queryable<CCSJ_SY_PF_DATA>().IntoTable<CCSJ_SY_PF_DATA>(DBHelp.GetTableOriginName<CCSJ_SY_PF_DATA>());
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine($"导入劈分数据异常:{ex.Message}");
//}
////劈分详细数据
//try
//{
// progress("导入劈分详细数据", 0, 0);
// int old_count = localDb.Queryable<CCSJ_SY_PF_DATA_DETAIL>().AS(DBHelp.GetTableOriginName<CCSJ_SY_PF_DATA_DETAIL>()).Count();
// int new_count = localDb.Queryable<CCSJ_SY_PF_DATA_DETAIL>().Count();
// if (new_count > 0 && old_count == 0)
// {
// localDb.Queryable<CCSJ_SY_PF_DATA_DETAIL>().IntoTable<CCSJ_SY_PF_DATA_DETAIL>(DBHelp.GetTableOriginName<CCSJ_SY_PF_DATA_DETAIL>());
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine($"导入劈分详细数据异常:{ex.Message}");
//}
//// 油底水顶数据
//try
//{
// progress("导入油底水顶数据", 0, 0);
// int old_count = localDb.Queryable<WellInvertedOilWaterContact>().AS(DBHelp.GetTableOriginName<WellInvertedOilWaterContact>()).Count();
// int new_count = localDb.Queryable<WellInvertedOilWaterContact>().Count();
// if (new_count > 0 && old_count == 0)
// {
// localDb.Queryable<WellInvertedOilWaterContact>().IntoTable<WellInvertedOilWaterContact>(DBHelp.GetTableOriginName<WellInvertedOilWaterContact>());
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine($"导入油底水顶数据异常:{ex.Message}");
//}
//// 区块范围数据
//try
//{
// progress("导入区块范围数据", 0, 0);
// int old_count = localDb.Queryable<BlockBoundaries>().AS(DBHelp.GetTableOriginName<BlockBoundaries>()).Count();
// int new_count = localDb.Queryable<BlockBoundaries>().Count();
// if (new_count > 0 && old_count == 0)
// {
// localDb.Queryable<BlockBoundaries>().IntoTable<BlockBoundaries>(DBHelp.GetTableOriginName<BlockBoundaries>());
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine($"导入区块范围数据异常:{ex.Message}");
//}
//// 过渡带数据
//try
//{
// progress("导入过渡带数据", 0, 0);
// int old_count = localDb.Queryable<TransitionZone>().AS(DBHelp.GetTableOriginName<TransitionZone>()).Count();
// int new_count = localDb.Queryable<TransitionZone>().Count();
// if (new_count > 0 && old_count == 0)
// {
// localDb.Queryable<TransitionZone>().IntoTable<TransitionZone>(DBHelp.GetTableOriginName<TransitionZone>());
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine($"导入过渡带数据异常:{ex.Message}");
//}
try
{
progress("导入有效数据", 0, 0);
int old_count = localDb.Queryable<CcsjYxhd>().AS(DBHelp.GetTableOriginName<CcsjYxhd>()).Count();
int new_count = localDb.Queryable<CcsjYxhd>().Count();
if (new_count > 0 && old_count == 0)
{
localDb.Queryable<CcsjYxhd>().IntoTable<CcsjYxhd>(DBHelp.GetTableOriginName<CcsjYxhd>());
}
}
catch (Exception)
{ }
try
{
progress("导入孔隙度数据", 0, 0);
int old_count = localDb.Queryable<CcsjKxd>().AS(DBHelp.GetTableOriginName<CcsjKxd>()).Count();
int new_count = localDb.Queryable<CcsjKxd>().Count();
if (new_count > 0 && old_count == 0)
{
localDb.Queryable<CcsjKxd>().IntoTable<CcsjKxd>(DBHelp.GetTableOriginName<CcsjKxd>());
}
}
catch (Exception)
{ }
try
{
progress("导入渗透率数据", 0, 0);
int old_count = localDb.Queryable<CcsjStl>().AS(DBHelp.GetTableOriginName<CcsjStl>()).Count();
int new_count = localDb.Queryable<CcsjStl>().Count();
if (new_count > 0 && old_count == 0)
{
localDb.Queryable<CcsjStl>().IntoTable<CcsjStl>(DBHelp.GetTableOriginName<CcsjStl>());
}
}
catch (Exception)
{ }
try
{
progress("导入饱和度数据", 0, 0);
int old_count = localDb.Queryable<CcsjBhd>().AS(DBHelp.GetTableOriginName<CcsjBhd>()).Count();
int new_count = localDb.Queryable<CcsjBhd>().Count();
if (new_count > 0 && old_count == 0)
{
localDb.Queryable<CcsjBhd>().IntoTable<CcsjBhd>(DBHelp.GetTableOriginName<CcsjBhd>());
}
}
catch (Exception)
{ }
//处理自定义涉及压裂段和测井曲线数据表
try
{
//处理压裂段
progress("导入压裂段数据", 0, 0);
string[] noColNames = { "JH", "XHID", "SYWZ1", "SYWZ2" };
var lst_yld = dynamicDb.Queryable<TableInfoValue>().Where(x => x.TableName == v_yld).ToList();
List<HoriWellFracturParameter> fracturParameters = lst_yld.AsParallel().GroupBy(data => new { data.RowGuid, data.RowID })
.Select(group => new HoriWellFracturParameter()
{
RowID = group.Key.RowID,
RowGuid = group.Key.RowGuid,
XHID = group.FirstOrDefault(x => x.ColumnName == "XHID").ColumnValue,
SYWZ1 = Convert.ToDouble(group.FirstOrDefault(x => x.ColumnName == "SYWZ1").ColumnValue),
SYWZ2 = Convert.ToDouble(group.FirstOrDefault(x => x.ColumnName == "SYWZ2").ColumnValue),
JH = group.FirstOrDefault(x => x.ColumnName == "JH").ColumnValue,
ColumnValue = JsonConvert.SerializeObject(group.Where(data => !noColNames.Contains(data.ColumnName)).ToDictionary(data => data.ColumnName, data => data.ColumnValue)),
}).ToList();
DBHelp.NewDb.BulkInsert(fracturParameters);
}
catch (Exception)
{ }
try
{
progress("导入测井曲线数据", 0, 0);
string[] noColNames = { "JH", "DEPTH" };
var lst_cjqx = dynamicDb.Queryable<TableInfoValue>().Where(x => x.TableName == v_cjqx).ToList();
List<WellCurve> wellCurves = lst_cjqx.AsParallel().GroupBy(data => new { data.RowGuid, data.RowID })
.Select(group => new WellCurve()
{
RowID = group.Key.RowID,
RowGuid = group.Key.RowGuid,
DEPTH = Convert.ToDouble(group.FirstOrDefault(x => x.ColumnName == "DEPTH").ColumnValue),
JH = group.FirstOrDefault(x => x.ColumnName == "JH").ColumnValue,
ColumnValue = JsonConvert.SerializeObject(group.Where(data => !noColNames.Contains(data.ColumnName)).ToDictionary(data => data.ColumnName, data => data.ColumnValue)),
}).ToList();
DBHelp.NewDb.BulkInsert(wellCurves);
}
catch (Exception)
{ }
// 同步数据库定义
EntityHelp.SyncDatabase();
// 处理井索引
DataHelp.SyncSearchWellName();
foreach (EntityInfo item in list)
{
DataHelp.UpdateSearchWellName(item.Type);
}
//处理工区信息
}
catch (Exception ex)
{
MessageBox.Show("数据迁移合并异常" + ex.Message);
}
}
else
{
MessageBox.Show("数据迁移合并异常,数据库不存在");
}
}
private void UpdateStatus(string msg)
{
if (InvokeRequired) { Invoke(new Action(() => UpdateStatus(msg))); return; }
{
Trace.WriteLine(msg);
}
}
private void OnErrorOccurred(string msg, Exception ex)
{
if (InvokeRequired) { Invoke(new Action(() => OnErrorOccurred(msg,ex))); return; }
UpdateStatus($"错误:{msg}");
}
private void OnDisconnected(string msg)
{
if (InvokeRequired) { Invoke(new Action(() => OnDisconnected(msg))); return; }
UpdateStatus($"断开:{msg}");
}
private void OnConnected()
{
if (InvokeRequired) { Invoke(new Action(OnConnected)); return; }
UpdateStatus("已连接到 A");
}
private void OnPacketReceived(HeartbeatPacket packet)
{
if (InvokeRequired)
{
Invoke(new Action(() => OnPacketReceived(packet)));
return;
}
//labelHeartbeat.Text = $"最后心跳:{DateTime.Now:HH:mm:ss} (Seq:{packet.SequenceId})";
if (!string.IsNullOrEmpty(packet.Payload))
{
//logBox.AppendText($"[A 数据] {packet.Payload}\n");
if (packet.Payload.Length == 0)
Trace.WriteLine("heart msg \r\n");
else
{
Trace.WriteLine(packet.Payload);
if(packet.Payload.StartsWith("newWell=", StringComparison.OrdinalIgnoreCase))
{
string[] strs = packet.Payload.Split('=');
if(strs.Length == 2)
{
CreateNewWell(strs[1]);
}
}
else if(packet.Payload.StartsWith("newWellsSection=", StringComparison.OrdinalIgnoreCase))
{
string[] strs = packet.Payload.Split('=');
if(strs.Length == 2)
{
CreateNewWellSectionWithWells(strs[1]);
}
}
}
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if(m_bSlave)
{
//m_KepServer.Dispose();
//m_KepPipe.Dispose();
if(m_Mmf != null)
m_Mmf.Dispose();
}
base.OnFormClosing(e);
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
//等主窗体已经启动了,再去创建文档,这样创建文档的对话框将做为主窗体的子窗体存在。
if (m_newWellName != "")
{
CreateNewWell(m_newWellName);
}
else if (m_newWellsSection != "")
{
CreateNewWellSectionWithWells(m_newWellsSection);
}
if (m_bSlave)
{
StartConnectKep();
}
}
//private void OnPipeMessageReceived(PipeMessage msg)
//{
// if (this.InvokeRequired) { this.Invoke(new Action<PipeMessage>(OnPipeMessageReceived), msg); return; }
// //listBoxLog.Items.Add($"[{msg.Timestamp}] {msg.Content}");
// Trace.WriteLine($"[{msg.Timestamp}] {msg.Content}");
// if (msg.Content.StartsWith("newWell=", StringComparison.OrdinalIgnoreCase))
// {
// string[] strs = msg.Content.Split('=');
// if (strs.Length == 2)
// {
// CreateNewWell(strs[1]);
// }
// }
// else if (msg.Content.StartsWith("newWellsSection=", StringComparison.OrdinalIgnoreCase))
// {
// string[] strs = msg.Content.Split('=');
// if (strs.Length == 2)
// {
// CreateNewWellSectionWithWells(strs[1]);
// }
// }
// CommnicationInfo.Caption = "KEP连接正常";// $"[{msg.Timestamp}] {msg.Content}";
//}
//private void OnPipeHeartbeatTimeout()
//{
// // 注意:这个事件可能在非 UI 线程触发
// if (this.InvokeRequired)
// {
// this.Invoke(new Action(OnPipeHeartbeatTimeout));
// return;
// }
// Trace.WriteLine("心跳超时 (服务端无响应");
// CommnicationInfo.Caption = "与KEP断开";
// // 这里 PipeManager 内部已经自动触发重连逻辑了
// // 你可以在这里记录日志或弹窗提示用户
//}
//private void OnPipeStatusChanged(bool connected)
//{
// if (this.InvokeRequired) { this.Invoke(new Action<bool>(OnPipeStatusChanged), connected); return; }
// if (connected)
// {
// Trace.WriteLine("已连接 (心跳正常)");
// CommnicationInfo.Caption = "已连接KEP";
// }
// else
// {
// Trace.WriteLine("断开 (重连中...)");
// CommnicationInfo.Caption = "断开)";
// }
//}
private void OnMmfDataReceived(string msg)
{
if (InvokeRequired) { Invoke(new Action(() => OnMmfDataReceived(msg))); return; }
if (msg.StartsWith("newWell=", StringComparison.OrdinalIgnoreCase))
{
string[] strs = msg.Split('=');
if (strs.Length == 2)
{
CreateNewWell(strs[1]);
}
}
else if (msg.StartsWith("newWellsSection=", StringComparison.OrdinalIgnoreCase))
{
string[] strs = msg.Split('=');
if (strs.Length == 2)
{
CreateNewWellSectionWithWells(strs[1]);
}
}
CommnicationInfo.Caption = "KEP连接正常";
}
private void OnMmfConnected()
{
if (InvokeRequired) { Invoke(new Action(OnMmfConnected)); return; }
CommnicationInfo.Caption = "连接KEP";
}
private void OnMmfDisconnected(string str)
{
if (InvokeRequired) { Invoke(new Action(() => OnMmfDisconnected(str))); return; }
CommnicationInfo.Caption = "断开KEP";
}
private void OnMmfError(string msg)
{
if (InvokeRequired) { Invoke(new Action(() => OnMmfError(msg))); return; }
CommnicationInfo.Caption = $"error:{msg}";
}
}
}