年度变更建库软件5.0版本
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

2775 lines
129 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ESRI.ArcGIS.Geodatabase;
using KGIS.Framework.Utils;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Platform.Helper;
using System.IO;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using KGIS.Framework.Maps;
using System.ComponentModel;
using KGIS.Framework.OpenData.Control;
using KGIS.Framework.OpenData.Filter;
using Kingo.OpenData.Filter;
using KGIS.Framework.OpenData.InterFace;
using ESRI.ArcGIS.DataSourcesFile;
using KGIS.Framework.AE;
using KGIS.Framework.AE.Enum;
using System.Windows.Forms;
using Kingo.PluginServiceInterface;
using System.Runtime.InteropServices;
using Kingo.Plugin.DataLoad.Model;
using System.Xml;
using UIShell.OSGi;
using Kingo.PluginServiceInterface.Helper.VCT;
using Kingo.PluginServiceInterface.Model;
namespace Kingo.Plugin.DataLoad.View
{
/// <summary>
/// FrmLoadDDTC.xaml 的交互逻辑
/// </summary>
public partial class FrmLoadDDTCData : BaseWindow
{
public event EventHandler Set_BtnLoad_Activated;
public event EventHandler Set_BtnLoad_UnActivated;
public event EventHandler Close_FrmBaseDataLoad;
public bool shutDown = false;
private string ImportDataType { get; set; }
private string layerTargetName = string.Empty;
private List<IFeatureClass> pSourceFeatureClasses = null;
private string SourceMDBPath = null;
private string pTargetGDBPath = string.Empty;
public IMap pMap { get; set; }
private IDataCatalogService _DataCatalog = null;
private DDTCDataMapping _selectedDDTCData;
/// <summary>
/// 选择的变更数据
/// </summary>
public DDTCDataMapping SelectedDDTCData
{
get { return _selectedDDTCData; }
set
{
_selectedDDTCData = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedDDTCData"));
}
}
protected internal virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public new event PropertyChangedEventHandler PropertyChanged;
public FrmLoadDDTCData()
{
InitializeComponent();
if (MapsManager.Instance.MapService.GetProjectInfo() is ProjectInfo prj)
{
pTargetGDBPath = prj.ZLDatabase;
}
pMap = MapsManager.Instance.MapService.getAxMapControl().ActiveView.FocusMap;
if (_DataCatalog == null)
_DataCatalog = BundleRuntime.Instance.GetFirstOrDefaultService<IDataCatalogService>();
}
/// <summary>
/// 选择单独图层数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelectedDDTCData_Click(object sender, RoutedEventArgs e)
{
try
{
using (ComReleaser com = new ComReleaser())
{
IWorkspaceFactory pWorkspaceFactory = null;
IWorkspace pWorkspace = null;
IFeatureWorkspace pFeatureWorkspace = null;
IFeatureClass pSourceFeatureClass = null;
OpenDataDialog pDialog = new OpenDataDialog();
ISpatialDataObjectFilter pOFilter = new FilterShapefiles();//Shape文件模式
pDialog.AddFilter(pOFilter, true);
pOFilter = new FilterGeoDatabasePersonal();//MDB格式
pDialog.AddFilter(pOFilter, true);
pOFilter = new FilterVCTFile();///VCT文件模式
pDialog.AddFilter(pOFilter, true);
pOFilter = new FilterGeoDatabaseFile();//GDB格式
pDialog.AddFilter(pOFilter, true);
pDialog.AllowMultiSelect = false;
pDialog.Title = "选择单独图层数据";
pDialog.RestoreLocation = true;
pDialog.StartLocation = pDialog.FinalLocation;
DialogResult dialogResult = pDialog.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK && pDialog.Selection.Count != 0)
{
ImportDataType = Path.GetExtension(pDialog.FinalLocation).ToUpper().Replace('.', ' ').TrimStart();
if (string.IsNullOrWhiteSpace(ImportDataType) || (ImportDataType != "VCT" && ImportDataType != "GDB" && ImportDataType != "MDB" && ImportDataType != "SHP"))
{
MessageHelper.Show("选择的数据路径有误,请根据过滤条件,重新选择数据库!!");
return;
}
if (ImportDataType == "SHP")
{
ImportDataType = "Shape";
}
ProgressHelper.ShowProcessBar("正在打开数据文件...");
string fileName = string.Empty;
if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("Shape"))
{
pSourceFeatureClasses = new List<IFeatureClass>();
for (int i = 0; i < pDialog.Selection.Count; i++)
{
pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
pWorkspace = pWorkspaceFactory.OpenFromFile(Path.GetDirectoryName(pDialog.Selection[i].FullName), 0);
pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
pSourceFeatureClass = pFeatureWorkspace.OpenFeatureClass(pDialog.Selection[i].Name);
pSourceFeatureClasses.Add(pSourceFeatureClass);
fileName += pDialog.Selection[i].Name + ";";
}
btnImportDataPath.EditValue = fileName;
if (pSourceFeatureClasses.Count > 0)
{
SetShapeTableMapping();
}
}
else if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("VCT"))
{
btnImportDataPath.EditValue = pDialog.FinalLocation;
string TempMDBFolderPath = Path.GetTempPath();
string TempMDBPath = Path.Combine(TempMDBFolderPath, string.Format("{0}.mdb", Path.GetFileNameWithoutExtension(pDialog.FinalLocation)));
if (File.Exists(TempMDBPath))
{
File.Delete(TempMDBPath);
}
ProgressHelper.ShowProcessBar("正在解析VCT文件... ...");
VCTToMDBHelper3 vcttomdb = new VCTToMDBHelper3();
vcttomdb.RootPath = TempMDBFolderPath;
vcttomdb.VCTToMDB(pDialog.FinalLocation);
ProgressHelper.CloseProcessBar();
if (!File.Exists(TempMDBPath))
{
MessageHelper.ShowError("VCT文件解析失败");
return;
}
SourceMDBPath = TempMDBPath;
SetTableMapping();
}
else
{
btnImportDataPath.EditValue = pDialog.FinalLocation;
SetTableMapping();
}
ProgressHelper.CloseProcessBar();
}
com.ManageLifetime(pWorkspaceFactory);
com.ManageLifetime(pWorkspace);
com.ManageLifetime(pFeatureWorkspace);
}
}
catch (Exception ex)
{
LogAPI.Debug("选择单独图层数据失败:" + ex);
ProgressHelper.CloseProcessBar();
MessageHelper.ShowTips("选择单独图层数据失败:" + ex);
}
}
private void SetShapeTableMapping()
{
IWorkspaceAPI t_WsAPI = null;
IFeatureClassAPI t_FCAPI = null;
try
{
dgTableMapping.ItemsSource = null;
string t_GdbPath = pTargetGDBPath;
if (t_GdbPath == string.Empty)
{
MessageHelper.ShowTips("未找到工程数据文件,请检查工程数据文件是否与工程文件处于同一目录下!");
return;
}
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
t_WsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
t_WsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
Dictionary<string, string> t_TbList = t_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureDataset);
Dictionary<string, string> t_TbList2 = t_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureClass);
#region 将目标图层作为字典项可进行下拉选择
List<DataDicTionary> dicTable = new List<DataDicTionary>();
dicTable.Add(new DataDicTionary() { NAME = "Null", CODE = "null" });
dicTable.Add(new DataDicTionary() { NAME = "追加图层", CODE = "Add" });
foreach (string item in t_TbList.Keys)
{
t_FCAPI = t_WsAPI.OpenFeatureClass(t_TbList[item]);
dicTable.Add(new DataDicTionary() { NAME = item, CODE = t_TbList[item], REMARK = t_FCAPI.FeatureClass.ShapeType.ToString() });
t_FCAPI.CloseFeatureClass();
}
foreach (string item in t_TbList2.Keys)
{
t_FCAPI = t_WsAPI.OpenFeatureClass(t_TbList2[item]);
dicTable.Add(new DataDicTionary() { NAME = item, CODE = t_TbList2[item], REMARK = t_FCAPI.FeatureClass.ShapeType.ToString() });
t_FCAPI.CloseFeatureClass();
}
#endregion
List<DDTCDataMapping> MappingList = new List<DDTCDataMapping>();
foreach (IFeatureClass pSourceFeatureClass in pSourceFeatureClasses)
{
// pSourceFeatureClass.CheckArea();
DDTCDataMapping mapping = new DDTCDataMapping();
mapping.State = TBState.Waiting;
mapping.S_TableName = (pSourceFeatureClass as FeatureClass).Name;
mapping.S_TableAliasName = pSourceFeatureClass.AliasName;
mapping.PropertyChanged2 += mapping_PropertyShapeChanged2;
mapping.S_Spatial = (pSourceFeatureClass as IGeoDataset).SpatialReference.Name;
mapping.S_TableType = pSourceFeatureClass.ShapeType.ToString();
DataDicTionary dic = dicTable.FirstOrDefault(f => f.NAME == (string.IsNullOrWhiteSpace(pSourceFeatureClass.AliasName) ? (pSourceFeatureClass as FeatureClass).Name : pSourceFeatureClass.AliasName) || f.CODE == (string.IsNullOrWhiteSpace(pSourceFeatureClass.AliasName) ? (pSourceFeatureClass as FeatureClass).Name : pSourceFeatureClass.AliasName));
if (dic != null)
{
mapping.T_TableAliasName = dic.NAME;
mapping.T_TableName = dic.CODE;
mapping.T_TableType = dic.REMARK;
}
else
{
dic = dicTable.Find(f => f.NAME == string.Format("基础_{0}", (string.IsNullOrWhiteSpace(pSourceFeatureClass.AliasName) ? (pSourceFeatureClass as FeatureClass).Name : pSourceFeatureClass.AliasName)) ||
f.CODE == string.Format("JC_{0}", (string.IsNullOrWhiteSpace(pSourceFeatureClass.AliasName) ? (pSourceFeatureClass as FeatureClass).Name : pSourceFeatureClass.AliasName)));
if (dic != null)
{
mapping.T_TableAliasName = dic.NAME;
mapping.T_TableName = dic.CODE;
mapping.T_TableType = dic.REMARK;
}
}
mapping.T_TableList = dicTable.Where(w => w.REMARK == mapping.S_TableType || w.CODE == "null" || w.CODE == "Add").ToList();
SetShapeDefaultFieldMapping(mapping, t_WsAPI);
MappingList.Add(mapping);
}
dgTableMapping.ItemsSource = MappingList;
JudgeIsTheSameSpatialReference();
}
catch (Exception ex)
{
LogAPI.Debug("获取单独图层列表数据失败:" + ex);
MessageHelper.Show("获取单独图层列表数据失败:" + ex);
}
finally
{
if (t_WsAPI != null)
t_WsAPI.CloseWorkspace();
}
}
private void SetTableMapping()
{
IWorkspaceAPI t_WsAPI = null;
IWorkspaceAPI s_WsAPI = null;
IFeatureClassAPI s_FCAPI = null;
try
{
dgTableMapping.ItemsSource = null;
string s_MdbPath = null;
if (ImportDataType == "VCT")
{
s_MdbPath = SourceMDBPath;
}
else
{
s_MdbPath = btnImportDataPath.EditValue.ToString();
}
if ((ImportDataType == "MDB" || ImportDataType == "VCT") && !File.Exists(s_MdbPath))
{
ProgressHelper.CloseProcessBar();
MessageHelper.ShowTips("请确保文件存在,并且为mdb文件!");
return;
}
else if (ImportDataType == "GDB" && !Directory.Exists(s_MdbPath))
{
ProgressHelper.CloseProcessBar();
MessageHelper.ShowTips("请确保GDB文件夹存在!");
return;
}
if (ImportDataType == "MDB" || ImportDataType == "VCT")
{
FileInfo s_MdbPathInfo = new FileInfo(s_MdbPath);
if (!s_MdbPathInfo.Extension.Equals(".mdb"))
{
ProgressHelper.CloseProcessBar();
MessageHelper.ShowTips("必须为mdb文件才能进行导入!");
return;
}
}
string t_GdbPath = pTargetGDBPath;
if (ImportDataType == "MDB" || ImportDataType == "VCT")
{
s_WsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.MDBFile);
}
else
{
s_WsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.GDBFile);
}
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
t_WsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
t_WsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
Dictionary<string, string> t_TbList = t_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureDataset).Where(X => !X.Value.StartsWith("TDQSQ") && !X.Value.StartsWith("JC_CZCDYD")).ToDictionary(X => X.Key, Y => Y.Value);//周旺华 0424 排除TDQSQ导致的导入问题
Dictionary<string, string> t_TbList2 = t_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureClass);
List<DataDicTionary> dicTable = new List<DataDicTionary>();
dicTable.Add(new DataDicTionary() { NAME = "Null", CODE = "null" });
dicTable.Add(new DataDicTionary() { NAME = "追加图层", CODE = "Add" });
List<string> excludeList = new List<string>() { "地类图斑更新", "DLTBGX", "地类图斑更新过程", "DLTBGXGC", "行政区更新", "XZQGX", "行政区更新过程", "XZQGXGC", "村级调查区更新", "CJDCQGX", "村级调查区更新过程", "CJDCQGXGC", "行政区界线更新", "XZQJXGX", "村级调查区界线更新", "CJDCQJXGX", "城镇村等用地更新", "CZCDYDGX", "城镇村等用地更新过程", "CZCDYDGXGC" };
List<string> OnlyLoadList = new List<string>() { "工厂化种植更新","GCHZZGX", "坡度图更新", "PDTGX", "拆除未尽区更新", "CCWJQGX", "耕地等别更新", "GDDBGX", "光伏板区更新", "GFBQGX", "路面范围更新", "LMFWGX", "推土区更新", "TTQGX" };
foreach (string item in t_TbList.Keys)
{
if (!OnlyLoadList.Contains(item)) continue;
s_FCAPI = t_WsAPI.OpenFeatureClass(t_TbList[item]);
dicTable.Add(new DataDicTionary() { NAME = item, CODE = t_TbList[item], REMARK = s_FCAPI.FeatureClass.ShapeType.ToString() });
}
foreach (string item in t_TbList2.Keys)
{
s_FCAPI = t_WsAPI.OpenFeatureClass(t_TbList2[item]);
dicTable.Add(new DataDicTionary() { NAME = item, CODE = t_TbList2[item], REMARK = s_FCAPI.FeatureClass.ShapeType.ToString() });
}
List<KeyAndValue> s_TbList = s_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureDataset).Where(x => !x.Value.StartsWith("TDQSQ")).Select(x => new KeyAndValue() { S_Key = x.Key, S_Value = x.Value }).ToList();//周旺华 0424 排除TDQSQ导致的导入问题
Dictionary<string, string> s_TbList2 = s_WsAPI.GetFeatureClassName(esriDatasetType.esriDTFeatureClass);
Dictionary<string, string> s_TbList3 = s_WsAPI.GetFeatureClassName(esriDatasetType.esriDTTable);
foreach (string item in s_TbList2.Keys)
{
if (!s_TbList.Select(x => x.S_Value).Contains(item))
s_TbList.Add(new KeyAndValue() { S_Key = item, S_Value = s_TbList2[item] });
}
bool appzj = false;
if (t_TbList != null && s_TbList != null)
{
List<DDTCDataMapping> MappingList = new List<DDTCDataMapping>();
var zjlist = s_TbList.Where(x => x.S_Value.EndsWith("ZJ")).ToList();
var zjcount = zjlist.Count();
if (zjcount == 1)//补充不足的注记图层
{
appzj = true;
var appzjcount = t_TbList.Values.Where(x => x.EndsWith("ZJ")).Count() - 1;
var ofindex = s_TbList.IndexOf(s_TbList.SingleOrDefault(x => x.S_Value == "ZJ"));
var templist = new List<KeyAndValue>();
for (var i = 0; i < appzjcount; i++)
{
templist.Add(new KeyAndValue() { S_Key = zjlist[0].S_Key, S_Value = zjlist[0].S_Value });
}
s_TbList.InsertRange(ofindex, templist);
}
var zjindex = 0;
var tzjlist = dicTable.Where(x => x.CODE.EndsWith("ZJ")).ToList();
foreach (string key in s_TbList.Select(x => x.S_Key))
{
var keyvalue = s_TbList.FirstOrDefault(x => x.S_Key == key).S_Value;
//if (excludeList.Contains(key)) continue;
if (!OnlyLoadList.Contains(key)) continue;
DDTCDataMapping mapping = new DDTCDataMapping();
mapping.PropertyChanged2 += mapping_PropertyChanged2;
mapping.State = TBState.Waiting;
mapping.S_TableName = keyvalue;
mapping.S_TableAliasName = key;
if (s_TbList3.Values.Contains(mapping.S_TableName))
{
mapping.S_TableType = "Table";
}
else
{
s_FCAPI = s_WsAPI.OpenFeatureClass(keyvalue);
mapping.S_Spatial = (s_FCAPI.FeatureClass as IGeoDataset).SpatialReference.Name;
mapping.S_TableType = s_FCAPI.FeatureClass.ShapeType.ToString();
s_FCAPI.CloseFeatureClass();
}
DataDicTionary dic = dicTable.Find(f => f.NAME == key || f.CODE == keyvalue);
if (appzj && keyvalue == "ZJ" && tzjlist.Count > 0)
{
dic = tzjlist[zjindex];
mapping.S_YSDM_SQL = "YSDM='" + GetRuleTableEntityByTableName(dic.CODE).YSDM + "'";
zjindex++;
}
if (dic != null)
{
mapping.T_TableAliasName = dic.NAME;
mapping.T_TableName = dic.CODE;
mapping.T_TableType = dic.REMARK;
}
mapping.T_TableList = dicTable.Where(w => w.REMARK == mapping.S_TableType || w.CODE == "null" || w.CODE == "Add").ToList();
SetDefaultFieldMapping(mapping, s_WsAPI, t_WsAPI);
MappingList.Add(mapping);
}
dgTableMapping.ItemsSource = MappingList;
}
JudgeIsTheSameSpatialReference();
}
catch (Exception ex)
{
LogAPI.Debug("获取单独图层列表数据失败:" + ex);
MessageHelper.Show("获取单独图层列表数据失败:" + ex);
}
finally
{
if (s_WsAPI != null)
s_WsAPI.CloseWorkspace();
if (t_WsAPI != null)
t_WsAPI.CloseWorkspace();
if (s_FCAPI != null)
{
s_FCAPI.CloseFeatureClass();
s_FCAPI = null;
}
}
}
private void mapping_PropertyChanged2(object sender, PropertyChangedEventArgs e)
{
DDTCDataMapping maping = dgTableMapping.SelectedItem as DDTCDataMapping;
if (maping != null)
{
maping.T_TableType = maping.S_TableType;
SetDefaultFieldMapping(maping, null, null);
dgFieldMapping.ItemsSource = maping.FieldMapping;
}
}
private void mapping_PropertyShapeChanged2(object sender, PropertyChangedEventArgs e)
{
DDTCDataMapping maping = dgTableMapping.SelectedItem as DDTCDataMapping;
if (maping != null)
{
maping.T_TableType = maping.S_TableType;
SetShapeDefaultFieldMapping(maping, null);
dgFieldMapping.ItemsSource = maping.FieldMapping;
}
}
public void SetShapeDefaultFieldMapping(DDTCDataMapping tbMapping, IWorkspaceAPI pTargetWsAPI)
{
if (tbMapping.T_TableName == "Add")
{
return;
}
if (pTargetWsAPI == null)
{
string t_GdbPath = pTargetGDBPath;
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
else
{
pTargetWsAPI = null;
MessageHelper.ShowTips("无法识别的工程数据类型");
return;
}
}
IFeatureClassAPI t_FcAPI = null;
ITableAPI t_TBAPI = null;
IFeatureClassAPI s_FcAPI = null;
ITableAPI s_TBAPI = null;
try
{
if (!string.IsNullOrWhiteSpace(tbMapping.S_TableName) && !string.IsNullOrWhiteSpace(tbMapping.T_TableName) && !tbMapping.T_TableName.Equals("NULL", StringComparison.OrdinalIgnoreCase))
{
if (tbMapping.T_TableType.Equals("TABLE", StringComparison.OrdinalIgnoreCase))
{
t_TBAPI = pTargetWsAPI.OpenTable(tbMapping.T_TableName);
}
else
{
t_FcAPI = pTargetWsAPI.OpenFeatureClass(tbMapping.T_TableName);
}
s_FcAPI = new FeatureClassAPI(pSourceFeatureClasses.Where(p => (p as FeatureClass).Name.Equals(tbMapping.S_TableName) || p.AliasName.Equals(tbMapping.S_TableName)).Single());
List<DataDicTionary> dicData = new List<DataDicTionary>();
dicData.Add(new DataDicTionary() { DisplayName = "Null", NAME = "Null", CODE = "-1", REMARK = "" });
dicData.Add(new DataDicTionary() { DisplayName = "追加字段", NAME = "Add", CODE = "-2", REMARK = "" });
if (t_FcAPI != null)
{
for (int i = 0; i < t_FcAPI.FeatureClass.Fields.FieldCount; i++)
{
IField field = t_FcAPI.FeatureClass.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
dicData.Add(new DataDicTionary() { DisplayName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName, NAME = field.Name, CODE = i.ToString(), REMARK = field.Type.ToString() });
}
}
else if (t_TBAPI != null)
{
for (int i = 0; i < t_TBAPI.ITable.Fields.FieldCount; i++)
{
IField field = t_TBAPI.ITable.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
dicData.Add(new DataDicTionary() { DisplayName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName, NAME = field.Name, CODE = i.ToString(), REMARK = field.Type.ToString() });
}
}
if (s_FcAPI != null && s_FcAPI.FeatureClass != null)
{
List<FieldMapping> data = new List<FieldMapping>();
for (int i = 0; i < s_FcAPI.FeatureClass.Fields.FieldCount; i++)
{
IField field = s_FcAPI.FeatureClass.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
FieldMapping item = new FieldMapping();
item.S_FieldName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName;
item.S_FieldIndex = i;
DataDicTionary dic = dicData.FirstOrDefault(f => (f.NAME == field.Name || f.DisplayName == field.Name || f.NAME == field.AliasName || f.DisplayName == field.AliasName));
if (dic != null)
{
item.T_FieldName = dic.DisplayName;
item.T_FieldIndex = Convert.ToInt16(dic.CODE);
}
else
{
item.T_FieldIndex = -1;
}
item.FieldList = dicData.FindAll(f => f.REMARK == field.Type.ToString() || f.REMARK.Contains("Double") || f.REMARK.Contains("Integer") || f.CODE == "-1" || f.CODE == "-2");
data.Add(item);
}
tbMapping.FieldMapping = data;
}
else if (s_TBAPI != null && s_TBAPI.ITable != null)
{
List<FieldMapping> data = new List<FieldMapping>();
for (int i = 0; i < s_TBAPI.ITable.Fields.FieldCount; i++)
{
IField field = s_TBAPI.ITable.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
FieldMapping item = new FieldMapping();
item.S_FieldName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName;
item.S_FieldIndex = i;
DataDicTionary dic = dicData.FirstOrDefault(f => (f.NAME == field.Name || f.DisplayName == field.Name || f.NAME == field.AliasName || f.DisplayName == field.AliasName));
if (dic != null)
{
item.T_FieldName = dic.DisplayName;
item.T_FieldIndex = Convert.ToInt16(dic.CODE);
}
else
{
item.T_FieldIndex = -1;
}
item.FieldList = dicData.FindAll(f => f.REMARK == field.Type.ToString() || f.CODE == "-1" || f.CODE == "-2");
data.Add(item);
}
tbMapping.FieldMapping = data;
}
}
}
catch (Exception ex)
{
MessageHelper.ShowTips("操作异常!" + ex.Message);
LogAPI.Debug(ex);
}
}
#region 判断是否是一样的坐标参考系
/// <summary>
/// 判断选中的数据参考坐标系是否和目标数据库一致
/// </summary>
public void JudgeIsTheSameSpatialReference()
{
try
{
#region 判断参考坐标系是否一致
int iIsShape = 0;
if (ImportDataType == "VCT")
{
iIsShape = 0;
}
else
{
if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("Shape"))
{
iIsShape = 1;
}
else
{
if (ImportDataType == "GDB")
{
iIsShape = 0;
}
else
{
iIsShape = 0;
}
}
}
if (iIsShape == 0)
{
JudgeIsTheSameSpatialReference_UnShape();
}
else
{
JudgeIsTheSameSpatialReference_Shape();
}
string s_MdbPath_T = null;
if (ImportDataType == "VCT")
{
s_MdbPath_T = SourceMDBPath;
}
else
{
s_MdbPath_T = btnImportDataPath.EditValue.ToString();
}
if (string.IsNullOrWhiteSpace(s_MdbPath_T) == false)
{
if (this.Set_BtnLoad_Activated != null)
{
this.Set_BtnLoad_Activated(null, null);
}
}
else
{
if (this.Set_BtnLoad_UnActivated != null)
{
this.Set_BtnLoad_UnActivated(null, null);
}
}
#endregion
}
catch (Exception ex)
{
LogAPI.Debug("判断选中的数据参考坐标系是否和目标数据库一致 时失败,异常原因: " + ex + " ; ");
}
}
/// <summary>
/// 判断选中的数据参考坐标系是否和目标数据库一致-非Shape时
/// </summary>
public void JudgeIsTheSameSpatialReference_UnShape()
{
List<DDTCDataMapping> mapping = dgTableMapping.ItemsSource as List<DDTCDataMapping>;
IWorkspaceAPI pSourceWsAPI = null;
IWorkspaceAPI pTargetWsAPI = null;
try
{
if (shutDown)
{
MessageHelper.Show("当前状态是 shutDown,故无法导入!");
ResetImport();
return;
}
string s_MdbPath = null;
if (ImportDataType == "VCT")
{
s_MdbPath = SourceMDBPath;
}
else
{
s_MdbPath = btnImportDataPath.EditValue.ToString();
}
string t_GdbPath = pTargetGDBPath;
if (string.IsNullOrWhiteSpace(s_MdbPath) || string.IsNullOrWhiteSpace(t_GdbPath))
{
MessageHelper.Show("导入数据或工程数据获取失败,故无法导入!");
ResetImport();
return;
}
if (ImportDataType == "MDB" || ImportDataType == "VCT" || ImportDataType == "DCSJ")
{
if (!File.Exists(s_MdbPath) || !Directory.Exists(t_GdbPath))
{
MessageHelper.Show("导入数据或工程数据获取失败,故无法导入!");
ResetImport();
return;
}
pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.MDBFile);
}
else
{
if (!Directory.Exists(s_MdbPath) || !Directory.Exists(t_GdbPath))
{
MessageHelper.Show("导入数据或工程数据获取失败,故无法导入!");
ResetImport();
return;
}
pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.GDBFile);
}
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
if (mapping != null)
{
//循环导入要素类
string message = string.Empty;
string errorMessage = string.Empty;
//设置图层验证成功,失败变量
int SuccessJudgeLayerCount = 0;
int FailJudgeLayerCount = 0;
foreach (DDTCDataMapping table in mapping)
{
if (string.IsNullOrWhiteSpace(table.T_TableName) || table.T_TableName == "null")
{
//LogAPI.Debug("为空的不处理的 表源名称: " + table.S_TableName + " ; ");
//LogAPI.Debug("为空的不处理的 表源类型: " + table.S_TableType + " ; ");
continue;
}
if (JudgeData_UnShape(table, pSourceWsAPI, pTargetWsAPI, ref message, ref errorMessage, ref FailJudgeLayerCount) == true)
{
SuccessJudgeLayerCount += 1;
}
}
string sErrorShowMsg = "";
if (string.IsNullOrWhiteSpace(message) == false)
{
message = message.Substring(0, message.Length - 1);
sErrorShowMsg += "表名为: " + message + "的数据 坐标系与工程坐标系不一致,故无法导入!";
}
if (FailJudgeLayerCount > 0 || string.IsNullOrWhiteSpace(errorMessage) == false)
{
sErrorShowMsg += "验证失败的表数量: " + FailJudgeLayerCount + " 个; ";
sErrorShowMsg += "失败原因如下: " + errorMessage + " ; ";
}
if (!string.IsNullOrWhiteSpace(sErrorShowMsg))
{
MessageHelper.Show(sErrorShowMsg, false);
ResetImport();
}
}
return;
}
catch (Exception ex)
{
LogAPI.Debug("验证 " + ImportDataType + " 数据时失败,异常原因: " + ex + " ; ");
throw ex;
}
finally
{
if (pSourceWsAPI != null)
{
pSourceWsAPI.CloseWorkspace();
}
if (pTargetWsAPI != null)
{
pTargetWsAPI.CloseWorkspace();
}
if (mapping != null && mapping.Count() > 0)
{
mapping = null;
}
}
}
/// <summary>
/// 判断选中的数据参考坐标系是否和目标数据库一致-非Shape时---主方法
/// </summary>
/// <param name="pTbMaping"></param>
/// <param name="pSourceWsAPI"></param>
/// <param name="pTargetWsAPI"></param>
/// <param name="message"></param>
/// <param name="errorMessage"></param>
/// <param name="FailJudgeLayerCount"></param>
/// <returns></returns>
private bool JudgeData_UnShape(
DDTCDataMapping pTbMaping, IWorkspaceAPI pSourceWsAPI, IWorkspaceAPI pTargetWsAPI,
ref string message, ref string errorMessage, ref int FailJudgeLayerCount)
{
if (pSourceWsAPI == null || pSourceWsAPI.CurrentWorkspace == null || pTargetWsAPI == null || pTargetWsAPI.CurrentWorkspace == null)
{
FailJudgeLayerCount++;
errorMessage += (pTbMaping.S_TableName + "表失败原因: 导入数据或工程数据 工作空间获取失败 ; ");
return false;
}
IFeatureClassAPI t_FcAPI = null;
IFeatureClassAPI s_FcAPI = null;
try
{
if (pSourceWsAPI.CurrentWorkspace == null || pTargetWsAPI.CurrentWorkspace == null)
{
FailJudgeLayerCount++;
errorMessage += (pTbMaping.S_TableName + "表失败原因: 导入数据或工程数据 工作空间获取失败 ; ");
return false;
}
if (!string.IsNullOrWhiteSpace(pTbMaping.S_TableName) && !string.IsNullOrWhiteSpace(pTbMaping.T_TableName))
{
if (pTbMaping.S_TableType.ToUpper() != "TABLE")
{
s_FcAPI = pSourceWsAPI.OpenFeatureClass(pTbMaping.S_TableName);
}
if (pTbMaping.T_TableName != "Add")
{
if (pTbMaping.T_TableType.ToUpper() != "TABLE")
{
t_FcAPI = pTargetWsAPI.OpenFeatureClass(pTbMaping.T_TableName);
}
}
//判断坐标参考是否一致
if (t_FcAPI != null && s_FcAPI != null &&
(t_FcAPI.FeatureClass as IGeoDataset) != null &&
(s_FcAPI.FeatureClass as IGeoDataset) != null)
{
bool isEqual = KGIS.Framework.AE.GeoDBAPI.SpatialReferenceCompare(
(t_FcAPI.FeatureClass as IGeoDataset).SpatialReference,
(s_FcAPI.FeatureClass as IGeoDataset).SpatialReference
);
if (!isEqual)
{
message += pTbMaping.S_TableAliasName + ",";
return false;
}
}
return true;
}
else
{
FailJudgeLayerCount++;
errorMessage += (pTbMaping.S_TableName + "表失败原因:此导入数据表表名或者工程目标数据表表名 获取失败 ; ");
return false;
}
}
catch (Exception ex)
{
FailJudgeLayerCount++;
errorMessage += (pTbMaping.S_TableName + "表验证是否坐标参考系一致 时失败,异常原因: " + ex + " ; ");
return false;
}
finally
{
if (t_FcAPI != null)
t_FcAPI.CloseFeatureClass();
if (s_FcAPI != null)
s_FcAPI.CloseFeatureClass();
}
}
/// <summary>
/// 判断选中的数据参考坐标系是否和目标数据库一致-Shape时
/// </summary>
public void JudgeIsTheSameSpatialReference_Shape()
{
IWorkspaceAPI pTargetWsAPI = null;
try
{
if (shutDown)
{
MessageHelper.Show("当前状态是 shutDown,故无法导入!");
ResetImport();
return;
}
string t_GdbPath = pTargetGDBPath;
if (string.IsNullOrWhiteSpace(t_GdbPath) || !Directory.Exists(t_GdbPath))
{
//MessageHelper.ShowTips("未找到当前工程数据库");
MessageHelper.Show("未找到当前工程数据库,故无法导入!");
ResetImport();
return;
}
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
List<DDTCDataMapping> mapping = dgTableMapping.ItemsSource as List<DDTCDataMapping>;
if (mapping != null)
{
//循环判断要素类
string message = string.Empty;
string erroeMessage = string.Empty;
//设置图层验证成功,失败变量
int SuccessJudgeLayerCount = 0;
int FailJudgeLayerCount = 0;
foreach (DDTCDataMapping table in mapping)
{
if (string.IsNullOrWhiteSpace(table.T_TableName) || table.T_TableName == "null")
{
continue;
}
if (JudgeData_Shape(table, pTargetWsAPI, ref message, ref erroeMessage, ref FailJudgeLayerCount) == true)
{
SuccessJudgeLayerCount += 1;
}
}
string sErrorShowMsg = "";
if (string.IsNullOrWhiteSpace(message) == false)
{
message = message.Substring(0, message.Length - 1);
sErrorShowMsg += "表名为: " + message + "的数据 坐标系与工程坐标系不一致,故无法导入!";
}
if (FailJudgeLayerCount > 0 || string.IsNullOrWhiteSpace(erroeMessage) == false)
{
sErrorShowMsg += "验证失败的表数量: " + FailJudgeLayerCount + " 个; ";
sErrorShowMsg += "失败原因如下: " + erroeMessage + " ; ";
}
if (!string.IsNullOrWhiteSpace(sErrorShowMsg))
{
MessageHelper.Show(sErrorShowMsg, false);
ResetImport();
}
}
return;
}
catch (Exception ex)
{
LogAPI.Debug("验证 " + ImportDataType + " 数据时失败,异常原因: " + ex + " ; ");
throw ex;
}
finally
{
if (pTargetWsAPI != null)
{
pTargetWsAPI.CloseWorkspace();
}
}
}
/// <summary>
/// 判断选中的数据参考坐标系是否和目标数据库一致-Shape时---主方法
/// </summary>
/// <param name="pTbMaping"></param>
/// <param name="pTargetWsAPI"></param>
/// <param name="message"></param>
/// <param name="erroeMessage"></param>
/// <param name="FailJudgeLayerCount"></param>
/// <returns></returns>
private bool JudgeData_Shape(
DDTCDataMapping pTbMaping, IWorkspaceAPI pTargetWsAPI,
ref string message, ref string erroeMessage, ref int FailJudgeLayerCount)
{
if (pSourceFeatureClasses == null || pTargetWsAPI == null || pTargetWsAPI.CurrentWorkspace == null)
{
FailJudgeLayerCount++;
erroeMessage += (pTbMaping.S_TableName + "表失败原因:此导入数据表表名或者工程目标数据表表名 获取失败 ; ");
return false;
}
IFeatureClassAPI t_FcAPI = null;
IFeatureClass pSourceFeatureClass = null;
string currentFiled = string.Empty;
try
{
if (pTargetWsAPI.CurrentWorkspace == null)
{
FailJudgeLayerCount++;
erroeMessage += (pTbMaping.S_TableName + "表失败原因:当前工程工作空间 获取失败 ; ");
return false;
}
if (!string.IsNullOrWhiteSpace(pTbMaping.S_TableName) && !string.IsNullOrWhiteSpace(pTbMaping.T_TableName))
{
pSourceFeatureClass = pSourceFeatureClasses.Where(p => (p as FeatureClass).Name.Equals(pTbMaping.S_TableName) || p.AliasName.Equals(pTbMaping.S_TableName)).Single();
if (pSourceFeatureClass == null)
{
FailJudgeLayerCount++;
erroeMessage += (pTbMaping.S_TableName + "表失败原因:表元素 获取失败 ; ");
return false;
}
if (pTbMaping.T_TableName != "Add")
{
t_FcAPI = pTargetWsAPI.OpenFeatureClass(pTbMaping.T_TableName);
}
//判断坐标参考是否一致
if (t_FcAPI != null &&
(t_FcAPI.FeatureClass as IGeoDataset) != null &&
(pSourceFeatureClass as IGeoDataset) != null)
{
bool isEqual = KGIS.Framework.AE.GeoDBAPI.SpatialReferenceCompare(
(t_FcAPI.FeatureClass as IGeoDataset).SpatialReference,
(pSourceFeatureClass as IGeoDataset).SpatialReference
);
if (!isEqual)
{
message += pTbMaping.S_TableAliasName + ",";
return false;
}
}
return true;
}
else
{
FailJudgeLayerCount++;
erroeMessage += (pTbMaping.S_TableName + "表失败原因:此导入数据表表名或者工程目标数据表表名 获取失败 ; ");
return false;
}
}
catch (Exception ex)
{
FailJudgeLayerCount++;
erroeMessage += (pTbMaping.S_TableName + "表验证是否坐标参考系一致 时失败,异常原因: " + ex + " ; ");
return false;
}
finally
{
if (t_FcAPI != null)
t_FcAPI.CloseFeatureClass();
}
}
/// <summary>
/// 重置导入
/// </summary>
public void ResetImport()
{
try
{
//将选中的数据源地址清空
btnImportDataPath.EditValue = "";
//将映射关系置空
if (dgTableMapping != null)
{
if (dgTableMapping.ItemsSource != null)
{
dgTableMapping.ItemsSource = null;
}
dgTableMapping.UnselectAll();
dgTableMapping.RefreshData();
}
if (dgFieldMapping != null)
{
if (dgFieldMapping.ItemsSource != null)
{
dgFieldMapping.ItemsSource = null;
}
}
}
catch (Exception ex)
{
LogAPI.Debug("重置 " + ImportDataType + " 的导入失败,异常原因: " + ex + " ; ");
}
}
#endregion
private void btnOK_Click(object sender, RoutedEventArgs e)
{
try
{
if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("Shape"))
{
ExeSHP();
}
else
{
Exe();
}
}
catch (Exception ex)
{
LogAPI.Debug("单独图层加载失败:" + ex);
MessageHelper.Show("单独图层加载失败:" + ex);
}
}
#region 导入GDB、MDB、Vct格式的数据
public void Exe()
{
List<DDTCDataMapping> mapping = dgTableMapping.ItemsSource as List<DDTCDataMapping>;
this.btnOK.IsEnabled = false;
IWorkspaceAPI pSourceWsAPI = null;
IWorkspaceAPI pTargetWsAPI = null;
try
{
if (btnImportDataPath.EditValue == null)
{
MessageHelper.ShowTips("请先选择要导入的 " + ImportDataType + " 数据");
return;
}
else
{
if (ImportDataType == "GDB")
{
if (Directory.Exists(btnImportDataPath.EditValue.ToString()) == false)
{
MessageHelper.ShowTips("无效的 " + ImportDataType + " 数据源");
btnImportDataPath.EditValue = "";
return;
}
else
{
if (btnImportDataPath.EditValue.ToString().ToLower().EndsWith(".gdb") == false)
{
MessageHelper.ShowTips("无效的 " + ImportDataType + " 数据源");
btnImportDataPath.EditValue = "";
return;
}
}
}
else//MDB/VCT/DCSJ
{
if (File.Exists(btnImportDataPath.EditValue.ToString()) == false)
{
MessageHelper.ShowTips("无效的 " + ImportDataType + " 数据源");
btnImportDataPath.EditValue = "";
return;
}
}
}
string s_MdbPath = null;
if (ImportDataType == "VCT")
{
s_MdbPath = SourceMDBPath;
}
else
{
s_MdbPath = btnImportDataPath.EditValue.ToString();
}
string t_GdbPath = pTargetGDBPath;
if (string.IsNullOrWhiteSpace(s_MdbPath) || string.IsNullOrWhiteSpace(t_GdbPath))
{
return;
}
if (ImportDataType == "MDB" || ImportDataType == "VCT" || ImportDataType == "DCSJ")
{
if (!File.Exists(s_MdbPath) || !Directory.Exists(t_GdbPath))
{
return;
}
pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.MDBFile);
}
else
{
if (!Directory.Exists(s_MdbPath) || !Directory.Exists(t_GdbPath))
{
return;
}
pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.GDBFile);
}
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
if (mapping != null)
{
//ILayer zltcGroup = MapsManager.Instance.MapService.GetGroupLayer("ZLTC");//获取增量图层组
//ILayer zltcGroup = MapsManager.Instance.MapService.GetGroupLayer("ZLCG");//获取增量图层组
//循环导入要素类
string message = string.Empty;
string errorMessage = string.Empty;
int SuccessImportLayerCount = 0;
int DeletedImportLayerCount = 0;
int FailImportLayerCount = 0;
foreach (DDTCDataMapping table in mapping)
{
if (shutDown)
{
return;
}
if (table.State == TBState.Delete)
continue;
if (string.IsNullOrWhiteSpace(table.T_TableName) || table.T_TableName == "null")
continue;
dgTableMapping.SelectedItem = table;
dgTableMapping.View.ScrollIntoView(dgTableMapping.SelectedItem);
System.Windows.Forms.Application.DoEvents();
table.State = TBState.BeingImport;
if (ImportData(table, pSourceWsAPI, pTargetWsAPI, ref message, ref errorMessage, ref FailImportLayerCount))
{
table.State = TBState.EndImport;
SuccessImportLayerCount++;
//已存在图层,仅仅加入数据即可;
//AddLayerToMap(pSourceWsAPI, zltcGroup, table);
}
else
{
table.State = TBState.Delete;
DeletedImportLayerCount++;
}
}
MapsManager.Instance.MapService.getAxMapControl().ActiveView.ContentsChanged();
MapsManager.Instance.MapService.getAxMapControl().ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground | esriViewDrawPhase.esriViewForeground |
esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGeoSelection |
esriViewDrawPhase.esriViewGraphics | esriViewDrawPhase.esriViewGraphicSelection, null, MapsManager.Instance.MapService.getAxMapControl().ActiveView.Extent);
MapsManager.Instance.MapService.getAxMapControl().Refresh();
Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "RefreshLayer" });
try
{
SaveProject();
}
catch (Exception ex)
{
LogAPI.Debug("添加图层到地图时发生异常:" + ex);
}
this.btnOK.IsEnabled = true;
if (!string.IsNullOrWhiteSpace(message))
{
message = message.Substring(0, message.Length - 1);
MessageHelper.ShowTips(message + "坐标系与工程坐标系不一致,无法导入!");
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
errorMessage = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
DeletedImportLayerCount, FailImportLayerCount) + errorMessage;
MessageHelper.Show(errorMessage, true);
}
else
{
int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
message = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
DeletedImportLayerCount, FailImportLayerCount) + message;
MessageHelper.Show(message, true);
}
//这里设置关闭
if (this.Close_FrmBaseDataLoad != null)
{
this.Close_FrmBaseDataLoad(null, null);
}
}
}
catch (Exception ex)
{
LogAPI.Debug(string.Format("导入{0}数据时失败,异常原因:{1}; ", ImportDataType, ex));
MessageHelper.Show(string.Format("导入{0}数据时失败,异常原因:{1}; ", ImportDataType, ex));
}
finally
{
this.btnOK.IsEnabled = true;
if (pSourceWsAPI != null)
{
pSourceWsAPI.CloseWorkspace();
}
if (pTargetWsAPI != null)
{
pTargetWsAPI.CloseWorkspace();
}
if (mapping != null && mapping.Count() > 0)
{
mapping = null;
}
}
}
private bool ImportData(DDTCDataMapping pTbMaping, IWorkspaceAPI pSourceWsAPI, IWorkspaceAPI pTargetWsAPI, ref string message, ref string errorMessage, ref int FailImportLayerCount)
{
if (pSourceWsAPI == null || pSourceWsAPI.CurrentWorkspace == null || pTargetWsAPI == null || pTargetWsAPI.CurrentWorkspace == null)
return false;
IFeatureClassAPI t_FcAPI = null;
ITableAPI t_TbAPI = null;
IFeatureClassAPI s_FcAPI = null;
ITableAPI s_TbAPI = null;
EngineEditor editor = null;
string currentFiled = string.Empty;
try
{
if (pSourceWsAPI.CurrentWorkspace == null || pTargetWsAPI.CurrentWorkspace == null)
return false;
if (!string.IsNullOrWhiteSpace(pTbMaping.S_TableName) && !string.IsNullOrWhiteSpace(pTbMaping.T_TableName))
{
if (pTargetWsAPI.CurrentWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
editor = new EngineEditorClass();
if (editor.EditState != esriEngineEditState.esriEngineStateEditing)
{
editor.StartEditing(pTargetWsAPI.CurrentWorkspace, pMap);
}
}
if (pTbMaping.S_TableType.ToUpper() == "TABLE")
{
s_TbAPI = pSourceWsAPI.OpenTable(pTbMaping.S_TableName);
}
else
{
s_FcAPI = pSourceWsAPI.OpenFeatureClass(pTbMaping.S_TableName);
}
if (pTbMaping.T_TableName == "Add")
{
if (s_FcAPI != null)
{
IFields fields = null;
GeoDBAPI.CreateFields(s_FcAPI.FeatureClass.Fields, out fields);
IGeoDataset ds = s_FcAPI.FeatureClass as IGeoDataset;
if (fields != null && ds != null)
{
t_FcAPI = pTargetWsAPI.CreateFeatureClass(pTbMaping.S_TableName, ds.SpatialReference, fields);
pTbMaping.T_TableName = pTbMaping.S_TableName;
pTbMaping.T_TableType = pTbMaping.S_TableType;
SetDefaultFieldMapping(pTbMaping, pSourceWsAPI, pTargetWsAPI);
}
}
else if (s_TbAPI != null)
{
IFields fields = null;
GeoDBAPI.CreateFields(s_TbAPI.ITable.Fields, out fields);
IGeoDataset ds = s_FcAPI.FeatureClass as IGeoDataset;
if (fields != null && ds != null)
{
t_TbAPI = pTargetWsAPI.CreateTable(pTbMaping.S_TableName, fields);
pTbMaping.T_TableType = pTbMaping.S_TableType;
SetDefaultFieldMapping(pTbMaping, pSourceWsAPI, pTargetWsAPI);
}
}
}
else
{
if (pTbMaping.T_TableType.ToUpper() == "TABLE")
{
t_TbAPI = pTargetWsAPI.OpenTable(pTbMaping.T_TableName);
}
else
{
t_FcAPI = pTargetWsAPI.OpenFeatureClass(pTbMaping.T_TableName);
}
}
//判断坐标参考是否一致
if (t_FcAPI != null && s_FcAPI != null &&
(t_FcAPI.FeatureClass as IGeoDataset) != null &&
(s_FcAPI.FeatureClass as IGeoDataset) != null)
{
bool isEqual = KGIS.Framework.AE.GeoDBAPI.SpatialReferenceCompare((t_FcAPI.FeatureClass as IGeoDataset).SpatialReference, (s_FcAPI.FeatureClass as IGeoDataset).SpatialReference);
if (!isEqual)
{
message += pTbMaping.S_TableAliasName + ",";
return false;
}
}
#region 如果替换已有数据,则将已有数据删除
if (cbReplace.IsChecked == true)
{
if (t_FcAPI != null && t_FcAPI.FeatureClass != null)
{
//优化代码,提高效率29s左右 王欢 2019-03-25
//(t_FcAPI.FeatureClass as ITable).DeleteSearchedRows(null);
IDataset pDataset = t_FcAPI.FeatureClass as IDataset;
pDataset.Workspace.ExecuteSQL("delete from " + pDataset.BrowseName);
}
else if (t_TbAPI != null && t_TbAPI.ITable != null)
{
t_TbAPI.ITable.DeleteSearchedRows(null);
}
}
#endregion
ICursor s_Cursor = null;
IQueryFilter queryFilter = new QueryFilterClass();
var counstwhere = false;
if (string.IsNullOrWhiteSpace(pTbMaping.S_YSDM_SQL) == false)
{
counstwhere = true;
queryFilter.WhereClause = pTbMaping.S_YSDM_SQL;
}
if (s_FcAPI != null)
{
s_Cursor = (ICursor)s_FcAPI.FeatureClass.Search(counstwhere ? queryFilter : null, true);//判断条件查询
int DataCount = s_FcAPI.FeatureClass.FeatureCount(null);
pTbMaping.Count = DataCount;
}
else
{
s_Cursor = s_TbAPI.ITable.Search(counstwhere ? queryFilter : null, true);//判断条件查询
int DataCount = s_TbAPI.ITable.RowCount(null);
pTbMaping.Count = DataCount;
}
int i = 0;
if (t_FcAPI != null && t_FcAPI.FeatureClass != null)
{
IFeature feature = null;
#region IFeatureClass
#region 新增字段
List<int> addFieldIndexs = new List<int>();
if (pTbMaping.FieldMapping != null)
{
List<FieldMapping> addFields = pTbMaping.FieldMapping.FindAll(f => f.T_FieldIndex == -2);
foreach (FieldMapping item in addFields)
{
IField f = s_FcAPI.FeatureClass.Fields.get_Field(item.S_FieldIndex);
if (t_FcAPI.FeatureClass.FindField(f.Name) > -1)
{
t_FcAPI.AddField(f.Name + "_a", f.Type, f.AliasName);
item.T_FieldIndex = t_FcAPI.FeatureClass.Fields.FindField(f.Name + "_a");
}
else
{
t_FcAPI.AddField(f.Name, f.Type, f.AliasName);
item.T_FieldIndex = t_FcAPI.FeatureClass.Fields.FindField(f.Name);
}
addFieldIndexs.Add(item.T_FieldIndex);
}
}
#endregion
IFeatureClass t_FC = t_FcAPI.FeatureClass;
IDataset pDataset = t_FC as IDataset;
IWorkspace pWs = pDataset.Workspace;
IWorkspaceEdit pWsEdit = pWs as IWorkspaceEdit;
//pWsEdit.StartEditing(true);
pWsEdit.StartEditOperation();
IFeatureCursor t_FeatureCursor = t_FC.Insert(true);
IFeatureBuffer newFeature = null;
while ((feature = (s_Cursor as IFeatureCursor).NextFeature()) != null)
{
using (ComReleaser comReleaser = new ComReleaser())
{
//if (newFeature == null)
newFeature = t_FC.CreateFeatureBuffer();
newFeature.Shape = feature.ShapeCopy;
if (pTbMaping.FieldMapping != null)
{
foreach (FieldMapping item in pTbMaping.FieldMapping)
{
if (item.S_FieldIndex < 0 || item.T_FieldIndex < 0)
continue;
object val = feature.get_Value(item.S_FieldIndex);
currentFiled = item.S_FieldName;
bool canSetValue = false;
switch (newFeature.Fields.get_Field(item.T_FieldIndex).Type)
{
case esriFieldType.esriFieldTypeSmallInteger:
int intValue = 0;
if (int.TryParse(val.ToString(), out intValue))
{
canSetValue = true;
//修改人:高山 修改时间:2018.12.4 修改原因:如果val不重新赋值,在入库后数据小数位数会变化,影响数据精度
val = intValue;
}
break;
case esriFieldType.esriFieldTypeDouble:
double doubleValue = 0;
if (double.TryParse(val.ToString(), out doubleValue))
{
canSetValue = true;
//修改人:高山 修改时间:2018.12.4 修改原因:如果val不重新赋值,在入库后数据小数位数会变化,影响数据精度
val = doubleValue;
}
break;
case esriFieldType.esriFieldTypeInteger:
int integerValue = 0;
if (int.TryParse(val.ToString(), out integerValue))
{
canSetValue = true;
//修改人:高山 修改时间:2018.12.4 修改原因:如果val不重新赋值,在入库后数据小数位数会变化,影响数据精度
val = integerValue;
}
break;
case esriFieldType.esriFieldTypeDate:
DateTime dateTimeValue;
if (DateTime.TryParse(val.ToString(), out dateTimeValue))
{
canSetValue = true;
//修改人:高山 修改时间:2018.12.4 修改原因:如果val不重新赋值,在入库后数据小数位数会变化,影响数据精度
val = dateTimeValue;
}
break;
case esriFieldType.esriFieldTypeString:
canSetValue = true;
if (string.IsNullOrWhiteSpace(val.ToString()))
{
val = DBNull.Value;
}
break;
default:
canSetValue = true;
break;
}
if (canSetValue)
{
if (val is int)
{
if ((int)val == 0)
continue;
}
if (val is double)
{
if ((currentFiled == "扣除地类系数" || currentFiled == "扣除地类面积") && (double)val == 0)//解决禅道问题 25839 扣除地类系数与扣除地类面积字段为0,导入表中也要为0
{
newFeature.set_Value(item.T_FieldIndex, val);
}
else if ((double)val == 0)
continue;
}
newFeature.set_Value(item.T_FieldIndex, val);
}
else //20190123 周旺华 未处理数据直接赋为DBNull.Value
{
newFeature.set_Value(item.T_FieldIndex, DBNull.Value);
}
}
}
t_FeatureCursor.InsertFeature(newFeature);
comReleaser.ManageLifetime(feature);
}
i++;
if (i % 1000 == 0 || i == pTbMaping.Count)
{
pTbMaping.Progress = i;
System.Windows.Forms.Application.DoEvents();
}
}
if (newFeature != null)
{
t_FeatureCursor.Flush();
Marshal.ReleaseComObject(newFeature);
}
Marshal.ReleaseComObject(t_FeatureCursor);
pWsEdit.StopEditOperation();
#endregion
}
else if (t_TbAPI != null && t_TbAPI.ITable != null)
{
#region ITable
IRow s_Row = null;
ICursor t_Cursor = t_TbAPI.ITable.Insert(true);
IRowBuffer t_RowBuffer = null;
while ((s_Row = s_Cursor.NextRow()) != null)
{
using (ComReleaser comReleaser = new ComReleaser())
{
if (t_RowBuffer == null)
t_RowBuffer = t_TbAPI.ITable.CreateRowBuffer();
foreach (FieldMapping item in pTbMaping.FieldMapping)
{
if (item.S_FieldIndex < 0 || item.T_FieldIndex < 0)
{
continue;
}
t_RowBuffer.set_Value(item.T_FieldIndex, s_Row.get_Value(item.S_FieldIndex));
}
t_Cursor.InsertRow(t_RowBuffer);
ComReleaser.ReleaseCOMObject(s_Row);
}
i++;
if (i % 100 == 0 || i == pTbMaping.Count)
{
pTbMaping.Progress = i;
System.Windows.Forms.Application.DoEvents();
}
}
if (t_RowBuffer != null)
{
t_Cursor.Flush();
Marshal.ReleaseComObject(t_RowBuffer);
}
Marshal.ReleaseComObject(t_Cursor);
#endregion
}
Marshal.ReleaseComObject(s_Cursor);
return true;
}
return false;
}
catch (Exception ex)
{
if (pTargetWsAPI.CurrentWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
editor.AbortOperation();
}
FailImportLayerCount++;
errorMessage += (pTbMaping.S_TableName + "表,字段" + currentFiled + "数据导入异常!" + ex.Message);
return false;
}
finally
{
if (pTargetWsAPI.CurrentWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
editor.StopEditing(true);
}
if (t_TbAPI != null)
t_TbAPI.CloseTable();
if (t_FcAPI != null)
t_FcAPI.CloseFeatureClass();
if (s_TbAPI != null)
s_TbAPI.CloseTable();
if (s_FcAPI != null)
s_FcAPI.CloseFeatureClass();
}
}
private void AddLayerToMap(IWorkspaceAPI pSourceWsAPI, ILayer zltcGroup, DDTCDataMapping table)
{
try
{
if (pSourceWsAPI != null)
{
bool displayLayer = true;
if (zltcGroup != null)
{
ICompositeLayer pComLayer = zltcGroup as ICompositeLayer;
for (int i = 0; i < pComLayer.Count; i++)
{
ILayer layer = pComLayer.Layer[i];
if ((layer as IDataset).BrowseName == table.S_TableName)
{
displayLayer = false;
continue;
}
}
}
IFeatureClassAPI s_FcAPI = pSourceWsAPI.OpenFeatureClass(table.S_TableName);
if (s_FcAPI != null && s_FcAPI.FeatureClass != null && displayLayer == true)
{
IFeatureLayer pTargetLayer = new FeatureLayer();
pTargetLayer.FeatureClass = s_FcAPI.FeatureClass;
pTargetLayer.Name = table.T_TableAliasName;
ILegendInfo pLegendInfo = pTargetLayer as ILegendInfo;
int legendGroupCount = pLegendInfo.LegendGroupCount;
ILegendGroup pLGroup;
for (int i = 0; i < legendGroupCount; i++)
{
pLGroup = pLegendInfo.get_LegendGroup(i);
pLGroup.Visible = false;
}
(zltcGroup as IGroupLayer).Add(pTargetLayer);
}
}
}
catch (Exception ex)
{
LogAPI.Debug("图层添加至mxd失败" + ex);
}
}
#endregion
#region 导入shp格式的数据
public void ExeSHP()
{
IWorkspaceAPI pTargetWsAPI = null;
this.btnOK.IsEnabled = false;
try
{
string str = "1234567890";
string t_GdbPath = pTargetGDBPath;
if (string.IsNullOrWhiteSpace(t_GdbPath) || !Directory.Exists(t_GdbPath))
{
MessageHelper.ShowTips("未找到当前工程数据库");
return;
}
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
List<DDTCDataMapping> mapping = dgTableMapping.ItemsSource as List<DDTCDataMapping>;
if (mapping != null)
{
//ILayer zltcGroups = MapsManager.Instance.MapService.GetGroupLayer("ZLCG");//获取增量图层组
//LayerCfg GroupLayerInfo = null;
//if (_DataCatalog != null)
//{
// _DataCatalog.GetNodeByLayer(zltcGroups);
// LayerCfg rootLayer = _DataCatalog.CurrentLayers as LayerCfg;
// List<LayerCfg> AllLayers = rootLayer.GetAllItem();
// GroupLayerInfo = AllLayers.FirstOrDefault(f => f.LayerName == "增量图层");
//}
//循环导入要素类
string message = string.Empty;
string erroeMessage = string.Empty;
foreach (DDTCDataMapping table in mapping)
{
//增加控制,以数字开头的图层不能追加到当前工程。对应bug11125
if (str.Contains(table.S_TableName.Substring(0, 1)) && table.T_TableName == "Add")
{
MessageHelper.ShowTips("以数字开头的图层不能追加到当前工程!");
return;
}
if (shutDown)
{
break;
}
if (table.State == TBState.Delete)
continue;
if (string.IsNullOrWhiteSpace(table.T_TableName) || table.T_TableName == "null")
continue;
dgTableMapping.SelectedItem = table;
dgTableMapping.View.ScrollIntoView(dgTableMapping.SelectedItem);
System.Windows.Forms.Application.DoEvents();
table.State = TBState.BeingImport;
if (ImportData(table, pTargetWsAPI, ref message, ref erroeMessage))
{
table.State = TBState.EndImport;
//当前的变更/增量数据中的单独图层都已经存在的,不需要重新添加,导入数据即可;
//AddShpLayerToMap(GroupLayerInfo, table, pTargetWsAPI);
}
else
{
table.State = TBState.Delete;
}
}
//目录刷新 展开 试图刷新
//if (_DataCatalog != null)
//{
// if (GroupLayerInfo.Layers.Count > 0)
// GroupLayerInfo.Expanded = true;
// _DataCatalog.UpdateTree();
//}
MapsManager.Instance.MapService.getAxMapControl().Refresh();
try
{
SaveProject();//保存加载的图斑
}
catch (Exception ex)
{
LogAPI.Debug("添加图层到地图时发生异常:" + ex);
}
this.btnOK.IsEnabled = true;
if (!string.IsNullOrWhiteSpace(message))
{
message = message.Substring(0, message.Length - 1);
MessageHelper.ShowTips(message + "坐标系与工程坐标系不一致,无法导入!");
}
if (!string.IsNullOrWhiteSpace(erroeMessage))
{
MessageHelper.ShowTips(erroeMessage);
}
if (string.IsNullOrWhiteSpace(message) && string.IsNullOrWhiteSpace(erroeMessage))
{
MessageHelper.ShowTips("导入完成!");
}
//这里设置关闭
this.Close_FrmBaseDataLoad?.Invoke(null, null);
}
else
{
if (btnImportDataPath.EditValue == null)
{
MessageHelper.ShowTips("请先选择 Shape 数据源");
}
else
{
string s_MdbPath_T2 = btnImportDataPath.EditValue.ToString();
if (string.IsNullOrWhiteSpace(s_MdbPath_T2) == true)
{
MessageHelper.ShowTips("请先选择 Shape 数据源");
}
else
{
if (Directory.Exists(s_MdbPath_T2) == false)
{
MessageHelper.ShowTips("选择的 Shape 数据源不存在");
btnImportDataPath.EditValue = "";
}
else
{
//判断目录下有没有shape文件
string[] strFiles = Directory.GetFiles(s_MdbPath_T2);
int iFileDirs = strFiles.Count();
List<string> ShapeFileNameList = strFiles.ToList();
if (ShapeFileNameList == null || ShapeFileNameList.Count <= 0)
{
MessageHelper.ShowTips("Shape 数据源不能为空");
btnImportDataPath.EditValue = "";
}
else
{
bool bHaveShp = false;
foreach (string strFile in strFiles)
{
if (strFile.ToLower().EndsWith(".shp") == true)
{
bHaveShp = true;
break;
}
}
if (bHaveShp == false)
{
MessageHelper.ShowTips("Shape 数据源不能为空");
btnImportDataPath.EditValue = "";
}
}
}
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug(string.Format("导入{0}数据时失败,异常原因:{1}; ", ImportDataType, ex));
MessageHelper.Show(string.Format("导入{0}数据时失败,异常原因:{1}; ", ImportDataType, ex));
}
finally
{
this.btnOK.IsEnabled = true;
if (pSourceFeatureClasses != null && pSourceFeatureClasses.Count > 0)
{
using (ComReleaser com = new ComReleaser())
{
foreach (IFeatureClass item in pSourceFeatureClasses)
{
com.ManageLifetime(item);
}
}
}
if (pTargetWsAPI != null)
{
pTargetWsAPI.CloseWorkspace();
}
}
}
private bool ImportData(DDTCDataMapping pTbMaping, IWorkspaceAPI pTargetWsAPI, ref string message, ref string erroeMessage)
{
if (pSourceFeatureClasses == null || pTargetWsAPI == null || pTargetWsAPI.CurrentWorkspace == null)
return false;
IFeatureClassAPI t_FcAPI = null;
IFeatureClass pSourceFeatureClass = null;
EngineEditor editor = null;
string currentFiled = string.Empty;
try
{
if (pTargetWsAPI.CurrentWorkspace == null)
return false;
if (!string.IsNullOrWhiteSpace(pTbMaping.S_TableName) && !string.IsNullOrWhiteSpace(pTbMaping.T_TableName))
{
if (pTargetWsAPI.CurrentWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
editor = new EngineEditorClass();
if (editor.EditState != esriEngineEditState.esriEngineStateEditing)
{
editor.StartEditing(pTargetWsAPI.CurrentWorkspace, pMap);
}
}
pSourceFeatureClass = pSourceFeatureClasses.Where(p => (p as FeatureClass).Name.Equals(pTbMaping.S_TableName) || p.AliasName.Equals(pTbMaping.S_TableName)).Single();
if (pSourceFeatureClass == null)
{
return false;
}
if (pTbMaping.T_TableName == "Add")
{
IFields fields = null;
GeoDBAPI.CreateFields(pSourceFeatureClass.Fields, out fields);
IGeoDataset ds = pSourceFeatureClass as IGeoDataset;
if (fields != null && ds != null)
{
t_FcAPI = pTargetWsAPI.CreateFeatureClass(pTbMaping.S_TableName, ds.SpatialReference, fields);
pTbMaping.T_TableName = pTbMaping.S_TableName;
pTbMaping.T_TableType = pTbMaping.S_TableType;
SetShapeDefaultFieldMapping(pTbMaping, pTargetWsAPI);
}
}
else
{
t_FcAPI = pTargetWsAPI.OpenFeatureClass(pTbMaping.T_TableName);
}
//判断坐标参考是否一致
if (t_FcAPI != null && (t_FcAPI.FeatureClass as IGeoDataset) != null && (pSourceFeatureClass as IGeoDataset) != null)
{
//bool isEqual = GeoDBAPI.SpatialReferenceCompare((t_FcAPI.FeatureClass as IGeoDataset).SpatialReference, (pSourceFeatureClass as IGeoDataset).SpatialReference);
if (!GeoDBAPI.SpatialReferenceCompare((t_FcAPI.FeatureClass as IGeoDataset).SpatialReference, (pSourceFeatureClass as IGeoDataset).SpatialReference))
{
message += pTbMaping.S_TableAliasName + ",";
return false;
}
}
#region 如果替换已有数据,则将已有数据删除
if (cbReplace.IsChecked == true && t_FcAPI != null && t_FcAPI.FeatureClass != null)
{
(t_FcAPI.FeatureClass as ITable).DeleteSearchedRows(null);
}
#endregion
ICursor s_Cursor = null;
s_Cursor = (ICursor)pSourceFeatureClass.Search(null, true);
int DataCount = pSourceFeatureClass.FeatureCount(null);
pTbMaping.Count = DataCount;
int i = 0;
if (t_FcAPI != null && t_FcAPI.FeatureClass != null)
{
IFeature feature = null;
#region IFeatureClass
#region 新增字段
List<int> addFieldIndexs = new List<int>();
if (pTbMaping.FieldMapping != null)
{
List<FieldMapping> addFields = pTbMaping.FieldMapping.FindAll(f => f.T_FieldIndex == -2);
foreach (FieldMapping item in addFields)
{
IField f = pSourceFeatureClass.Fields.get_Field(item.S_FieldIndex);
if (t_FcAPI.FeatureClass.FindField(f.Name) > -1)
{
t_FcAPI.AddField(f.Name + "_a", f.Type, f.AliasName);
item.T_FieldIndex = t_FcAPI.FeatureClass.Fields.FindField(f.Name + "_a");
}
else
{
t_FcAPI.AddField(f.Name, f.Type, f.AliasName);
item.T_FieldIndex = t_FcAPI.FeatureClass.Fields.FindField(f.Name);
}
addFieldIndexs.Add(item.T_FieldIndex);
}
}
#endregion
IFeatureClass t_FC = t_FcAPI.FeatureClass;
IFeatureCursor t_FeatureCursor = t_FC.Insert(true);
IFeatureBuffer newFeature = null;
while ((feature = (s_Cursor as IFeatureCursor).NextFeature()) != null)
{
using (ComReleaser comReleaser = new ComReleaser())
{
if (newFeature == null)
newFeature = t_FC.CreateFeatureBuffer();
newFeature.Shape = feature.ShapeCopy;
if (pTbMaping.FieldMapping != null)
{
foreach (FieldMapping item in pTbMaping.FieldMapping)
{
if (item.S_FieldIndex < 0 || item.T_FieldIndex < 0)
continue;
object val = feature.get_Value(item.S_FieldIndex);
currentFiled = item.S_FieldName;
bool canSetValue = false;
switch (newFeature.Fields.get_Field(item.T_FieldIndex).Type)
{
case esriFieldType.esriFieldTypeSmallInteger:
int intValue = 0;
if (int.TryParse(val.ToString(), out intValue))
{
canSetValue = true;
}
break;
case esriFieldType.esriFieldTypeDouble:
double doubleValue = 0;
if (double.TryParse(val.ToString(), out doubleValue))
{
canSetValue = true;
}
break;
case esriFieldType.esriFieldTypeInteger:
int integerValue = 0;
if (int.TryParse(val.ToString(), out integerValue))
{
canSetValue = true;
}
break;
case esriFieldType.esriFieldTypeDate:
DateTime dateTimeValue;
if (DateTime.TryParse(val.ToString(), out dateTimeValue))
{
canSetValue = true;
}
break;
case esriFieldType.esriFieldTypeString:
canSetValue = true;
if (string.IsNullOrWhiteSpace(val.ToString()))
{
val = DBNull.Value;
}
break;
default:
canSetValue = true;
break;
}
if (canSetValue)
{
newFeature.set_Value(item.T_FieldIndex, val);
}
else
{
newFeature.set_Value(item.T_FieldIndex, null);
}
}
}
t_FeatureCursor.InsertFeature(newFeature);
comReleaser.ManageLifetime(feature);
}
i++;
if (i % 100 == 0 || i == pTbMaping.Count)
{
pTbMaping.Progress = i;
System.Windows.Forms.Application.DoEvents();
}
}
if (newFeature != null)
{
t_FeatureCursor.Flush();
Marshal.ReleaseComObject(newFeature);
}
Marshal.ReleaseComObject(t_FeatureCursor);
#endregion
}
Marshal.ReleaseComObject(s_Cursor);
if (pTargetWsAPI.CurrentWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
editor.StopEditing(true);
}
return true;
}
return false;
}
catch (Exception ex)
{
if (pTargetWsAPI.CurrentWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
editor.AbortOperation();
}
erroeMessage += (pTbMaping.S_TableName + "表,字段" + currentFiled + "数据导入异常!" + ex.Message);
return false;
}
finally
{
if (pTargetWsAPI.CurrentWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
editor.StopEditing(true);
}
if (t_FcAPI != null)
t_FcAPI.CloseFeatureClass();
}
}
private void AddShpLayerToMap(LayerCfg zltcGroup, DDTCDataMapping table, IWorkspaceAPI pTargetWsAPI)
{
try
{
if (pSourceFeatureClasses != null && pSourceFeatureClasses.Count != 0)
{
bool displayLayer = true;
if (zltcGroup != null)
{
foreach (LayerCfg item in zltcGroup.Layers)
{
if (item.FcName == table.S_TableName)
{
displayLayer = false;//已存在不添加;
break;
}
}
}
//
IFeatureClass pSourceFeatureClass = pSourceFeatureClasses.Where(p => (p as FeatureClass).Name.Equals(table.S_TableName) || p.AliasName.Equals(table.S_TableName)).Single();
//IFeatureClassAPI pSourceFeatureClass = pTargetWsAPI.OpenFeatureClass(table.T_TableName);
if (pSourceFeatureClass != null && displayLayer == true)
{
IFeatureLayer pTargetLayer = new FeatureLayer
{
FeatureClass = pSourceFeatureClass,
Name = table.T_TableAliasName
};
ILegendInfo pLegendInfo = pTargetLayer as ILegendInfo;
int legendGroupCount = pLegendInfo.LegendGroupCount;
ILegendGroup pLGroup;
for (int i = 0; i < legendGroupCount; i++)
{
pLGroup = pLegendInfo.get_LegendGroup(i);
pLGroup.Visible = false;
}
_DataCatalog.AddLayer(pTargetLayer, zltcGroup);
}
}
}
catch (Exception ex)
{
LogAPI.Debug("图层添加至图层目录失败" + ex.Message);
}
}
#endregion
private void SaveProject()
{
try
{
Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
}
catch (Exception ex)
{
LogAPI.Debug("添加图层到地图时发生异常,异常信息如下:");
LogAPI.Debug(ex);
}
}
public void SetDefaultFieldMapping(DDTCDataMapping tbMapping, IWorkspaceAPI pSourceWsAPI, IWorkspaceAPI pTargetWsAPI)
{
if (tbMapping.T_TableName == "Add")
{
return;
}
if (pSourceWsAPI == null)
{
string s_MdbPath = null;
if (ImportDataType == "VCT")
{
s_MdbPath = SourceMDBPath;
}
else
{
s_MdbPath = btnImportDataPath.EditValue.ToString();
}
if (ImportDataType == "MDB" || ImportDataType == "VCT")
{
pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.MDBFile);
}
else
{
pSourceWsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.GDBFile);
}
}
if (pTargetWsAPI == null)
{
IFeatureClass pFeatureClass = null;
if (pFeatureClass == null)
{
string t_GdbPath = pTargetGDBPath;
if (t_GdbPath.ToLower().EndsWith(".gdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.GDBFile);
}
else if (t_GdbPath.ToLower().EndsWith(".mdb"))
{
pTargetWsAPI = new WorkspaceAPI(t_GdbPath, WorkspaceTypeEnum.MDBFile);
}
}
else
{
pTargetWsAPI = new WorkspaceAPI((pFeatureClass as FeatureClass).Workspace);
}
}
IFeatureClassAPI t_FcAPI = null;
ITableAPI t_TBAPI = null;
IFeatureClassAPI s_FcAPI = null;
ITableAPI s_TBAPI = null;
try
{
if (!string.IsNullOrWhiteSpace(tbMapping.S_TableName) && !string.IsNullOrWhiteSpace(tbMapping.T_TableName) && !tbMapping.T_TableName.ToUpper().Equals("NULL"))
{
if (tbMapping.T_TableType.ToUpper() == "TABLE")
{
t_TBAPI = pTargetWsAPI.OpenTable(tbMapping.T_TableName);
}
else
{
t_FcAPI = pTargetWsAPI.OpenFeatureClass(tbMapping.T_TableName);
}
if (tbMapping.S_TableType.ToUpper() == "TABLE")
{
s_TBAPI = pTargetWsAPI.OpenTable(tbMapping.S_TableName);
}
else
{
s_FcAPI = pSourceWsAPI.OpenFeatureClass(tbMapping.S_TableName);
}
List<DataDicTionary> dicData = new List<DataDicTionary>();
dicData.Add(new DataDicTionary() { DisplayName = "Null", NAME = "Null", CODE = "-1", REMARK = "" });
dicData.Add(new DataDicTionary() { DisplayName = "追加字段", NAME = "Add", CODE = "-2", REMARK = "" });
if (t_FcAPI != null)
{
for (int i = 0; i < t_FcAPI.FeatureClass.Fields.FieldCount; i++)
{
IField field = t_FcAPI.FeatureClass.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
dicData.Add(new DataDicTionary() { DisplayName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName, NAME = field.Name, CODE = i.ToString(), REMARK = field.Type.ToString() });
}
}
else if (t_TBAPI != null)
{
for (int i = 0; i < t_TBAPI.ITable.Fields.FieldCount; i++)
{
IField field = t_TBAPI.ITable.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
dicData.Add(new DataDicTionary() { DisplayName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName, NAME = field.Name, CODE = i.ToString(), REMARK = field.Type.ToString() });
}
}
if (s_FcAPI != null && s_FcAPI.FeatureClass != null)
{
List<FieldMapping> data = new List<FieldMapping>();
for (int i = 0; i < s_FcAPI.FeatureClass.Fields.FieldCount; i++)
{
IField field = s_FcAPI.FeatureClass.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
FieldMapping item = new FieldMapping();
item.S_FieldName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName;
item.S_FieldIndex = i;
DataDicTionary dic = dicData.FirstOrDefault(f => (f.NAME == field.Name || f.DisplayName == field.Name || f.NAME == field.AliasName || f.DisplayName == field.AliasName));//&& f.REMARK == field.Type.ToString()
if (dic != null)
{
item.T_FieldName = dic.DisplayName;
item.T_FieldIndex = Convert.ToInt16(dic.CODE);
}
else
{
item.T_FieldIndex = -1;
}
//item.PropertyType = enumPropertyType.ComboBox;
item.FieldList = dicData.FindAll(f => f.REMARK == field.Type.ToString() || f.REMARK.Contains("Double") || f.REMARK.Contains("Integer") || f.CODE == "-1" || f.CODE == "-2");
data.Add(item);
}
tbMapping.FieldMapping = data;
}
else if (s_TBAPI != null && s_TBAPI.ITable != null)
{
List<FieldMapping> data = new List<FieldMapping>();
for (int i = 0; i < s_TBAPI.ITable.Fields.FieldCount; i++)
{
IField field = s_TBAPI.ITable.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper() == "SHAPE")
continue;
FieldMapping item = new FieldMapping();
item.S_FieldName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName;
item.S_FieldIndex = i;
DataDicTionary dic = dicData.FirstOrDefault(f => (f.NAME == field.Name || f.DisplayName == field.Name || f.NAME == field.AliasName || f.DisplayName == field.AliasName));//&& f.REMARK == field.Type.ToString()
if (dic != null)
{
item.T_FieldName = dic.DisplayName;
item.T_FieldIndex = Convert.ToInt16(dic.CODE);
}
else
{
item.T_FieldIndex = -1;
}
//item.PropertyType = enumPropertyType.ComboBox;
item.FieldList = dicData.FindAll(f => f.REMARK == field.Type.ToString() || f.CODE == "-1" || f.CODE == "-2");
data.Add(item);
}
tbMapping.FieldMapping = data;
}
}
}
catch (Exception ex)
{
MessageHelper.ShowTips("操作异常!" + ex.Message);
LogAPI.Debug(ex);
}
}
private void DgTableMapping_SelectedItemChanged(object sender, DevExpress.Xpf.Grid.SelectedItemChangedEventArgs e)
{
if (e.NewItem is TableMapping)
{
if ((e.NewItem as TableMapping).T_TableName == null || (e.NewItem as TableMapping).T_TableName.ToUpper().Equals("NULL"))
{
dgFieldMapping.ItemsSource = null;
}
else
{
dgFieldMapping.ItemsSource = (e.NewItem as TableMapping).FieldMapping;
}
}
}
/// <summary>
/// 取消
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void chkSelectedAll_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
{
try
{
if (this.dgTableMapping == null || (dgTableMapping.ItemsSource as List<DDTCDataMapping>) == null)
{
return;
}
List<DDTCDataMapping> listTableMapping = (dgTableMapping.ItemsSource as List<DDTCDataMapping>);
bool check = (sender as DevExpress.Xpf.Editors.CheckEdit).IsChecked == null ? false : bool.Parse((sender as DevExpress.Xpf.Editors.CheckEdit).IsChecked.Value.ToString());
if (check)
{
listTableMapping.ForEach(x => x.State = TBState.Waiting);
}
else
{
listTableMapping.ForEach(x => x.State = TBState.Delete);
}
dgTableMapping.RefreshData();
}
catch (Exception ex)
{
MessageHelper.ShowTips("全选发生异常:" + ex.Message);
}
}
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
DDTCDataMapping tbm = dgTableMapping.SelectedItem as DDTCDataMapping;
if (tbm != null)
{
switch (tbm.State)
{
case TBState.Waiting:
tbm.State = TBState.Delete;
break;
case TBState.Delete:
tbm.State = TBState.Waiting;
break;
case TBState.BeingImport:
break;
case TBState.EndImport:
break;
default:
break;
}
dgTableMapping.RefreshData();
}
}
/// <summary>
/// 根据TableName获取表
/// </summary>
/// <returns></returns>
public static RuleTableEntity GetRuleTableEntityByTableName(string tableName)
{
RuleTableEntity ruleTableEntity = null;
try
{
XmlDocument doc = new XmlDocument();
string strPath = KGIS.Framework.Utils.SysAppPath.GetDataCheckTableMappingConfigPath();
doc.Load(strPath);
if (doc != null)
{
#region 获取规则检查TableMapping
XmlNodeList nodeTableMappingList = doc.SelectNodes("CheckTableMapping");
if (nodeTableMappingList != null && nodeTableMappingList.Count > 0)
{
foreach (XmlNode checkTableNode in nodeTableMappingList)
{
foreach (XmlNode tableNode in checkTableNode.ChildNodes)
{
if (tableNode.Attributes["TableName"] != null && tableNode.Attributes["TableName"].Value.Trim().Replace(" ", "") != tableName)
{
continue;
}
RuleTableEntity pRuleTableEntity = new RuleTableEntity();
pRuleTableEntity.Columns = new List<RuleColumnEntity>();
pRuleTableEntity.TableName = tableNode.Attributes["TableName"].Value;
if (tableNode.Attributes["Name"] != null)
{
pRuleTableEntity.TableAliasName = tableNode.Attributes["Name"].Value.Trim().Replace(" ", "");
}
if (tableNode.Attributes["Type"] != null)
{
pRuleTableEntity.Type = tableNode.Attributes["Type"].Value.Trim().Replace(" ", "");
}
if (tableNode.Attributes["YSDM"] != null)
{
pRuleTableEntity.YSDM = tableNode.Attributes["YSDM"].Value.Trim().Replace(" ", "");
}
if (tableNode.Attributes["CDM"] != null)
{
pRuleTableEntity.CDM = tableNode.Attributes["CDM"].Value;
}
if (tableNode.Attributes["IsNecessary"] != null)
{
bool b = false;
if (bool.TryParse(tableNode.Attributes["IsNecessary"].Value, out b))
{
}
pRuleTableEntity.IsNecessary = b;
}
foreach (XmlNode columnNode in tableNode.ChildNodes)
{
RuleColumnEntity pRuleColumnEntity = new RuleColumnEntity();
if (columnNode.Attributes["Name"] != null)
{
pRuleColumnEntity.ColumnName = columnNode.Attributes["Name"].Value.Trim().Replace(" ", "");
}
if (columnNode.Attributes["AliasName"] != null)
{
pRuleColumnEntity.AliasName = columnNode.Attributes["AliasName"].Value.Trim().Replace(" ", "");
}
if (columnNode.Attributes["Range"] != null)
{
pRuleColumnEntity.Range = columnNode.Attributes["Range"].Value.Trim().Replace(" ", "");
}
if (columnNode.Attributes["ToolTip"] != null)
{
pRuleColumnEntity.ToolTip = columnNode.Attributes["ToolTip"].Value.Trim().Replace(" ", "");
}
if (columnNode.Attributes["Pic"] != null)
{
pRuleColumnEntity.Pic = columnNode.Attributes["Pic"].Value.Trim().Replace(" ", "");
}
pRuleColumnEntity.AllowDBNull = false;
//字段是否可为空:如果未配置则默认为false:标识当前字段为必填项,不可为空
if (columnNode.Attributes["AllowDBNull"] != null)
{
bool b = false;
if (bool.TryParse(columnNode.Attributes["AllowDBNull"].Value, out b))
{
}
pRuleColumnEntity.AllowDBNull = b;
}
pRuleColumnEntity.IsUnique = false;
//字段值是否必须唯一:如果未配置则默认为false:表示当前字段不是必须唯一,可重复
if (columnNode.Attributes["IsUnique"] != null)
{
bool b = false;
if (bool.TryParse(columnNode.Attributes["IsUnique"].Value, out b))
{
}
pRuleColumnEntity.IsUnique = b;
}
if (columnNode.Attributes["DataType"] != null)
{
pRuleColumnEntity.DataType = columnNode.Attributes["DataType"].Value.Trim().Replace(" ", "").ToLower();
}
pRuleColumnEntity.IllegalityCheck = true;
//如果不是字符串类型的字段则不检查
//字段值非法字符检查:如果未配置则默认为false:表示需要检查非法字符
if (pRuleColumnEntity.DataType != "esriFieldTypeString")
{
pRuleColumnEntity.IllegalityCheck = false;
}
else
{
pRuleColumnEntity.IllegalityCheck = true;
}
if (columnNode.Attributes["IllegalityNotCheck"] != null)
{
bool b = false;
if (bool.TryParse(columnNode.Attributes["IllegalityNotCheck"].Value, out b))
{
}
pRuleColumnEntity.IllegalityCheck = b;
}
int max = 0;
if (columnNode.Attributes["MaxLength"] != null && int.TryParse(columnNode.Attributes["MaxLength"].Value, out max))
{
}
pRuleColumnEntity.MaxLength = max;
if (columnNode.Attributes["Precision"] != null)
{
int precision = 0;
if (int.TryParse(columnNode.Attributes["Precision"].Value, out precision))
{
}
pRuleColumnEntity.Precision = precision;
}
if (columnNode.Attributes["Dic"] != null)
{
pRuleColumnEntity.DIC = columnNode.Attributes["Dic"].Value.Trim().Replace(" ", "");
}
pRuleColumnEntity.IsEllipsoidArea = false;
if (columnNode.Attributes["IsEllipsoidArea"] != null)
{
bool b = false;
if (bool.TryParse(columnNode.Attributes["IsEllipsoidArea"].Value, out b))
{
}
pRuleColumnEntity.IsEllipsoidArea = b;
}
pRuleColumnEntity.ExtendField = false;
if (columnNode.Attributes["ExtendField"] != null)
{
bool b = false;
if (bool.TryParse(columnNode.Attributes["ExtendField"].Value, out b))
{
}
pRuleColumnEntity.ExtendField = b;
}
pRuleTableEntity.Columns.Add(pRuleColumnEntity);
}
ruleTableEntity = pRuleTableEntity;
}
}
}
#endregion
}
if (ruleTableEntity == null)
{
throw new Exception("未找到" + tableName + "表配置");
}
return ruleTableEntity;
}
catch (Exception ex)
{
LogAPI.Debug("根据TableName获取表 时异常,异常信息如下:");
LogAPI.Debug(ex);
LogAPI.Debug("根据TableName获取表 时异常信息结束");
throw new Exception("获取表结构异常:" + ex.Message);
}
}
/// <summary>
/// 表映射关系
/// </summary>
public class DDTCDataMapping : INotifyPropertyChanged
{
/// <summary>
/// 源数据表名
/// </summary>
public string S_TableName { get; set; }
/// <summary>
/// 源数据表名
/// </summary>
public string S_TableAliasName { get; set; }
/// <summary>
/// 数据源表类型
/// </summary>
public string S_TableType { get; set; }
/// <summary>
/// 坐标系
/// </summary>
public string S_Spatial { get; set; }
///// <summary>
///// 数据源要素类型
///// </summary>
//public string S_ShapeType { get; set; }
///// <summary>
///// 目标要素类型
///// </summary>
//public string T_ShapeType { get; set; }
private string _T_TableName;
/// <summary>
/// 目标数据表名
/// </summary>
public string T_TableName
{
get { return _T_TableName; }
set
{
_T_TableName = value;
if (PropertyChanged2 != null)
{
PropertyChanged2(this, new PropertyChangedEventArgs("T_TableName"));
}
}
}
/// <summary>
/// 目标数据表名
/// </summary>
public string T_TableAliasName { get; set; }
/// <summary>
/// 目标表类型
/// </summary>
public string T_TableType { get; set; }
/// <summary>
/// 条件sql语句
/// </summary>
private string _S_YSDM_SQL;
public string S_YSDM_SQL
{
get
{
return _S_YSDM_SQL;
}
set
{
_S_YSDM_SQL = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("S_YSDM_SQL"));
}
}
}
private List<FieldMapping> _FieldMapping;
/// <summary>
/// 字段映射信息
/// </summary>
public List<FieldMapping> FieldMapping
{
get { return _FieldMapping; }
set
{
_FieldMapping = value;
int count = _FieldMapping.FindAll(f => f.S_FieldIndex == -1).Count;
if (count == 0)
{
FieldMappingMsg = "所有字段已匹配";
}
else
{
FieldMappingMsg = string.Format("{0} 个字段未匹配", count);
}
}
}
/// <summary>
/// 目标数据表值域
/// </summary>
public List<DataDicTionary> T_TableList { get; set; }
private string _FieldMappingMsg;
public string FieldMappingMsg
{
get
{
return _FieldMappingMsg;
}
set
{
_FieldMappingMsg = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("FieldMappingMsg"));
}
}
}
#region
private TBState _State;
public TBState State
{
get { return _State; }
set
{
_State = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("State"));
}
}
}
private int _Count;
/// <summary>
/// 总进度
/// </summary>
public int Count
{
get
{
return _Count;
}
set
{
_Count = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Count"));
}
}
}
private int _Progress;
/// <summary>
/// 当前进度
/// </summary>
public int Progress
{
get
{
return _Progress;
}
set
{
_Progress = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Progress"));
}
}
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangedEventHandler PropertyChanged2;
}
}
}