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.

2949 lines
110 KiB
C#

1 month ago
// ***********************************************************************
// Assembly : Construction
// Author : flythink
// Created : 06-22-2020
//
// Last Modified By : flythink
// Last Modified On : 09-01-2020
// ***********************************************************************
// <copyright file="frmImportData.cs" company="jindongfang">
// Copyright (c) jindongfang. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace WellWorkDataUI
{
using DevExpress.XtraDiagram;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraTreeList.Nodes;
using DQ.Construction.NewLook.DataManager;
using DQ.Construction.NewLook.DataTemplate;
//using DQ.Construction.NewLook.FTP;
using Microsoft.VisualBasic;
// using Org.BouncyCastle.Tls.Crypto;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using WellWorkDataUI.CustomControls;
using WorkData;
using WorkData.Entity;
using WorkData.EntityBase;
using ComboBoxItem = WellWorkDataUI.CustomControls.ComboBoxItem;
/// <summary>
/// Class FrmImportData.
/// Implements the <see cref="System.Windows.Forms.Form" />
/// </summary>
/// <seealso cref="System.Windows.Forms.Form" />
public partial class FrmImportData : XtraForm, IImportDataUI, IImportDataCfg
{
private Color[] arrayColor = null;
private string createCw;
private string createCwId;
private int currentSelectedRow = -1;
private string dbType = string.Empty;
/// <summary>
/// 映射字典
/// </summary>
private Dictionary<string, HashSet<string>> mapQuickMatch = new Dictionary<string, HashSet<string>>();
private MatchColumnControl match = new MatchColumnControl()
{
Dock = DockStyle.Fill,
Orientation = Orientation.Vertical,
};
private string tableName;
private bool autoClose = true;
private DataTable dataTableTree;
private RepositoryItemComboBox repoLayers = new RepositoryItemComboBox();
public string errorMessage = string.Empty;
private ImportManager impMgr;
/// <summary>
/// Initializes a new instance of the <see cref="FrmImportData" /> class.
/// </summary>
public FrmImportData()
{
this.InitializeComponent();
this.InitializeCustomComponent();
this.LoadSettings();
this.LoadCommonData();
this.impMgr = new ImportManager(this);
}
/// <summary>
/// Initializes a new instance of the <see cref="FrmImportData" /> class.
/// </summary>
/// <param name="tablename_p">The tablename p.</param>
/// <param name="childName">The childName</param>
/// <param name="dt_p">The dt p.</param>
public FrmImportData(string tablename_p, string childName, DataTable dt_p)
: this()
{
this.BindMenuSystem();
this.BindRoot();
this.autoClose = !string.IsNullOrWhiteSpace(tablename_p);
this.arrayColor = new Color[4];
this.arrayColor[0] = Color.OrangeRed;
this.arrayColor[1] = Color.Yellow;
this.arrayColor[2] = Color.DeepSkyBlue;
this.arrayColor[3] = Color.Lime;
if (!string.IsNullOrWhiteSpace(tablename_p))
{
this.Width -= this.splitMain.Panel1.Width;
this.splitMain.PanelVisibility = SplitPanelVisibility.Panel2;
}
this.UpdateNode = childName;
this.tableName = tablename_p;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = FormStartPosition.CenterParent;
this.Init(dt_p);
this.trlWorkData.LookAndFeel.UseDefaultLookAndFeel = false;
this.trlWorkData.LookAndFeel.UseWindowsXPTheme = true;
this.trlWorkData.Appearance.Row.BackColor = Color.Transparent; // 节点默认背景色
}
/// <summary>
/// Initializes a new instance of the <see cref="FrmImportData" /> class.
/// </summary>
/// <param name="tablename_p">The tablename p.</param>
/// <param name="childName">The childName p.</param>
/// <param name="dt_p">The dt p.</param>
/// <param name="array">The array.</param>
public FrmImportData(string tablename_p, string childName, DataTable dt_p, string[] array)
: this(tablename_p, childName, dt_p)
{
if (array != null && array.Length > 0)
{
//根据格式判断类型
if (string.IsNullOrWhiteSpace(this.dbType))
{
string ext = Path.GetExtension(array.FirstOrDefault());
if (ext.ToLower().Equals(".xls") || ext.ToLower().Equals(".xlsx"))
{
this.rdo_excel.Checked = true;
this.dbType = "excel";
}
}
this.SelectFileImpl(array, this.IsMultiSelect());
this.UpdateSaveButton();
}
}
/// <summary>
/// 数据库连接字符串.
/// </summary>
/// <value>The connect string.</value>
public string ConnectString { get; set; } = string.Empty;
/// <summary>
/// The database oracle
/// </summary>
/// <value>The database oracle.</value>
public string DbOracle { get; set; } = string.Empty;
/// <summary>
/// The database SQL server
/// </summary>
/// <value>The database SQL server.</value>
public string DbSqlServer { get; set; } = string.Empty;
/// <summary>
/// The import data name
/// </summary>
/// <value>The name of the import data.</value>
public string ImportDataName { get; set; } = string.Empty;
/// <summary>
/// The ip oracle
/// </summary>
/// <value>The ip oracle.</value>
public string IpOracle { get; set; } = string.Empty;
/// <summary>
/// The ip SQL server
/// </summary>
/// <value>The ip SQL server.</value>
public string IpSqlServer { get; set; } = string.Empty;
/// <summary>
/// The password oracle
/// </summary>
/// <value>The password oracle.</value>
public string PwdOracle { get; set; } = string.Empty;
/// <summary>
/// The password SQL server
/// </summary>
/// <value>The password SQL server.</value>
public string PwdSqlServer { get; set; } = string.Empty;
/// <summary>
/// The uid oracle
/// </summary>
/// <value>The uid oracle.</value>
public string UidOracle { get; set; } = string.Empty;
/// <summary>
/// The uid SQL server
/// </summary>
/// <value>The uid SQL server.</value>
public string UidSqlServer { get; set; } = string.Empty;
/// <summary>
/// 强制插入
/// </summary>
public bool AlwaysAppend { get; set; } = false;
public bool UpdateAppend { get; set; } = false;
public string UpdateNode { get; set; } = string.Empty;
private List<MatchFromItem> prevMatches => this.match.GetMatches();
/// <summary>
/// 强制插入
/// </summary>
public bool ImportFromTable { get; set; } = false;
/// <inheritdoc/>
public IWin32Window Window => this;
/// <inheritdoc/>
public int BeginIndex => Convert.ToInt32(this.seRowIndex.Value - 1);
/// <inheritdoc/>
public int BeginColumn => Convert.ToInt32(this.seColumnIndex.Value - 1);
/// <summary>
/// Gets the column width.
/// </summary>
public int ColumnWidth => Convert.ToInt32(this.seColumnEndIndex.Value);
/// <inheritdoc/>
public bool IsVertical => this.chkVertical.Checked;
/// <inheritdoc/>
public bool UseMatch => this.btnMatch.Enabled;
/// <inheritdoc/>
public List<TableInfo> ListColumnNames { get; private set; }
/// <inheritdoc/>
public List<string> ListFileNames { get; } = new List<string>();
/// <inheritdoc/>
public string TableName => this.tableName;
/// <inheritdoc/>
public Type TableType { get; private set; }
/// <inheritdoc/>
public List<InterpretLayer> ListInterpretLayer { get; } = new List<InterpretLayer>();
/// <inheritdoc/>
public List<MatchFromItem> ListMatches => this.match.GetMatches();
/// <inheritdoc/>
public string DbType => this.dbType;
/// <inheritdoc/>
public string DbTableName => this.cobTableName.Text;
/// <inheritdoc/>
public bool UseHeaderRow => this.chkIsTitle.Checked;
/// <inheritdoc/>
public string DbConnectString => this.ConnectString;
/// <inheritdoc/>
public DataStorage Storage { get; } = new DataStorage();
/// <inheritdoc/>
public bool Continue { get; set; }
/// <inheritdoc/>
public int TotalImport { get; set; }
IWin32Window IImportDataUI.Window => throw new NotImplementedException();
/// <summary>
/// Initializes the specified dt p.
/// </summary>
/// <param name="dt_p">The dt p.</param>
protected void Init(DataTable dt_p)
{
this.ReSet();
//if (this.tableName == ReservoirHelp.Table)
//{
// this.TableType = ReservoirHelp.Type;
//}
//else
{
this.TableType = EntityHelp.GetEntityTypeByName(this.tableName);
}
this.Text = "导入 " + this.GetDisplayName(this.tableName);
this.btnReSet.Enabled = false;
this.btnImport.Enabled = false;
this.btnMatch.Enabled = false;
//非压裂段隐藏
if (this.tableName != DBHelp.GetTableName<HoriWellFracturParameter>())
{
this.chkUpdateColumnData.Enabled = false;
this.chkUpdateColumnData.Visible = false;
}
if (this.tableName == string.Empty)
{
this.rdo_dbf.Enabled = false;
this.rdo_excel.Enabled = false;
this.rdo_access.Enabled = false;
this.rdo_oracle.Enabled = false;
this.rdo_sqlserver.Enabled = false;
this.tabgroupPreview.SelectedTabPageIndex = 0;
this.cobTableName.ForeColor = Color.DarkGray;
this.cobTableName.Enabled = false;
this.lblTableName.Enabled = false;
this.seRowIndex.Enabled = false;
this.chkIsTitle.Enabled = false;
this.chkShowData.Enabled = false;
this.lblCount.Enabled = false;
this.btnSelect.Enabled = false;
}
//else if (this.TableType.IsType<InterpretTable>()
// || this.tableName == DBHelp.GetTableName<WellTimeDepth>()
// || this.tableName == DBHelp.GetTableName<WorkArea>())
//{
// this.rdo_dbf.Enabled = false;
// this.rdo_excel.Enabled = false;
// this.rdo_access.Enabled = false;
// this.rdo_oracle.Enabled = false;
// this.rdo_sqlserver.Enabled = false;
// this.lcgroupPreviewVertical.HideToCustomization();
// this.tabgroupPreview.InsertTabPage(0, this.lcgroupPreviewVertical2);
// this.lcgroupPreviewVertical2.RestoreFromCustomization();
// this.tabgroupPreview.SelectedTabPageIndex = 0;
// this.cobTableName.Visible = true;
// this.seRowIndex.Enabled = true;
// this.chkShowData.Enabled = false;
// this.lblCount.Enabled = false;
// this.btnSelect.Enabled = true;
// this.lblTableName.Enabled = false;
// this.cobTableName.Enabled = false;
//}
//else if (this.tableName == DBHelp.GetTableName<Crossplot>())
//{
// this.rdo_txt.Enabled = false;
// this.rdo_dbf.Enabled = false;
// this.rdo_excel.Enabled = true;
// this.rdo_access.Enabled = false;
// this.rdo_oracle.Enabled = false;
// this.rdo_sqlserver.Enabled = false;
// this.rdo_ftp.Enabled = false;
// this.rdo_excel.Checked = true;
// this.lcgroupPreviewVertical2.HideToCustomization();
// this.tabgroupPreview.InsertTabPage(0, this.lcgroupPreviewVertical);
// this.lcgroupPreviewVertical.RestoreFromCustomization();
// this.tabgroupPreview.SelectedTabPageIndex = 0;
// this.cobTableName.Visible = true;
// this.seRowIndex.Enabled = false;
// this.chkIsTitle.Enabled = false;
// this.chkShowData.Enabled = true;
// this.lblCount.Enabled = true;
// this.btnSelect.Enabled = true;
//}
else
{
this.rdo_dbf.Enabled = true;
this.rdo_excel.Enabled = true;
this.rdo_access.Enabled = true;
this.rdo_oracle.Enabled = true;
this.rdo_sqlserver.Enabled = true;
this.lcgroupPreviewVertical2.HideToCustomization();
this.tabgroupPreview.InsertTabPage(0, this.lcgroupPreviewVertical);
this.lcgroupPreviewVertical.RestoreFromCustomization();
this.tabgroupPreview.SelectedTabPageIndex = 0;
this.cobTableName.Visible = true;
this.seRowIndex.Enabled = true;
this.chkIsTitle.Enabled = true;
this.chkShowData.Enabled = true;
this.lblCount.Enabled = true;
this.btnSelect.Enabled = true;
if (this.tableName == DBHelp.GetTableName<WellCurve>())
{
this.chkIsTitle.Checked = true;
this.chkIsTitle.Enabled = true;
this.Chk_vagueMatch.Checked = false;
}
}
this.LoadMatchTemplate();
this.chkIsTitle.Checked = this.chkIsTitle.Enabled;
if (!this.LoadColumnNames())
{
return;
}
this.RegenerateMatch(bForce: true);
if (dt_p != null)
{
if (dt_p.Rows.Count > 1)
{
this.chkIsTitle.Enabled = true;
}
else
{
this.chkIsTitle.Enabled = false;
}
this.btnSelect.Enabled = false;
this.cobTableName.Enabled = false;
this.Storage.DataTablePaste = dt_p;
//this.dtData = new DataTable();
this.impMgr.ReadPasteData(ref this.Storage.DataTableShow);
this.btnReSet.Enabled = true;
this.btnImport.Enabled = true;
this.btnMatch.Enabled = true;
this.ListFileNames.Add("paste");
}
this.LoadHistory();
this.chkIsTitle.Checked = false;
if (this.tableName == DBHelp.GetTableName<Crossplot>())
{
this.chkIsTitle.Checked = true;
}
}
private void LoadMatchTemplate()
{
// 加载模板文件
if (!string.IsNullOrWhiteSpace(this.tableName))
{
string desc = EntityHelp.GetTableDescriptionByName(this.tableName);
if (!string.IsNullOrWhiteSpace(desc))
{
this.comboTemplate.Properties.Items.Clear();
foreach (string item in DataTemplateConfigManager.EnumerateTemplate(desc))
{
this.comboTemplate.Properties.Items.Add(item);
}
string last = DataTemplateConfigManager.Current.Items
.Where(o => o.Table == desc)
.Select(o => o.Last)
.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(last))
{
this.comboTemplate.SelectedItem = last;
}
if (this.comboTemplate.SelectedIndex < 0 && this.comboTemplate.Properties.Items.Count > 0)
{
this.comboTemplate.SelectedIndex = 0;
}
}
}
}
/// <summary>
/// 加载基础数据(层位表...).
/// </summary>
protected async void LoadCommonData()
{
this.ListInterpretLayer.AddRange(await DBHelp.NewDb.Queryable<InterpretLayer>().ToListAsync());
}
/// <summary>
/// 初始化其他Component
/// </summary>
protected void InitializeCustomComponent()
{
this.repoLayers.TextEditStyle = TextEditStyles.DisableTextEditor;
this.repoLayers.SelectedValueChanged += new EventHandler(this.CwChange);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Form.FormClosing" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.FormClosingEventArgs" /> that contains the event data.</param>
protected override void OnFormClosing(FormClosingEventArgs e)
{
this.SaveSettings();
base.OnFormClosing(e);
}
/// <summary>
/// 加载模板数据.
/// </summary>
/// <param name="file">The file.</param>
private void LoadMatchFromDataTemplate(string file)
{
try
{
XDocument doc = XDocument.Load(file);
this.mapQuickMatch.Clear();
foreach (XElement item in doc.Root.Elements())
{
string from = item.Attribute("From").Value;
string to = item.Attribute("TO").Value;
if (!this.mapQuickMatch.ContainsKey(from))
{
this.mapQuickMatch.Add(from, new HashSet<string>());
}
var toArray = to.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var t in toArray)
{
this.mapQuickMatch[from].Add(t);
}
}
}
catch (Exception)
{
// empty
}
}
private void SaveMatchToDataTemplate(string file)
{
try
{
XDocument doc = new XDocument(new XElement("Config"));
MatchCache cache = new MatchCache(this.match.GetMatches());
foreach (KeyValuePair<string, MatchData> kv in cache)
{
if (!string.IsNullOrWhiteSpace(kv.Value.MatchColumn))
{
doc.Root.Add(new XElement(
"Entry",
new XAttribute("From", kv.Value.ChineseName),
new XAttribute("TO", kv.Value.MatchColumn)));
}
}
doc.Save(file);
this.LoadMatchTemplate();
}
catch (Exception)
{
// empty
}
}
// 绑定子节点
private void AddChild(TreeListNode node)
{
DataRow dr2 = (DataRow)node.Tag; // 获取与根节点关联的数据行
string pId = dr2["SYSDATATREE_ID"].ToString(); // 获取根节点的deptId
string pname = dr2["NODE_NAME"].ToString();
// 从dt表中查询出parentId=deptId的节点
DataRow[] rows = this.dataTableTree.Select("PARENT_ID=" + pId);
if (rows.Length == 0)
{
return;
}
int nIcon = 0;
string dataname = dr2["DATANAME"].ToString();
if (dataname == "井斜" || dataname == "断层多边形" || dataname == "时间层位" || dataname == "深度层位"
|| dataname == "储层数据" || dataname == "地震边界" || dataname == "地震属性" || dataname == "测井曲线"
|| dataname == "射孔" || dataname == "断点")
{
node.SetValue(this.trlColumnWorkData, pname + "(" + rows.Length + ")");
}
// 再次遍历,添加子节点
foreach (DataRow drow in rows)
{
TreeListNode node3 = this.trlWorkData.AppendNode(this.trlColumnWorkData, node);
node3.Tag = drow;
string strIcon = drow["ICON"].ToString();
if (!string.IsNullOrEmpty(strIcon))
{
int.TryParse(strIcon, out nIcon);
}
node3.ImageIndex = nIcon;
node3.SelectImageIndex = nIcon;
if (dataname == "井基础" || dataname == "井分层")
{
int subcount = DBHelp.Db.Ado.GetInt("select count(*) from " + this.GetTableName(dataname));
if (subcount > 0)
{
node3.SetValue(this.trlColumnWorkData, pname + "(" + subcount + ")");
}
else
{
node3.SetValue(this.trlColumnWorkData, drow["NODE_NAME"].ToString());
}
}
else
{
node3.SetValue(this.trlColumnWorkData, drow["NODE_NAME"].ToString());
}
// 递归
this.AddChild(node3);
}
}
private void BindMenuSystem()
{
this.dataTableTree = DBHelp.Db.Queryable<SysDataTree>()
.OrderBy(it => it.PARENT_ID)
.OrderBy(it => it.ORDER_NUM)
.ToDataTable();
}
private void BindRoot()
{
this.trlWorkData.Nodes.Clear();
DataRow[] ro = this.dataTableTree.Select("PARENT_ID=0");
this.trlWorkData.Columns.Clear();
this.trlWorkData.Columns.Add(this.trlColumnWorkData);
int nIcon = 0;
foreach (DataRow dr in ro)
{
TreeListNode node = this.trlWorkData.AppendNode(null, -1);
node.SetValue(this.trlColumnWorkData, dr["NODE_NAME"].ToString());
string strIcon = dr["ICON"].ToString();
if (!string.IsNullOrEmpty(strIcon))
{
int.TryParse(strIcon, out nIcon);
}
node.ImageIndex = nIcon;
node.SelectImageIndex = nIcon;
node.Tag = dr;
this.AddChild(node);
}
this.trlWorkData.ExpandAll();
}
private Stopwatch stopwatch = new Stopwatch();
//Dictionary<string, string> dict_progress = new Dictionary<string, string>();
/// <summary>
/// 更新进度
/// </summary>
/// <param name="conts">内容</param>
public void UpdateProgress(string conts)
{
if (!this.InvokeRequired && this.stopwatch.Elapsed.TotalMilliseconds > 500)
{
this.stopwatch.Restart();
SplashHelper.SetCaptionM(conts);
}
}
/// <summary>
/// 导入按钮事件处理.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private async void BtnImport_Click(object sender, EventArgs e)
{
if (this.chkUpdateColumnData.Checked)
{
//二次更新
this.UpdateAppend = true;
}
//判断必联项目
List<MatchFromItem> matches = this.ListMatches;
MatchCache cache = new MatchCache(matches);
var columnNames = this.ListColumnNames.Where(x => x.IsMust == "是").ToList();
foreach (var mustItem in columnNames)
{
if (!matches.Any(x => x.Tag.ToString() == mustItem.ColumnName))
{
MessageBox.Show($"左侧没有包含必需列,中文名称:{mustItem.ChineseName},字段名称:{mustItem.ColumnName}");
return;
}
var cItem = matches.FirstOrDefault(x => x.Tag.ToString() == mustItem.ColumnName);
if (cItem.Connections.Count == 0)
{
MessageBox.Show($"左侧必需列未连线,名称:{mustItem.ChineseName}");
return;
}
}
SplashScreenManager.ShowForm(this, typeof(DlgWait), false, false, ParentFormState.Unlocked);
this.btnImport.Enabled = false;
this.stopwatch.Start();
DBHelp.NewDb.Ado.ExecuteCommand("PRAGMA foreign_keys = OFF;");
await this.impMgr.ImportTable(this).ContinueWith((d) =>
{
try
{
if (SplashScreenManager.Default != null)
{
SplashScreenManager.CloseForm();
}
this.stopwatch.Stop();
}
catch (Exception)
{
}
});
this.btnImport.Enabled = true;
}
/// <summary>
/// 匹配按钮事件处理.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void BtnMatch_Click(object sender, EventArgs e)
{
this.RegenerateMatch(true);
}
/// <summary>
/// 重置按钮事件处理.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void BtnReSet_Click(object sender, EventArgs e)
{
this.RegenerateMatch();
}
/// <summary>
/// 选择数据源
/// </summary>
/// <param name="sender">s</param>
/// <param name="e">e</param>
private void BtnSelect_Click(object sender, EventArgs e)
{
if (this.rdo_txt.Checked)
{
this.dbType = "txt";
}
else if (this.rdo_dbf.Checked)
{
this.dbType = "dbf";
}
else if (this.rdo_excel.Checked)
{
this.dbType = "excel";
}
else if (this.rdo_access.Checked)
{
this.dbType = "access";
}
else if (this.rdo_oracle.Checked)
{
this.dbType = "oracle";
}
else if (this.rdo_sqlserver.Checked)
{
this.dbType = "sqlserver";
}
else if (this.rdo_ftp.Checked)
{
this.dbType = "ftp";
}
if (this.dbType == "txt" || this.dbType == "dbf" || this.dbType == "excel" || this.dbType == "access")
{
this.openFileDialog1 = new OpenFileDialog();
this.openFileDialog1.InitialDirectory = WorkConfig.Data.LastDataDirectory;
this.openFileDialog1.Multiselect = this.IsMultiSelect();
if (this.dbType == "txt")
{
if (this.tableName == DBHelp.GetTableName<LssxCjx>()
|| this.tableName == DBHelp.GetTableName<LssxSt>()
|| this.tableName == DBHelp.GetTableName<LssxYlsy>()
|| this.tableName == DBHelp.GetTableName<LssxYxsy>())
{
this.openFileDialog1.Filter = "散点文件(*.txt)|*.txt";
}
else if (this.tableName == DBHelp.GetTableName<WellCurve>())
{
this.chkIsTitle.Checked = true;
this.openFileDialog1.Filter = "LAS文件(*.las)|*.las|DAT文件(*.dat)|*.dat|CUR文件(*.cur)|*.cur|716文件(*.716)|*.716";
}
else
{
this.openFileDialog1.Filter = "分隔符文件(*.txt;*.dat;*.csv;*.xyz)|*.txt;*.dat;*.csv;*.xyz";
//if (this.TableType.IsType<InterpretTable>()
// || this.tableName == DBHelp.GetTableName<WorkArea>())
//{
// this.openFileDialog1.Filter += "|*.kev|*.kev|*.dfd|*.dfd";
//}
//else
if (this.tableName == DBHelp.GetTableName<WellDeflection>())
{
this.openFileDialog1.Filter += "|DEV文件(*.dev)|*.dev";
}
}
this.openFileDialog1.Filter += "|所有文件(*.*)|*.*";
}
else if (this.dbType == "dbf")
{
this.openFileDialog1.Filter = "DBF文件(*.dbf)|*.dbf";
}
else if (this.dbType == "excel")
{
this.openFileDialog1.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx|所有文件(*.*)|*.*";
}
else if (this.dbType == "access")
{
this.openFileDialog1.Filter = "MDB文件(*.mdb)|*.mdb";
}
this.openFileDialog1.Filter.TrimStart('|');
this.btnReSet.Enabled = false;
this.btnMatch.Enabled = false;
this.openFileDialog1.RestoreDirectory = false;
//this.invokeThread = new Thread(new ThreadStart(this.InvokeMethod));
//this.invokeThread.SetApartmentState(ApartmentState.STA);
//this.invokeThread.Start();
//this.invokeThread.Join();
this.result = this.openFileDialog1.ShowDialog(this);
if (this.result != DialogResult.OK)
{
return;
}
this.match.Clear();
// 保存最后导入操作的文件夹
WorkConfig.Data.LastDataDirectory = Path.GetDirectoryName(this.openFileDialog1.FileName);
WorkConfig.SaveData();
this.SelectFileImpl(this.openFileDialog1.FileNames, this.openFileDialog1.Multiselect);
}
else if (this.dbType == "oracle")
{
FrmDBConnect frm = new FrmDBConnect(this, this.dbType);
frm.StartPosition = FormStartPosition.CenterScreen;
DialogResult result = frm.ShowDialog();
if (result == DialogResult.OK)
{
string sql = "select table_name from all_tables where owner='" + this.UidOracle.ToUpper()
+ "'and tablespace_name='SYSTEM'order by table_name";
Oracle10g dB = new Oracle10g(this.ConnectString);
DataTable dt_sheet = dB.GetDataTable(sql);
dB.Dispose();
this.cobTableName.Properties.Items.Clear();
for (int i = 0; i < dt_sheet.Rows.Count; i++)
{
string tableName = dt_sheet.Rows[i]["table_name"].ToString();
this.cobTableName.Properties.Items.Add(new ComboBoxItem(tableName, tableName));
}
}
}
else if (this.dbType == "sqlserver")
{
FrmDBConnect frm = new FrmDBConnect(this, this.dbType);
frm.StartPosition = FormStartPosition.CenterScreen;
DialogResult result = frm.ShowDialog();
if (result == DialogResult.OK)
{
Server2008 dB = new Server2008(this.ConnectString);
DataTable dt_sheet = dB.GetDataTable("select name from sys.tables");
dB.Dispose();
this.cobTableName.Properties.Items.Clear();
for (int i = 0; i < dt_sheet.Rows.Count; i++)
{
string tableName = dt_sheet.Rows[i]["name"].ToString();
this.cobTableName.Properties.Items.Add(new ComboBoxItem(tableName, tableName));
}
}
}
else if (this.dbType == "ftp")
{
//var conn = FtpConnectionManager.ConnectionList.FirstOrDefault(o => o.IsDefault);
//if (conn == null)
//{
// var frmFtpSelect = new FrmFtpSelect();
// if (frmFtpSelect.ShowDialog() != DialogResult.OK)
// {
// return;
// }
// conn = frmFtpSelect.Selected;
//}
//var frm = new FrmFtpExplorer(conn, false);
//if (frm.ShowDialog() != DialogResult.OK)
//{
// return;
//}
//this.SelectFileImpl(frm.SelectedFiles.ToArray(), this.IsMultiSelect());
}
this.UpdateSaveButton();
}
private OpenFileDialog openFileDialog1;
private Thread invokeThread;
private DialogResult result;
/// <summary>
/// Invokes the method.
/// </summary>
private void InvokeMethod()
{
this.result = this.openFileDialog1.ShowDialog(this);
}
/// <summary>
/// Checks the edit_ dbtype_ click.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void CheckEdit_Dbtype_Click(object sender, EventArgs e)
{
if (this.tableName == string.Empty /*|| this.TableType.IsType<InterpretTable>()*/ || this.tableName == DBHelp.GetTableName<WellTimeDepth>())
{
return;
}
CheckEdit rad = (CheckEdit)sender;
this.dbType = rad.Name.Substring(rad.Name.LastIndexOf("_") + 1).Trim();
if (this.dbType == "dbf" || this.dbType == "access" || this.dbType == "oracle"
|| this.dbType == "sqlserver")
{
this.chkIsTitle.Enabled = false;
if (this.dbType == "oracle" || this.dbType == "sqlserver")
{
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
else
{
if (this.dbType == "access")
{
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
else
{
this.cobTableName.Enabled = false;
this.lblTableName.Enabled = false;
}
}
}
else
{
this.chkIsTitle.Enabled = true;
if (this.dbType == "excel")
{
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
else
{
this.cobTableName.ForeColor = Color.DarkGray;
this.cobTableName.Enabled = false;
this.lblTableName.Enabled = false;
}
}
this.cobTableName.Properties.Items.Clear();
if (!(this.dbType == "sqlserver" || this.dbType == "oracle"))
{
if (this.ListFileNames.Count > 0)
{
string path = this.ListFileNames[0];
}
}
}
private void chkVertical_CheckedChanged(object sender, EventArgs e)
{
this.tabgroupPreview.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;
this.tabgroupPreview.SelectedTabPageIndex = 0;
this.lcgroupPreview.TextVisible = true;
this.seRowIndex.Enabled = true;
this.seColumnIndex.Enabled = false;
this.seColumnEndIndex.Enabled = false;
}
private void chkHorizon_CheckedChanged(object sender, EventArgs e)
{
this.tabgroupPreview.ShowTabHeader = DevExpress.Utils.DefaultBoolean.True;
this.lcgroupPreview.TextVisible = false;
this.tabgroupPreview.SelectedTabPageIndex = 2;
this.generateHorizonData();
this.seRowIndex.Enabled = false;
this.seColumnIndex.Enabled = true;
this.seColumnEndIndex.Enabled = true;
}
private void chkHorizonMatch_CheckedChanged(object sender, EventArgs e)
{
this.match.Orientation = this.chkHorizonMatch.Checked ? Orientation.Horizontal : Orientation.Vertical;
}
private void chkUpdateColumnData_CheckedChanged(object sender, EventArgs e)
{
}
private void ChkIsTitle_CheckedChanged(object sender, EventArgs e)
{
this.ReadPreviewData();
}
private void ChkShowData_CheckedChanged(object sender, EventArgs e)
{
bool show = this.chkShowData.Checked;
if (show)
{
this.lcgroupPreview.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
}
else
{
this.lcgroupPreview.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
}
}
private void CobChar_SelectedIndexChanged(object sender, EventArgs e)
{
this.impMgr.ReadFilePreview(ref this.Storage.DataTableShow, true);
}
private void CobTableName_SelectedIndexChanged(object sender, EventArgs e)
{
this.impMgr.ReadDataByTableName(ref this.Storage.DataTableShow, true);
}
private void CwChange(object sender, EventArgs e)
{
ComboBoxEdit combobox = sender as ComboBoxEdit;
string selvalue = (combobox.SelectedItem as ComboBoxItem).Value.ToString();
if (selvalue.ToLower() == "new")
{
this.createCw = Interaction.InputBox("层位名称", "提示", string.Empty, -1, -1);
this.createCw = this.createCw.Trim();
if (this.createCw == string.Empty)
{
this.ShowMessageBox("层位不能为空");
return;
}
InterpretLayer cwobj = this.ListInterpretLayer.FirstOrDefault(o => o.CW.Equals(this.createCw, StringComparison.CurrentCultureIgnoreCase));
if (cwobj != null)
{
this.ShowMessageBox("该层位已存在");
return;
}
List<InterpretLayer> list_layer = this.ListInterpretLayer;
int id_cw = list_layer.Count > 0 ? list_layer.Max(o => o.ID) + 1 : 0;
InterpretLayer obj_cw = new InterpretLayer();
id_cw = list_layer.Count > 0 ? list_layer.Max(o => o.ID) + 1 : 0;
obj_cw.ID = id_cw;
obj_cw.CW = this.createCw;
obj_cw.GQID = WorkConfig.GetGQID();
DBHelp.Db.Insertable(obj_cw).ExecuteCommand();
list_layer.Add(obj_cw);
this.createCwId = id_cw + string.Empty;
this.LoadRepoLayers();
ComboBoxItem item = new ComboBoxItem(this.createCwId, this.createCw);
combobox.Properties.Items.Insert(combobox.Properties.Items.Count - 1, item);
combobox.SelectedItem = item;
this.UpdateCW();
}
else
{
this.createCw = ((sender as ComboBoxEdit).SelectedItem as ComboBoxItem).Text;
this.createCwId = selvalue;
this.UpdateCW();
}
}
/// <summary>
/// 生成横向数据
/// </summary>
private void generateHorizonData()
{
if (this.Storage.DataTableShow == null)
{
return;
}
this.Storage.DataTableShowHorizon = this.impMgr.Convert2HorizonTable(this.Storage.DataTableShow);
this.gridViewHorizon.Columns.Clear();
this.gridHorizon.DataSource = this.Storage.DataTableShowHorizon;
this.RegenerateMatch();
}
/// <summary>
/// Regenerates the match.
/// </summary>
/// <param name="automatch">If true, automatch.</param>
/// <param name="bForce">If true, b force.</param>
/// <param name="isBlur">If true, is blur.</param>
/// <returns>A bool.</returns>
private bool RegenerateMatch(bool automatch = false, bool bForce = false)
{
if (this.tableName == DBHelp.GetTableName<WellTimeDepth>()
|| this.tableName == DBHelp.GetTableName<Crossplot>())
{
return true;
}
//else if (this.TableType.IsType<InterpretTable>()
// || this.tableName == DBHelp.GetTableName<WorkArea>())
//{
// if (!this.GenerateMatchByCw())
// {
// this.ShowMessageBox("文件数据缺少列", "提示");
// return false;
// }
//}
else if (!this.GenerateMatchByFile(bForce))
{
this.ShowMessageBox("文件数据缺少列" + this.impMgr.errorMessage, "提示");
return false;
}
if (automatch)
{
if (this.Chk_vagueMatch.Checked)
{
this.AutoMatchColumnByCw();
this.AutoBlurMatchColumn();
}
else
{
this.AutoMatchColumnNew();
}
}
return true;
}
/// <summary>
/// 匹配列名
/// </summary>
private bool GenerateMatchByFile(bool bForce = false)
{
DataTable table = this.IsVertical ? this.Storage.DataTableShow : this.Storage.DataTableShowHorizon;
List<TableInfo> array = this.ListColumnNames;
if (!bForce && (table == null || table.Columns.Count == 0))
{
return false;
}
if (array == null || array.Count == 0)
{
return false;
}
bool useFileName = false;
if (this.TableType == typeof(WellDeflection) || this.TableType == typeof(WellCurve))
{
useFileName = true;
}
this.GenerateMatchImpl(table, array, useFileName);
return true;
}
/// <summary>
/// Processes the selected items.
/// </summary>
/// <param name="selectionRectangle">The selection rectangle.</param>
private List<DiagramItem> ProcessSelectedItems(RectangleF selectionRectangle)
{
List<DiagramItem> selectedItems = new List<DiagramItem>();
// 遍历 DiagramControl 中的所有项,判断哪些项在选中区域内
foreach (var item in this.match.diagramControl.Items)
{
if (this.IsItemWithinSelection(item, selectionRectangle))
{
selectedItems.Add(item);
}
}
return selectedItems;
}
/// <summary>
/// 判断项是否在选中区域内
/// </summary>
/// <param name="item">The item.</param>
/// <param name="selectionRectangle">The selection rectangle.</param>
/// <returns>A bool.</returns>
private bool IsItemWithinSelection(DiagramItem item, RectangleF selectionRectangle)
{
// 获取项的位置和边界信息
RectangleF itemBounds = item.Bounds;
// 判断项的边界是否与选中区域相交
return selectionRectangle.IntersectsWith(itemBounds);
}
/// <summary>
/// 计算选中区域的方法
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <returns>A RectangleF.</returns>
private RectangleF CalculateSelectionRectangle(Point start, Point end)
{
// 根据起始点和结束点计算选中区域的矩形框
return new RectangleF(Math.Min(start.X, end.X), Math.Min(start.Y, end.Y), Math.Abs(end.X - start.X), Math.Abs(end.Y - start.Y));
}
private DevExpress.XtraDiagram.DiagramItem clickedItem;
private Point startPoint;
private RectangleF selectionRectangle = default(RectangleF);
/// <summary>
/// Generates the match impl.
/// </summary>
/// <param name="table">The table.</param>
/// <param name="array">The array.</param>
/// <param name="useFileName">If true, use file name.</param>
private void GenerateMatchImpl(DataTable table, List<TableInfo> array, bool useFileName)
{
this.pnlColumnName.Controls.Clear();
this.pnlColumnName.Controls.Add(this.match);
//添加右键创建动态列
if (this.tableName == DBHelp.GetTableName<WellCurve>() || this.tableName == DBHelp.GetTableName<HoriWellFracturParameter>())
{
this.match.diagramControl.MouseClick += (a, b) =>
{
if (b.Button == MouseButtons.Right)
{
// 处理选中的项
this.contextMenuStrip1.Show(this.match, b.Location);
this.clickedItem = (a as DiagramControl).CalcHitItem(b.Location);
}
};
}
this.match.Clear();
float length = 2;
//连线字段显示样式宽度计算
if (array != null)
{
length = array.Max(x => x.ChineseName.Length);
}
foreach (TableInfo item in array)
{
this.match.AddFromItem(item.ChineseName, item.ColumnName, must: item.IsMust == "是" ? true : false);
}
if (useFileName)
{
this.match.AddToItem("[文件名]", "${FileName}");
}
if (table != null)
{
foreach (DataColumn col in table.Columns)
{
float strLength = this.CalcStringLength(col.ColumnName);
length = strLength > length ? strLength : length;
this.match.AddToItem(col.ColumnName, col.ColumnName);
}
}
float width = length * 18;
this.match.ShapeWidth = width > 400 ? 400 : width > 60 ? width : 60;
this.match.UpdateMatch();
}
/// <summary>
/// 绑定匹配列表
/// </summary>
/// <param name="table">The table.</param>
/// <param name="array">The array.</param>
private void GenerateMatchImpl(DataTable table, params string[] array)
{
this.pnlColumnName.Controls.Clear();
this.pnlColumnName.Controls.Add(this.match);
this.match.Clear();
float length = 2;
if (array != null)
{
length = array.Max(x => x.Length);
}
foreach (string item in array)
{
this.match.AddFromItem(item, item);
}
if (table != null)
{
foreach (DataColumn col in table.Columns)
{
float strLength = this.CalcStringLength(col.ColumnName);
length = strLength > length ? strLength : length;
this.match.AddToItem(col.ColumnName, col.ColumnName);
}
}
float width = length * 18;
this.match.ShapeWidth = width > 400 ? 400 : width > 60 ? width : 60;
this.match.UpdateMatch();
}
/// <summary>
/// Calculates the string length.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>A float.</returns>
private float CalcStringLength(string input)
{
float length = 0;
foreach (char c in input)
{
if (char.IsLetterOrDigit(c))
{
length += 0.5f; // 字母和数字按照 0.5 计算
}
else
{
length += 1; // 其他字符按照 1 计算
}
}
return length;
}
/// <summary>
/// Generates the match by cw.
/// </summary>
/// <returns>A bool.</returns>
private bool GenerateMatchByCw()
{
//if (this.tableName == DBHelp.GetTableName<InterpretTimeLayer>()
// || this.tableName == DBHelp.GetTableName<InterpretAttribute>())
//{
// this.GenerateMatchImpl(this.Storage.DataTableShow, "X坐标", "Y坐标", "Z值", "线号", "道号");
// return true;
//}
//else if (this.TableType.IsType<InterpretTableXYZ>())
//{
// this.GenerateMatchImpl(this.Storage.DataTableShow, "X坐标", "Y坐标", "Z值");
// return true;
//}
//else if (this.tableName == DBHelp.GetTableName<InterpretBoundary>()
// || this.tableName == DBHelp.GetTableName<InterpretFault>()
// || this.tableName == DBHelp.GetTableName<ScatterBaseFault>()
// || this.tableName == DBHelp.GetTableName<ScatterBaseBoundary>()
// || this.tableName == DBHelp.GetTableName<WorkArea>())
//{
// this.GenerateMatchImpl(this.Storage.DataTableShow, "X坐标", "Y坐标", "名称");
// return true;
//}
return false;
}
/// <summary>
/// Gets the data table file list.
/// </summary>
private void GetDataTableFileList()
{
this.gridPreview.DataSource = null;
using (this.Storage.DataTableList = new DataTable())
{
this.Storage.DataTableList.Columns.Add("文件名");
this.Storage.DataTableList.Columns.Add("井号");
this.Storage.DataTableList.Columns.Add("层位", typeof(object));
this.Storage.DataTableList.Columns.Add("属性名");
this.Storage.DataTableList.Columns.Add("类型");
this.Storage.DataTableList.Columns.Add("层位ID");
this.Storage.DataTableList.Columns.Add("显示名");
for (int i = 0; i < this.ListFileNames.Count; i++)
{
DataRow dr = this.Storage.DataTableList.NewRow();
string f = this.ListFileNames[i].Substring(this.ListFileNames[i].LastIndexOf("\\") + 1);
string showName = f.Split('.')[0];
dr["文件名"] = f;
dr["层位ID"] = string.Empty;
dr["井号"] = showName;
//if (this.TableType.IsType<InterpretTableXYZ>())
//{
// dr["层位"] = showName;
// dr["显示名"] = showName;
//}
//else if (this.TableType.IsType<ScatterBaseBoundary>() || this.TableType.IsType<ScatterBaseFault>())
//{
// dr["层位"] = showName;
// dr["显示名"] = showName;
// string name = Path.GetFileNameWithoutExtension(f);
// // 查找同名层位
// ScatterBase obj = DBHelp.NewDb.Queryable<ScatterBase>().First(o => string.Equals(o.CW, name, StringComparison.OrdinalIgnoreCase));
// if (obj != null)
// {
// dr["层位"] = obj.CW;
// dr["层位ID"] = obj.ID;
// }
//}
//else
{
dr["层位"] = string.Empty;
string name = Path.GetFileNameWithoutExtension(f);
// 查找同名层位
InterpretLayer obj = this.ListInterpretLayer.FirstOrDefault(o => string.Equals(o.CW, name, StringComparison.OrdinalIgnoreCase));
// 查找相似层位
if (obj == null)
{
obj = this.ListInterpretLayer
.Where(o => !string.IsNullOrWhiteSpace(o.CW))
.FirstOrDefault(o => name.IndexOf(o.CW, StringComparison.OrdinalIgnoreCase) >= 0);
}
if (obj != null)
{
dr["层位"] = obj.CW;
dr["层位ID"] = obj.ID;
}
}
dr["属性名"] = showName;
this.Storage.DataTableList.Rows.Add(dr);
}
this.gridList.DataSource = this.Storage.DataTableList;
this.gridViewList.OptionsBehavior.Editable = false;
this.gridViewList.OptionsMenu.EnableColumnMenu = false;
//if (this.TableType.IsType<InterpretTableXYZ>())
//{
// this.gridViewList.Columns["层位"].OptionsColumn.AllowEdit = true;
//}
this.gridViewList.Columns["文件名"].OptionsColumn.AllowEdit = false;
this.gridViewList.Columns["文件名"].Width = 80;
this.gridViewList.Columns["井号"].Width = 80;
this.gridViewList.Columns["层位"].Width = 80;
this.gridViewList.Columns["属性名"].Width = 80;
this.gridViewList.Columns["井号"].Visible = false;
this.gridViewList.Columns["层位"].Visible = false;
this.gridViewList.Columns["属性名"].Visible = false;
this.gridViewList.Columns["类型"].Visible = false;
this.gridViewList.Columns["层位ID"].Visible = false;
this.gridViewList.Columns["显示名"].Visible = false;
if (this.tableName == DBHelp.GetTableName<InterpretAttribute>())
{
this.gridViewList.Columns["层位"].Visible = true;
this.gridViewList.Columns["属性名"].Visible = true;
}
else if (this.tableName == DBHelp.GetTableName<WellCurve>() || this.tableName == DBHelp.GetTableName<WellTimeDepth>())
{
this.gridViewList.Columns["井号"].Visible = true;
}
else if (this.tableName == DBHelp.GetTableName<WorkArea>())
{
this.gridViewList.Columns["层位"].Visible = false;
this.gridViewList.BestFitColumns();
}
else
{
this.gridViewList.Columns["层位"].Visible = true;
}
}
}
private string GetDisplayName(string tableName)
{
//if (tableName == DBHelp.GetTableName<WorkArea>())
//{
// return "工区边界";
//}
//if (tableName == ReservoirHelp.Table)
//{
// return ReservoirHelp.Display;
//}
return EntityHelp.GetTableDescriptionByName(tableName);
}
private string GetTableName(string dataname)
{
if (dataname == "工区边界")
{
return DBHelp.GetTableName<WorkArea>();
}
return EntityHelp.GetTableNameByDesc(dataname);
}
private void GridView1_CustomDrawRowIndicator(
object sender,
DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
{
if (e.Info.IsRowIndicator && e.RowHandle >= 0)
{
e.Info.DisplayText = (e.RowHandle + 1).ToString();
}
}
private void GridView2_BeforeLeaveRow(object sender, DevExpress.XtraGrid.Views.Base.RowAllowEventArgs e)
{
this.gridViewList.OptionsBehavior.Editable = false;
}
private void GridView2_CellValueChanged(
object sender,
DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
/*DataTable dt_temp = table.Copy();
if (this.cellValue == string.Empty)
{
if (dt_temp.Rows[e.RowHandle][e.Column.ColumnHandle] != null)
{
dt_temp.Rows[e.RowHandle][e.Column.ColumnHandle] = System.DBNull.Value;
}
}*/
}
private void GridView2_CustomDrawRowIndicator(
object sender,
DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
{
if (e.Info.IsRowIndicator && e.RowHandle >= 0)
{
e.Info.DisplayText = (e.RowHandle + 1).ToString();
}
}
private void GridView2_CustomRowCellEdit(
object sender,
DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
{
if (e.Column.FieldName == "类型")
{
RepositoryItemComboBox cbx = new RepositoryItemComboBox();
cbx.TextEditStyle = TextEditStyles.DisableTextEditor;
cbx.Items.Add("DFD");
cbx.Items.Add("XYNAME");
cbx.Items.Add("XYZNAME");
e.RepositoryItem = cbx;
}
else if (e.Column.FieldName == "层位")
{
if (this.tableName == DBHelp.GetTableName<InterpretFault>()
|| this.tableName == DBHelp.GetTableName<InterpretBoundary>()
|| this.tableName == DBHelp.GetTableName<InterpretAttribute>()
|| this.tableName == DBHelp.GetTableName<InterpretDrillWellLayered>())
{
e.RepositoryItem = this.repoLayers;
this.LoadRepoLayers();
}
}
}
private void LoadRepoLayers()
{
this.repoLayers.Items.Clear();
foreach (InterpretLayer item in this.ListInterpretLayer)
{
this.repoLayers.Items.Add(new ComboBoxItem(item.ID.ToString(), item.CW));
}
this.repoLayers.Items.Add(new ComboBoxItem("new", "新建层位"));
}
private void gridViewList_MouseWheel(object sender, MouseEventArgs e)
{
this.gridViewList.OptionsBehavior.Editable = false;
}
private void gridViewList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
{
this.gridViewList.OptionsBehavior.Editable = true;
}
private void gridViewList_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
int rowindex = this.BeginIndex;
string filename = this.ListFileNames[e.RowHandle];
this.currentSelectedRow = e.RowHandle;
if (this.Storage.DataTableShow != null)
{
this.Storage.DataTableShow.Columns.Clear();
}
if (!this.IsDfdFile(filename))
{
this.impMgr.ReadFilePreview(ref this.Storage.DataTableShow, true);
this.gridPreview.DataSource = this.Storage.DataTableShow;
this.impMgr.ReadFileByRowPreview(ref this.Storage.DataTableShow, e.RowHandle, false);
this.ReadFileByRowPreviewFinish();
}
}
/// <summary>
/// Reads the file by row preview finish.
/// </summary>
private void ReadFileByRowPreviewFinish()
{
if (this.tableName != DBHelp.GetTableName<WellCurve>()
&& this.tableName != DBHelp.GetTableName<WellTimeDepth>()
&& this.tableName != DBHelp.GetTableName<Crossplot>())
{
this.btnReSet.Enabled = true;
this.btnMatch.Enabled = true;
}
this.lblCount.Text = Convert.ToString(this.impMgr.RecordCount);
this.lblCount.Enabled = true;
}
/// <summary>
/// 是否允许多选
/// </summary>
/// <returns><c>true</c> if [is multi select]; otherwise, <c>false</c>.</returns>
private bool IsMultiSelect()
{
if (this.tableName == DBHelp.GetTableName<WorkArea>())
{
return false;
}
if (this.tableName == DBHelp.GetTableName<Crossplot>())
{
return false;
}
return true;
/*if (this.tableName == DBHelp.GetTableName<InterpretFault>()
|| this.tableName == DBHelp.GetTableName<InterpretTimeLayer>()
|| this.tableName == DBHelp.GetTableName<InterpretDepthLayer>()
|| this.tableName == DBHelp.GetTableName<InterpretBoundary>()
|| this.tableName == DBHelp.GetTableName<InterpretAttribute>()
|| this.tableName == DBHelp.GetTableName<WellCurve>()
|| this.tableName == DBHelp.GetTableName<WellCapacityOilMonth>()
|| this.tableName == DBHelp.GetTableName<WellCapacityOilYear>()
|| this.tableName == DBHelp.GetTableName<WellCapacityWaterMonth>()
|| this.tableName == DBHelp.GetTableName<WellCapacityWaterYear>()
|| this.tableName == DBHelp.GetTableName<LssxCjx>()
|| this.tableName == DBHelp.GetTableName<LssxSt>()
|| this.tableName == DBHelp.GetTableName<LssxYlsy>()
|| this.tableName == DBHelp.GetTableName<LssxYxsy>())
{
return true;
}
return false;*/
}
private bool LoadColumnNames()
{
//if (this.TableType == ReservoirHelp.Type)
//{
// //this.ListColumnNames = ReservoirHelp.TableInfo.ToList();
// Dictionary<string, (string colName, string[] noColNames)> tableNames = new Dictionary<string, (string, string[])>(StringComparer.CurrentCultureIgnoreCase)
// {
// { "有效厚度", (DBHelp.GetTableName<CcsjYxhd>(),new string[] { "ID", "XHID", "CWID" }) },
// { "砂岩厚度", (DBHelp.GetTableName<CcsjSyhd>(),new string[] { "ID", "XHID", "CWID" }) },
// { "孔隙度", (DBHelp.GetTableName<CcsjKxd>(),new string[] { "ID", "XHID", "CWID" ,"YXHD","YXHD_CS" }) },
// { "饱和度", (DBHelp.GetTableName<CcsjBhd>(),new string[] { "ID", "XHID", "CWID" ,"YXHD","YXHD_CS" }) },
// { "渗透率", (DBHelp.GetTableName<CcsjStl>(),new string[] { "ID", "XHID", "CWID" ,"YXHD","YXHD_CS" }) },
// };
// string GetCol(string tableName, string colName, string chName)
// {
// string res = chName;
// if (colName.Contains("V_HD") && colName.Contains("V_DSSD"))
// {
// res = $"{chName}({tableNames[tableName]})";
// }
// return res;
// }
// var yxhd = DataHelp.ListTableInfo.Where(o => string.Equals(tableNames["有效厚度"].colName, o.TableName, StringComparison.CurrentCultureIgnoreCase) && !tableNames["有效厚度"].noColNames.Contains(o.ColumnName));
// var syhd = DataHelp.ListTableInfo.Where(o => string.Equals(tableNames["砂岩厚度"].colName, o.TableName, StringComparison.CurrentCultureIgnoreCase) && !tableNames["砂岩厚度"].noColNames.Contains(o.ColumnName));
// var kxd = DataHelp.ListTableInfo.Where(o => string.Equals(tableNames["孔隙度"].colName, o.TableName, StringComparison.CurrentCultureIgnoreCase) && !tableNames["孔隙度"].noColNames.Contains(o.ColumnName));
// var bhd = DataHelp.ListTableInfo.Where(o => string.Equals(tableNames["饱和度"].colName, o.TableName, StringComparison.CurrentCultureIgnoreCase) && !tableNames["饱和度"].noColNames.Contains(o.ColumnName));
// var stl = DataHelp.ListTableInfo.Where(o => string.Equals(tableNames["渗透率"].colName, o.TableName, StringComparison.CurrentCultureIgnoreCase) && !tableNames["渗透率"].noColNames.Contains(o.ColumnName));
// this.ListColumnNames = new List<TableInfo>();
// this.ListColumnNames.AddRange(yxhd);
// this.ListColumnNames.AddRange(syhd);
// this.ListColumnNames.AddRange(kxd);
// this.ListColumnNames.AddRange(bhd);
// this.ListColumnNames.AddRange(stl);
// this.ListColumnNames = this.ListColumnNames.GroupBy(x => new
// {
// x.ColumnName,
// x.ColumnType,
// }).Select(x => new TableInfo()
// {
// ChineseName = x.First().ChineseName,
// ColumnName = x.Key.ColumnName,
// ColumnType = x.First().ColumnType,
// ColumnWidth = x.First().ColumnWidth,
// ID = x.Max(c => c.ID),
// OrderBy = x.Max(c => c.OrderBy),
// Show = "是",
// }).OrderBy(x => x.OrderBy).ToList();
//}
//else
if (this.TableType == typeof(WellCurve))
{
this.ListColumnNames = DataHelp.ListTableInfo
.Where(o => string.Equals(o.TableName, this.tableName, StringComparison.CurrentCultureIgnoreCase))
.Where(r => !r.ColumnName.Equals("id", StringComparison.OrdinalIgnoreCase))
.Where(r => r.Show == "是")
.ToList();
}
else if (this.TableType == typeof(HoriWellFracturParameter) || this.TableType == typeof(HoriWellFracturCoord))
{
this.ListColumnNames = DataHelp.ListTableInfo
.Where(o => string.Equals(o.TableName, this.tableName, StringComparison.CurrentCultureIgnoreCase))
.Where(r => !r.ColumnName.Equals("id", StringComparison.OrdinalIgnoreCase))
.Where(r => r.Show == "是")
.ToList();
}
else
{
this.ListColumnNames = DataHelp.ListTableInfo
.Where(o => string.Equals(o.TableName, this.tableName, StringComparison.CurrentCultureIgnoreCase))
.Where(r => !r.ColumnName.Equals("id", StringComparison.OrdinalIgnoreCase))
.Where(r => !r.ColumnName.Equals("xhid", StringComparison.OrdinalIgnoreCase))
.Where(r => r.Show == "是")
.ToList();
}
return this.ListColumnNames.Count > 0;
}
private void LoadHistory()
{
DataTable dt_uo = DBHelp.Db.Queryable<UserOperate>().Where(it => it.TableName == this.tableName)
.ToDataTable();
if (dt_uo.Rows.Count > 0)
{
this.dbType = dt_uo.Rows[0]["dbType"].ToString();
if (this.dbType == "txt")
{
this.rdo_txt.Checked = true;
}
if (this.dbType == "dbf")
{
this.rdo_dbf.Checked = true;
}
if (this.dbType == "excel")
{
this.rdo_excel.Checked = true;
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
if (this.dbType == "access")
{
this.rdo_access.Checked = true;
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
if (this.dbType == "oracle")
{
this.rdo_oracle.Checked = true;
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
if (this.dbType == "sqlserver")
{
this.rdo_sqlserver.Checked = true;
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
this.seRowIndex.Value = Convert.ToDecimal(dt_uo.Rows[0]["rowindex"]);
if (this.seRowIndex.Value < 1)
{
this.seRowIndex.Value = 1;
}
if (dt_uo.Rows[0]["showdata"].ToString() == "1")
{
this.chkShowData.Checked = true;
}
if (dt_uo.Rows[0]["istitle"].ToString() == "1")
{
if (this.Storage.DataTablePaste == null)
{
this.chkIsTitle.Checked = true;
}
}
this.IpSqlServer = dt_uo.Rows[0]["IpSqlServer"].ToString();
this.DbSqlServer = dt_uo.Rows[0]["DbSqlServer"].ToString();
this.UidSqlServer = dt_uo.Rows[0]["UidSqlServer"].ToString();
this.PwdSqlServer = dt_uo.Rows[0]["PwdSqlServer"].ToString();
this.IpOracle = dt_uo.Rows[0]["IpOracle"].ToString();
this.DbOracle = dt_uo.Rows[0]["DbOracle"].ToString();
this.UidOracle = dt_uo.Rows[0]["UidOracle"].ToString();
this.PwdOracle = dt_uo.Rows[0]["PwdOracle"].ToString();
}
}
private void LoadSettings()
{
Properties.Settings setting = Properties.Settings.Default;
if (setting.FrmImportData_Width > 0 && setting.FrmImportData_Height > 0)
{
this.Width = setting.FrmImportData_Width;
this.Height = setting.FrmImportData_Height;
}
}
/// <summary>
/// 拆分模糊匹配项
/// </summary>
/// <param name="words">匹配字典</param>
/// <param name="input">输入内容</param>
/// <param name="list">返回匹配</param>
/// <returns>返回是否匹配成功</returns>
private bool FindBestMatch(List<MatchItem> words, string input, out IEnumerable<MatchItem> list)
{
// 按照N字、4字、3字、2字、1字依次类推的拆分规则
input = input.Replace("(", string.Empty).Replace(")", string.Empty).Replace("", string.Empty).Replace("", string.Empty).ToUpper();
int mimLength = 0;
if (Regex.IsMatch(input, @"^[a-zA-Z]+$"))
{
// 纯字母必须保持两位匹配
mimLength = input.Length > 1 ? 1 : 0;
}
for (int i = input.Length; i > mimLength; i--)
{
for (int j = 0; j <= input.Length - i; j++)
{
string substring = input.Substring(j, i);
if (words.Any(x => x.Name.Replace("(", string.Empty).Replace(")", string.Empty).Replace("", string.Empty).Replace("", string.Empty).ToUpper().Contains(substring)))
{
list = words.Where(x => x.Name.Replace("(", string.Empty).Replace(")", string.Empty).Replace("", string.Empty).Replace("", string.Empty).ToUpper().Contains(substring)).ToList();
return true;
}
}
}
list = null;
return false; // 没有找到匹配项
}
/// <summary>
/// 智能模糊匹配列
/// </summary>
private void AutoBlurMatchColumn()
{
using (SplashHelper.Create())
{
// 使用新版匹配的逻辑
if (this.match.Visible)
{
List<MatchItem> selectedFm = new List<MatchItem>();
List<MatchItem> selectedTo = new List<MatchItem>();
List<MatchItem> fromNames = this.match.GetFromItems().OrderBy(x => x.Name.Length).ToList();
List<MatchItem> toNames = this.match.GetToItems().OrderBy(x => x.Name.Length).ToList();
foreach (MatchItem fn in fromNames)
{
//优先匹配字段
if (this.mapQuickMatch.TryGetValue(fn.Name, out HashSet<string> oList))
{
IEnumerable<MatchItem> lst_tn = toNames.Where(x => oList.Contains(x.Name));
foreach (MatchItem tn in lst_tn)
{
if (selectedFm.Contains(fn) || selectedTo.Contains(tn))
{
continue;
}
this.match.Connect(fn, tn);
selectedTo.Add(tn);
if (!selectedFm.Contains(fn))
{
selectedFm.Add(fn);
}
break;
}
}
}
foreach (MatchItem tn in toNames)
{
//模糊匹配字段
if (this.FindBestMatch(fromNames, tn.Name, out IEnumerable<MatchItem> osList))
{
//模糊匹配
foreach (MatchItem fn in osList)
{
if (selectedFm.Contains(fn) || selectedTo.Contains(tn))
{
continue;
}
this.match.Connect(fn, tn);
selectedTo.Add(tn);
if (!selectedFm.Contains(fn))
{
selectedFm.Add(fn);
}
break;
}
}
}
}
}
}
/// <summary>
/// 智能匹配列
/// </summary>
private void AutoMatchColumnNew()
{
using (SplashHelper.Create())
{
if (!this.match.Visible)
{
return;
}
var fromNames = this.match.GetFromItems().ToList();
var toNames = this.match.GetToItems().ToList();
// 特殊逻辑:如果是 地震解释资料部分导入 且 toNames 数量为 3则使用预设映射匹配
if (this.TableName.Contains("interpret") && toNames.Count == 3)
{
var nameMapping = new Dictionary<string, string>
{
{ "X坐标", "列1" },
{ "Y坐标", "列2" },
{ "Z值", "列3" },
};
// 将 toNames 构造成字典,便于快速查找
var toNamesDict = toNames.ToDictionary(tn => tn.Name);
foreach (var fn in fromNames)
{
if (nameMapping.TryGetValue(fn.Name, out string expectedToName) &&
toNamesDict.TryGetValue(expectedToName, out MatchItem tn))
{
this.match.Connect(fn, tn);
}
}
return;
}
// 其他匹配逻辑:遍历每个 fromName按顺序尝试两种匹配规则
foreach (var fn in fromNames)
{
foreach (var tn in toNames)
{
// 如果存在 mapQuickMatch 并且 tn.Name 在对应集合中,则匹配成功
if (this.mapQuickMatch.TryGetValue(fn.Name, out HashSet<string> validNames) &&
validNames.Contains(tn.Name))
{
this.match.Connect(fn, tn);
break;
}
//模板匹配
if (tn.Name == fn.Name || tn.Name == fn.Tag.ToString())
{
//连线
this.match.Connect(fn, tn);
break;
}
// 如果启用了导入模板,并且在之前的匹配中存在 fn 与 tn 的连接,则匹配成功
if (this.ImportFromTable &&
this.prevMatches.Any(item => item.Name == fn.Name && item.Connections.Any(c => c.Name == tn.Name)))
{
this.match.Connect(fn, tn);
break;
}
}
}
}
}
/// <summary>
/// 智能匹配列
/// </summary>
private void AutoMatchColumn()
{
using (SplashHelper.Create())
{
// 使用新版匹配的逻辑
if (this.match.Visible)
{
List<MatchItem> selected = new List<MatchItem>();
List<MatchItem> fromNames = this.match.GetFromItems().ToList();
List<MatchItem> toNames = this.match.GetToItems().ToList();
foreach (MatchItem fn in fromNames)
{
foreach (MatchItem tn in toNames)
{
if (selected.Contains(tn))
{
continue;
}
// 这里的智能匹配如果不勾选模糊匹配的话 , 就只需要照着模板来匹配, 所以不需要根据名字来匹配连线,只需要根据保存的模板来找就好了
//if (tn.Name == fn.Name /*|| fn.Name.StartsWith(tn.Name)*/ || tn.Name == fn.Tag.ToString())
//{
// //连线
// this.match.Connect(fn, tn);
// /*selected.Add(tn);*/
// break;
//}
if (this.mapQuickMatch.TryGetValue(fn.Name, out HashSet<string> oList))
{
bool bBreak = false;
foreach (string oValue in oList)
{
if (oValue == tn.Name)
{
this.match.Connect(fn, tn);
/*selected.Add(tn);*/
bBreak = true;
break;
}
}
if (bBreak)
{
break;
}
}
if (this.ImportFromTable)
{
bool bBreak = false;
foreach (var item in this.prevMatches)
{
if (item.Name == fn.Name && item.Connections.Any(o => o.Name == tn.Name))
{
this.match.Connect(fn, tn);
bBreak = true;
break;
}
}
if (bBreak)
{
break;
}
}
}
}
// 如果是横向数据, 则未匹配的数据, 反向一对一匹配
/* if (this.chkHorizon.Checked)
{
var matches = this.match.GetMatches();
int j = 0;
for (int i = matches.Count - 1; i >= 0; i--, j++)
{
if (toNames.Count - 1 - j < 0)
{
break;
}
if (matches[i].Connections.Count == 0)
{
this.match.Connect(matches[i], toNames[toNames.Count - 1 - j]);
}
}
}*/
return;
}
}
}
/// <summary>
/// Autos the match column by cw.
/// </summary>
private void AutoMatchColumnByCw()
{
using (SplashHelper.Create())
{
// 使用新版匹配的逻辑
if (this.match.Visible)
{
bool matchX = false;
bool matchY = false;
bool matchZ = false;
List<MatchItem> fromNames = this.match.GetFromItems().ToList();
List<string> cols = new List<string>() { "X坐标", "Y坐标", "Z值", "名称" };
List<MatchItem> toNames = this.match.GetToItems().Where(r => cols.Contains(r.Name)).ToList();
List<MatchItem> selected = new List<MatchItem>();
// 不是名称列
List<MatchItem> ignoreZ = toNames.Where(r => this.Storage.DataTableShow.Select($"{r.Name} not in ('6','7','8')").Length == 0).ToList();
//foreach (MatchItem fn in fromNames)
//{
// if (this.TableType.IsType<InterpretTableXYZ>())
// {
// if (!matchX && fn.Name == "X坐标")
// {
// foreach (MatchItem tn in toNames.Where(r => !selected.Contains(r)))
// {
// string value = this.Storage.DataTableShow.Rows[0][tn.Name].ToString();
// if (Validation.IsDecimal(value) || value.Length == 6 || value.Length == 8)
// {
// this.match.Connect(fn, tn);
// selected.Add(tn);
// matchX = true;
// break;
// }
// }
// }
// if (!matchY && fn.Name == "Y坐标")
// {
// foreach (MatchItem tn in toNames.Where(r => !selected.Contains(r)))
// {
// string value = this.Storage.DataTableShow.Rows[0][tn.Name].ToString();
// if (Validation.IsDecimal(value) || value.Length == 7)
// {
// this.match.Connect(fn, tn);
// selected.Add(tn);
// matchY = true;
// break;
// }
// }
// }
// if (!matchZ && fn.Name == "Z值")
// {
// foreach (MatchItem tn in toNames.Where(r => !selected.Contains(r)))
// {
// string value = this.Storage.DataTableShow.Rows[0][tn.Name].ToString();
// if (Validation.IsDecimal(value))
// {
// this.match.Connect(fn, tn);
// selected.Add(tn);
// matchZ = true;
// break;
// }
// }
// }
// if (!matchZ && fn.Name == "Z值")
// {
// foreach (MatchItem tn in toNames.Where(r => !selected.Contains(r)))
// {
// string value = this.Storage.DataTableShow.Rows[0][tn.Name].ToString();
// this.match.Connect(fn, tn);
// selected.Add(tn);
// matchZ = true;
// break;
// }
// }
// }
// else if (this.tableName == DBHelp.GetTableName<InterpretBoundary>()
// || this.tableName == DBHelp.GetTableName<InterpretFault>()
// || this.tableName == DBHelp.GetTableName<WorkArea>())
// {
// if (!matchX && fn.Name == "X坐标")
// {
// foreach (MatchItem tn in toNames.Where(r => !selected.Contains(r)))
// {
// string value = this.Storage.DataTableShow.Rows[0][tn.Name].ToString();
// if (Validation.IsDecimal(value) || value.Length == 6 || value.Length == 8)
// {
// this.match.Connect(fn, tn);
// selected.Add(tn);
// matchX = true;
// break;
// }
// }
// }
// if (!matchY && fn.Name == "Y坐标")
// {
// foreach (MatchItem tn in toNames.Where(r => !selected.Contains(r)))
// {
// string value = this.Storage.DataTableShow.Rows[0][tn.Name].ToString();
// if (Validation.IsDecimal(value) || value.Length == 7)
// {
// this.match.Connect(fn, tn);
// selected.Add(tn);
// matchY = true;
// break;
// }
// }
// }
// if (!matchZ && fn.Name == "名称")
// {
// foreach (MatchItem tn in toNames.Where(r => !selected.Contains(r) && !ignoreZ.Contains(r)))
// {
// this.match.Connect(fn, tn);
// selected.Add(tn);
// matchZ = true;
// break;
// }
// }
// }
//}
return;
}
}
}
/// <summary>
/// PrepareFile
/// </summary>
/// <param name="fullpath">f</param>
internal static void PrepareFile(string fullpath)
{
string dir = Path.GetDirectoryName(fullpath);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
if (File.Exists(fullpath))
{
File.Delete(fullpath);
}
}
private void Rad_dbtype_Click(object sender, EventArgs e)
{
if (this.tableName == string.Empty /*|| this.TableType.IsType<InterpretTable>()*/
|| this.tableName == DBHelp.GetTableName<WellCurve>()
|| this.tableName == DBHelp.GetTableName<WellTimeDepth>())
{
return;
}
RadioButton rad = (RadioButton)sender;
this.dbType = rad.Name.Substring(rad.Name.LastIndexOf("_") + 1);
if (this.dbType == "dbf" || this.dbType == "access" || this.dbType == "oracle"
|| this.dbType == "sqlserver")
{
this.chkIsTitle.Enabled = false;
if (this.dbType == "oracle" || this.dbType == "sqlserver")
{
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
else
{
if (this.dbType == "access")
{
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
else
{
this.cobTableName.Enabled = false;
this.lblTableName.Enabled = false;
}
}
}
else
{
this.chkIsTitle.Enabled = true;
if (this.dbType == "excel")
{
this.cobTableName.ForeColor = Color.Black;
this.cobTableName.Enabled = true;
this.lblTableName.Enabled = true;
}
else
{
this.cobTableName.ForeColor = Color.DarkGray;
this.cobTableName.Enabled = false;
this.lblTableName.Enabled = false;
}
}
this.cobTableName.Properties.Items.Clear();
if (!(this.dbType == "sqlserver" || this.dbType == "oracle"))
{
if (this.ListFileNames.Count > 0)
{
string path = this.ListFileNames[0];
}
}
}
private void ReSet()
{
this.ListFileNames.Clear();
this.gridViewVertical.Columns.Clear();
this.gridVertical.DataSource = null;
if (this.Storage.DataTableShow != null)
{
this.Storage.DataTableShow = new DataTable();
}
this.pnlColumnName.Controls.Clear();
this.seRowIndex.Value = 1;
this.lblCount.Text = "0";
// cobChar.Text =string.Empty;
// cob_file.Text =string.Empty;
this.cobTableName.Text = string.Empty;
}
/// <summary>
/// Saves the history.
/// </summary>
private void SaveHistory()
{
UserOperate u = new UserOperate();
u.TableName = this.tableName;
u.FilePath = this.ListFileNames.FirstOrDefault() ?? string.Empty;
u.RowIndex = this.BeginIndex;
if (this.chkShowData.Checked)
{
u.ShowData = 1;
}
else
{
u.ShowData = 0;
}
if (this.chkIsTitle.Checked)
{
u.IsTitle = 1;
}
else
{
u.IsTitle = 0;
}
u.DbType = "txt";
if (this.rdo_dbf.Checked)
{
u.DbType = "dbf";
}
if (this.rdo_excel.Checked)
{
u.DbType = "excel";
}
if (this.rdo_access.Checked)
{
u.DbType = "access";
}
if (this.rdo_oracle.Checked)
{
u.DbType = "oracle";
}
if (this.rdo_sqlserver.Checked)
{
u.DbType = "sqlserver";
}
u.IpOracle = this.IpOracle;
u.DbOracle = this.DbOracle;
u.UidOracle = this.UidOracle;
u.PwdOracle = this.PwdOracle;
u.IpSqlServer = this.IpSqlServer;
u.DbSqlServer = this.DbSqlServer;
u.UidSqlServer = this.UidSqlServer;
u.PwdSqlServer = this.PwdSqlServer;
DBHelp.Db.Updateable(u).ExecuteCommand();
}
private void SaveSettings()
{
int shrink = 0;
if (this.splitMain.PanelVisibility == SplitPanelVisibility.Panel2)
{
shrink = this.splitMain.SplitterPosition;
}
Properties.Settings setting = Properties.Settings.Default;
setting.FrmImportData_Height = this.Height;
setting.FrmImportData_Width = this.Width + shrink;
setting.Save();
}
private void seColumnIndex_EditValueChanged(object sender, EventArgs e)
{
this.generateHorizonData();
}
private bool IsDfdFile(string filename)
{
if (filename.EndsWith(".kev", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (filename.EndsWith(".dfd", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
/// <summary>
/// 选择文件的实现.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="multiSelect">if set to <c>true</c> [multi select].</param>
private void SelectFileImpl(string[] array, bool multiSelect)
{
// 清空预览缓存
this.errorMessage = string.Empty;
this.impMgr.PreviewCache.Clear();
this.ListFileNames.Clear();
this.ListFileNames.AddRange(array);
Type t = EntityHelp.GetEntityTypeByName(this.tableName);
if (typeof(InterpretTable).IsAssignableFrom(t)
|| this.tableName == DBHelp.GetTableName<WorkArea>()
|| this.tableName == DBHelp.GetTableName<WellTimeDepth>())
{
// 获取文件列表
this.GetDataTableFileList();
int rowindex = this.BeginIndex;
string filename = this.ListFileNames[0];
this.currentSelectedRow = 0;
if (!this.IsDfdFile(filename))
{
// this.txtPreview.Text = this.impMgr.ReadPreviewText(filename, rowindex);
this.impMgr.ReadFilePreview(ref this.Storage.DataTableShow, true);
this.gridPreview.DataSource = this.Storage.DataTableShow;
this.impMgr.ReadFileByRowPreview(ref this.Storage.DataTableShow, this.currentSelectedRow, true);
this.ReadFileByRowPreviewFinish();
}
}
else
{
this.impMgr.ReadFilePreview(ref this.Storage.DataTableShow, true);
}
}
private void seRowIndex_EditValueChanged(object sender, EventArgs e)
{
this.ReadPreviewData();
this.ReadPreviewText();
}
private void ReadPreviewText()
{
int rowHandle = this.gridViewList.FocusedRowHandle;
if (rowHandle >= 0)
{
int rowindex = this.BeginIndex;
string filename = this.ListFileNames[rowHandle];
this.currentSelectedRow = rowHandle;
// this.txtPreview.Text = this.impMgr.ReadPreviewText(filename, rowindex);
this.impMgr.ReadFilePreview(ref this.Storage.DataTableShow, true);
this.gridPreview.DataSource = this.Storage.DataTableShow;
}
}
private void ReadPreviewData()
{
if (this.Storage.DataTablePaste == null)
{
this.impMgr.ReadFilePreview(ref this.Storage.DataTableShow, true);
if (this.chkHorizon.Checked)
{
this.generateHorizonData();
}
}
else
{
this.impMgr.ReadPasteData(ref this.Storage.DataTableShow);
}
}
private void comboTemplate_ButtonClick(object sender, ButtonPressedEventArgs e)
{
if (e.Button.Caption == "编辑")
{
string filename = this.comboTemplate.SelectedItem?.ToString();
if (!string.IsNullOrWhiteSpace(filename))
{
string fullpath = FileHelp.GetDataTemplateFile(filename);
var frm = new FrmDataTemplateEditor(fullpath);
if (frm.ShowDialog() == DialogResult.OK)
{
this.LoadMatchFromDataTemplate(fullpath);
}
}
}
}
private void comboTemplate_EditValueChanged(object sender, EventArgs e)
{
string filename = this.comboTemplate.SelectedItem?.ToString();
var color = string.IsNullOrWhiteSpace(filename) ? Color.Gray : Color.Black;
this.comboTemplate.Properties.Buttons[0].Appearance.ForeColor = color;
}
private void TrlWorkData_MouseDoubleClick(object sender, MouseEventArgs e)
{
TreeListNode clickedNode = this.trlWorkData.FocusedNode;
DataRow dr = clickedNode.Tag as DataRow;
string strNodeName = dr["DATANAME"].ToString();
int nNodeType = Convert.ToInt32(dr["NODE_TYPE"]);
if (clickedNode == null || clickedNode.Level == 0 || nNodeType == 0)
{
return;
}
this.tableName = this.GetTableName(strNodeName);
if (!DataHelp.ListTableInfo.Any(o => string.Equals(o.TableName, this.tableName, StringComparison.CurrentCultureIgnoreCase)))
{
this.ShowMessageBox("请设置数据库信息表");
return;
}
this.Init(null);
}
private void TrlWorkData_NodeCellStyle(object sender, DevExpress.XtraTreeList.GetCustomNodeCellStyleEventArgs e)
{
if (e.Node.Selected)
{
e.Appearance.BackColor2 = Color.WhiteSmoke;
}
}
private void FrmImportData_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && this.impMgr.IsDataImported)
{
this.DialogResult = DialogResult.OK;
}
}
// 保存模板
private void btnSaveTemplate_Click(object sender, EventArgs e)
{
string result = XtraInputBox.Show("输入模板名称", "保存模板", "新建模板");
if (!string.IsNullOrWhiteSpace(result))
{
string desc = EntityHelp.GetTableDescriptionByName(this.tableName);
string fullpath = FileHelp.GetDataTemplateFile($"{result}.{desc}");
this.SaveMatchToDataTemplate(fullpath);
}
}
// 删除模板
private void btnDelTemplate_Click(object sender, EventArgs e)
{
string filename = this.comboTemplate.SelectedItem?.ToString();
if (!string.IsNullOrWhiteSpace(filename))
{
if (MessageBox.Show($"是否删除模板{filename}?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
{
return;
}
string fullpath = FileHelp.GetDataTemplateFile(filename);
File.Delete(fullpath);
this.LoadMatchTemplate();
}
}
// 切换模板
private void comboTemplate_SelectedIndexChanged(object sender, EventArgs e)
{
string filename = this.comboTemplate.SelectedItem?.ToString();
if (!string.IsNullOrWhiteSpace(filename))
{
string fullpath = FileHelp.GetDataTemplateFile(filename);
this.LoadMatchFromDataTemplate(fullpath);
string desc = EntityHelp.GetTableDescriptionByName(this.tableName);
var t = DataTemplateConfigManager.Current.Items
.FirstOrDefault(o => o.Table == desc);
t.Last = filename;
DataTemplateConfigManager.SaveTemplate();
}
}
private void UpdateCW()
{
this.gridViewList.GetDataRow(this.gridViewList.FocusedRowHandle)["层位"] = this.createCw;
this.gridViewList.GetDataRow(this.gridViewList.FocusedRowHandle)["层位ID"] = this.createCwId;
}
/// <summary>
/// 更新保存功能按钮的状态.
/// </summary>
private void UpdateSaveButton()
{
//if (!(EntityHelp.GetEntityTypeByName(this.tableName).IsType<InterpretTable>()
// || this.tableName == DBHelp.GetTableName<WellTimeDepth>()
// || this.tableName == DBHelp.GetTableName<Crossplot>()))
//{
// this.btnReSet.Enabled = true;
// this.btnMatch.Enabled = true;
//}
// 如果是工区导入dfd的话, 屏蔽列匹配功能
if (this.tableName == DBHelp.GetTableName<WorkArea>())
{
string filename = this.ListFileNames[0];
if (this.IsDfdFile(filename))
{
this.btnMatch.Enabled = false;
}
}
this.btnImport.Enabled = true;
}
/// <summary>
/// Shows the message box.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="title">The title.</param>
/// <param name="buttons">The buttons.</param>
/// <param name="icon">The icon.</param>
/// <returns>A DialogResult.</returns>
private DialogResult ShowMessageBox(string text, string title = "", MessageBoxButtons buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Information)
{
// 解决弹窗在Splash窗口后面的问题
return SplashHelper.ShowMessageBox(this, text, title, buttons, icon);
}
/// <inheritdoc/>
bool IImportDataCfg.IsSkippingRow(int beginIndex, int i)
{
return this.chkIsTitle.Checked && i <= beginIndex;
}
/// <inheritdoc/>
void IImportDataUI.OnSaveFinish(IImportDataCfg cfg)
{
this.SaveHistory();
this.ImportDataName = EntityHelp.GetTableDescriptionByName(this.tableName);
if (this.autoClose)
{
//this.Visible = false;
this.DialogResult = DialogResult.OK;
}
}
/// <inheritdoc/>
void IImportDataUI.OnLoadOfficeTablesFinish(List<string> list, int activeIndex)
{
this.cobTableName.Properties.Items.Clear();
foreach (var tableName in list)
{
this.cobTableName.Properties.Items.Add(new ComboBoxItem(tableName, tableName));
}
if (this.cobTableName.Properties.Items.Count > 0)
{
this.cobTableName.SelectedIndex = activeIndex;
}
}
/// <inheritdoc/>
void IImportDataUI.RegenerateMatch()
{
this.RegenerateMatch();
}
/// <inheritdoc/>
void IImportDataUI.OnReadDataFinish(LoadDataResult dataResult)
{
this.gridViewVertical.Columns.Clear();
if (dataResult.status == ResultStatus.)
{
this.ShowMessageBox("数据无法解析," + this.impMgr.errorMessage, "提示");
}
else if (dataResult.status == ResultStatus.)
{
this.gridVertical.DataSource = null;
this.pnlColumnName.Controls.Clear();
this.ShowMessageBox("数据无法解析," + this.impMgr.errorMessage, "提示");
return;
}
if (this.dbType == "txt")
{
if (!this.IsVertical)
{
this.generateHorizonData();
}
}
this.lblCount.Text = Convert.ToString(dataResult.recordCount);
this.gridVertical.DataSource = null;
this.gridVertical.DataSource = this.Storage.DataTableShow;
this.gridViewVertical.BestFitColumns();
this.RegenerateMatch();
}
/// <inheritdoc/>
async Task<bool> IImportDataUI.ImportWellBase(DataTable dt)
{
await Task.Delay(500);
if (this.ShowMessageBox("井基础表中不存在部分井号, 是否查看?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
FrmImportData frm = new FrmImportData(DBHelp.GetTableName<WellBase>(), string.Empty, dt);
frm.AlwaysAppend = true;
frm.ImportFromTable = true;
frm.ShowDialog();
}
return false;
}
/// <inheritdoc/>
DialogResult IImportDataUI.ShowMessageBox(string text, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
{
return this.ShowMessageBox(text, title, buttons, icon);
}
private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem == this.toolStripMenuItem2)
{
//批量
var di = this.match.GetToItems().ToList();
List<MatchItem> items = this.match.GetToItems().ToList();
List<TableInfo> tableInfos = DBHelp.NewDb.Queryable<TableInfo>().Where(x => x.TableName == this.tableName).Select(x => new TableInfo() { ColumnName = x.ColumnName, ChineseName = x.ChineseName }).ToList();
List<TableInfo> ex_tableInfos = items.Where(x => !tableInfos.Any(c => c.ColumnName == x.Name) && x.Name != "[文件名]").Select(x => new TableInfo() { ColumnName = x.Name, ChineseName = x.Name }).ToList();
frmCreateColumn createColumn = new frmCreateColumn(ex_tableInfos, this.tableName);
createColumn.ShowDialog();
}
else
{
//开始执行生成操作
if (this.clickedItem != null && this.clickedItem.Tag != null)
{
string tagName = this.clickedItem.Tag.ToString();
if (tagName == "[文件名]")
{
return;
}
if (!DBHelp.NewDb.Queryable<TableInfo>().Where(x => x.TableName == this.tableName).Any(x => x.ChineseName == tagName))
{
TableInfo tableInfo = new TableInfo()
{
TableName = this.tableName,
ColumnType = "文本",
ChineseName = tagName,
ColumnWidth = "100",
ColumnName = tagName,
IsMust = "否",
OrderBy = 0,
Show = "是",
};
DBHelp.NewDb.Insertable(tableInfo).ExecuteCommand();
}
}
}
this.LoadAsync();
}
private async Task LoadAsync()
{
await DataHelp.LoadDataTableInfo();
this.LoadColumnNames();
this.RegenerateMatch(true);
}
private void btn_FuzzyMatch_Click(object sender, EventArgs e)
{
this.Chk_vagueMatch.Checked = true;
this.RegenerateMatch(true);
}
private void rdo_excel_CheckedChanged(object sender, EventArgs e)
{
this.chkIsTitle.Checked = true;
}
public int FileCount { get; set; }
public int RarefyIndex { get; set; } = -1;
}
}