using ESRI.ArcGIS.ADF; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; using KGIS.Framework.AE; using KGIS.Framework.OpenData.Control; using KGIS.Framework.OpenData.Filter; using KGIS.Framework.OpenData.InterFace; using KGIS.Framework.Platform; using KGIS.Framework.Utils; using KGIS.Framework.Utils.Helper; using Kingo.Plugin.General.ViewDTBJK; using Kingo.PluginServiceInterface.Model; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Windows; using KUI.Windows; using Kingo.PluginServiceInterface; using KGIS.Framework.Maps; namespace Kingo.Plugin.General.ViewYCLJK { /// /// FrmDataImport.xaml 的交互逻辑 /// public partial class FrmDataImport : BaseWindow { private TaskPackage taskPackage { get; set; } public Action ImpComplate; private bool _AllowEdit = true; public bool AllowEdit { get { return _AllowEdit; } set { _AllowEdit = value; //validationContainer.IsEnabled = value; } } private string _DataSourcePath; /// /// 数据源路径 /// public string DataSourcePath { get { return _DataSourcePath; } set { _DataSourcePath = value; //btnTargetData.EditValue = value; } } private IFeatureLayer _TargetLayer; /// /// 目标图层 /// public IFeatureLayer TargetLayer { get { return _TargetLayer; } set { _TargetLayer = value; if (_TargetLayer != null) txtTargetLayer.EditValue = _TargetLayer.Name; } } private IFeatureClass _SourceFeatureClass; /// /// 数据源 /// public IFeatureClass SourceFeatureClass { get { return _SourceFeatureClass; } set { _SourceFeatureClass = value; } } private ProjectInfo ProjectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo; string strWhere = string.Empty; public FrmDataImport(TaskPackage _taskPackage = null) { taskPackage = _taskPackage; InitializeComponent(); //白明雅 2018-11-26 添加工具说明 this.CustomToolTip = "导入的源数据需保证与目标图层类型一致且字段长度不大于目标字段长度"; } private void btnSelectedImportDataPath_Click(object sender, RoutedEventArgs e) { if (TargetLayer == null) { MessageHelper.ShowTips("目标图层不能为空!"); return; } OpenDataDialog pDialog = new OpenDataDialog(); ISpatialDataObjectFilter pOFilter; pOFilter = new FilterDatasetsAndLayers(); pDialog.AddFilter(pOFilter, true); //pOFilter = new FilterTextFiles(); //pDialog.AddFilter(pOFilter, false); //pOFilter = new FilterCadDrawingDatasets(); //pDialog.AddFilter(pOFilter, false); pDialog.Title = "选择导入的数据"; pDialog.AllowMultiSelect = false; pDialog.RestoreLocation = true; pDialog.StartLocation = pDialog.FinalLocation; System.Windows.Forms.DialogResult dialogResult = pDialog.ShowDialog(); if (dialogResult == System.Windows.Forms.DialogResult.OK && pDialog.Selection.Count != 0) { foreach (ISpatialDataObject distObj in pDialog.Selection) { if (distObj.DatasetType == esriDatasetType.esriDTFeatureClass) { btnImportDataPath.EditValue = pDialog.FinalLocation; SourceFeatureClass = (distObj.DatasetName as IName).Open() as IFeatureClass; //IRegionAuthorize region = new RegionAuthorize(); ////1.0.8需求,图幅接合表数据导入不受区域授权限制 //if ((_TargetLayer.FeatureClass as FeatureClass).Name != "TFJHB" && !region.ValidateAuthorize(SourceFeatureClass)) //{ // MessageHelper.ShowTips("选择数据不在授权范围内!"); // continue; //} SetFieldMapping(); } } } } /// /// 设置字段映射 /// public void SetFieldMapping() { try { //选择的不为空且数据类型一致 if (SourceFeatureClass != null && SourceFeatureClass.ShapeType == TargetLayer.FeatureClass.ShapeType) { List dicData = new List(); dicData.Add(new DataDicTionary() { DisplayName = "Null", NAME = "Null", CODE = "-1", REMARK = "" }); dicData.Add(new DataDicTionary() { DisplayName = "追加字段", NAME = "Add", CODE = "-2", REMARK = "" }); for (int i = 0; i < TargetLayer.FeatureClass.Fields.FieldCount; i++) { IField field = TargetLayer.FeatureClass.Fields.get_Field(i); if (!field.Editable || field.Name.ToUpper() == "SHAPE" || field.Name.ToUpper() == "BID") continue;//山西需求-自主图斑任务包数据导入不需要BID字段 dicData.Add(new DataDicTionary() { DisplayName = string.IsNullOrWhiteSpace(field.AliasName) ? field.Name : field.AliasName, NAME = field.Name, CODE = i.ToString(), REMARK = field.Type.ToString() }); } List data = new List(); for (int i = 0; i < SourceFeatureClass.Fields.FieldCount; i++) { IField field = SourceFeatureClass.Fields.get_Field(i); if (!field.Editable || field.Name.ToUpper() == "SHAPE" || field.Name.ToUpper() == "BID") 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());//&& 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); } dgFieldMapping.ItemsSource = null; dgFieldMapping.ItemsSource = data; } //提示不明确或缺少提示 王欢 2018-09-19 else { MessageHelper.ShowTips("选择数据不正确,请确认数据是否为空或格式是否正确!"); return; } } catch (Exception ex) { MessageHelper.ShowError("异常:" + ex.Message); LogAPI.Debug(ex); } } private void BtnOK_Click(object sender, RoutedEventArgs e) { int RowCount = 0; int ImportRowCount = 0; IWorkspaceEdit pWsEdit = null; try { if (string.IsNullOrEmpty(btnImportDataPath.Text)) { MessageHelper.ShowTips("请先选择导入数据文件的路径!"); return; } #region 判断坐标系一致性 IFeatureClass t_FC = TargetLayer.FeatureClass; //外部图层FeatureDataset为空,bug11428 if ((t_FC as FeatureClass).Workspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) { IEngineEditor edit = new EngineEditorClass(); if (edit.EditState == esriEngineEditState.esriEngineStateNotEditing) { MessageHelper.ShowTips("网络版数据库需要开启编辑后,再进行导入!"); return; } } if (t_FC is IGeoDataset && SourceFeatureClass is IGeoDataset) { IGeoDataset t_Ds = t_FC as IGeoDataset; IGeoDataset s_Ds = SourceFeatureClass as IGeoDataset; if (t_Ds.SpatialReference != null && s_Ds.SpatialReference != null) { if (!GeoDBAPI.SpatialReferenceCompare(t_Ds.SpatialReference, s_Ds.SpatialReference)) { if (MessageHelper.ShowYesNoAndTips("投影坐标系不一致,是否转换为相同投影坐标系后继续导入?") == System.Windows.Forms.DialogResult.Yes) { GeoDBAPI.SetGeoDatasetSpatialReference((SourceFeatureClass as FeatureClass).Workspace, t_Ds.SpatialReference, 0.0001); } else return; //MessageHelper.ShowTips("源要素坐标系与目标要素类坐标系不一致,无法进行数据导入!"); //return; } } } #endregion IDataset pDataset = t_FC as IDataset; IWorkspace pWs = pDataset.Workspace; pWsEdit = pWs as IWorkspaceEdit; pWsEdit.StartEditOperation(); if (cbReplace.IsChecked == true) { var FeatureCount = t_FC.FeatureCount(null); if (FeatureCount > 0) { if (MessageHelper.ShowYesNoAndTips(string.Format("是否确定要覆盖当前任务包{0}自主变更图斑数据?覆盖后数据不可恢复,请谨慎操作!", TargetLayer.Name)) == System.Windows.Forms.DialogResult.Yes) { IQueryFilter queryFilter = new QueryFilterClass() { WhereClause = $"BID='{this.taskPackage.BID.ToString()}'" }; //清除数据 ITable pTable = t_FC as ITable; pTable.DeleteSearchedRows(queryFilter); } else { return; } } } using (ComReleaser releaser = new ComReleaser()) { #region 新增字段 ////提示不明确或缺少提示 王欢 2018-09-19 if (!(dgFieldMapping.ItemsSource is List mFieldMapping)) { MessageHelper.ShowTips("无法获取字段映射信息,数据导入失败!"); return; } List addFields = mFieldMapping.FindAll(f => f.T_FieldIndex == -2); IFeatureClassAPI t_FcAPI = new FeatureClassAPI(t_FC); foreach (FieldMapping item in addFields) { IField f = SourceFeatureClass.Fields.get_Field(item.S_FieldIndex); if (t_FC.FindField(f.Name) > -1) { t_FcAPI.AddField(f.Name + "_a", f.Type, f.AliasName); item.T_FieldIndex = t_FC.Fields.FindField(f.Name + "_a"); } else { t_FcAPI.AddField(f.Name, f.Type, f.AliasName); item.T_FieldIndex = t_FC.Fields.FindField(f.Name); } } #endregion string str = btnSQLDataPath.Text; IQueryFilter filter = GeoDBAPI.CreateQueryFilter(str); IFeatureClassLoad pFclsLoad = t_FC as IFeatureClassLoad; if (pFclsLoad != null) pFclsLoad.LoadOnlyMode = true; IFeatureCursor cursor = t_FC.Insert(true); IFeatureBuffer newFeature = null; releaser.ManageLifetime(cursor); IFeatureCursor s_Cursor = SourceFeatureClass.Search(filter, false); releaser.ManageLifetime(s_Cursor); this.ShowLoading(string.Format("正在导入【{0}】数据……", TargetLayer.Name), 0, 0); System.Threading.Thread.Sleep(1000); int Count = SourceFeatureClass.FeatureCount(filter); RowCount = Count; int i = 0; IFeature feature = null; while ((feature = s_Cursor.NextFeature()) != null) { if (newFeature == null) { newFeature = t_FC.CreateFeatureBuffer(); } int indexBID = newFeature.Fields.FindField("BID"); if (indexBID > -1 && taskPackage != null) { newFeature.set_Value(indexBID, this.taskPackage.BID.ToString()); } indexBID = newFeature.Fields.FindField("TBBSM"); if (indexBID > -1) { newFeature.set_Value(indexBID, Guid.NewGuid().ToString().Replace("-", "")); } indexBID = newFeature.Fields.FindField("SJLY"); if (indexBID > -1) { newFeature.set_Value(indexBID, "ZZBG"); } indexBID = newFeature.Fields.FindField("JCBH"); if (indexBID > -1) { newFeature.set_Value(indexBID, $"{ProjectInfo.CODE}ZZTB" + Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8)); } indexBID = newFeature.Fields.FindField("XZQDM"); if (indexBID > -1) { newFeature.set_Value(indexBID, ProjectInfo.CODE); } IGeometry pGeo = feature.ShapeCopy; if (pGeo == null || pGeo.IsEmpty == true) { string FieldValue = feature.get_Value(feature.Fields.FindField("OBJECTID")).ToString(); LogAPI.Debug("OID:" + FieldValue + " 缺少图像数据(IGeometry)"); continue; } IZAware pZAware = pGeo as IZAware; pZAware.ZAware = false; newFeature.Shape = pGeo; foreach (FieldMapping item in mFieldMapping) { if (item.S_FieldName.Equals("BID", StringComparison.CurrentCultureIgnoreCase) || item.S_FieldName.Equals("TBBSM", StringComparison.CurrentCultureIgnoreCase) || item.S_FieldName.Equals("ZZBG", StringComparison.CurrentCultureIgnoreCase)) { continue; } if (item.S_FieldIndex < 0 || item.T_FieldIndex < 0) continue; if (string.IsNullOrWhiteSpace(feature.get_Value(item.S_FieldIndex).ToString())) { newFeature.set_Value(item.T_FieldIndex, DBNull.Value); } else { newFeature.set_Value(item.T_FieldIndex, feature.get_Value(item.S_FieldIndex)); } } cursor.InsertFeature(newFeature); i++; ImportRowCount = i; if (i % 200 == 0 || i == Count) this.UpdateMsg($"正在导入【{TargetLayer.Name}】数据({i}/{Count})……"); } if (cursor != null) cursor.Flush(); pWsEdit.StopEditOperation(); pFclsLoad.LoadOnlyMode = false; if ((t_FC as FeatureClass).Workspace.Type != esriWorkspaceType.esriRemoteDatabaseWorkspace) { IFeatureClassManage fcManage = t_FC as IFeatureClassManage; fcManage.UpdateExtent(); } } this.UpdateMsg("正在更新任务包......"); if (ImpComplate != null) { ImpComplate(true); } else { MessageHelper.ShowError("更新任务包事件'ImpComplate'异常!"); } if (SourceFeatureClass != null) { Marshal.ReleaseComObject(SourceFeatureClass); } int FailedRowCount = RowCount - ImportRowCount; this.CloseLoading(); string message = string.Format("共导入{0}条,成功{1}条,失败{2}条", RowCount, ImportRowCount, FailedRowCount); MessageHelper.ShowTips(message); this.Close(); } catch (Exception ex) { this.CloseLoading(); LogAPI.Debug("预处理-自主图斑-数据导入异常:" + ex); int FailedRowCount = RowCount - ImportRowCount; string message = string.Format("共导入{0}条,成功{1}条,失败{2}条, 失败原因:{3}", RowCount, ImportRowCount, FailedRowCount, ex.Message); MessageHelper.ShowWarning(message, true); LogAPI.Debug(message); } finally { this.CloseLoading(); if (pWsEdit != null) Marshal.ReleaseComObject(pWsEdit); } } private void BtnCancel_Click(object sender, RoutedEventArgs e) { this.Close(); } private void btnSelectedSQLDataPath_Click(object sender, RoutedEventArgs e) { try { IFeatureClass pFeatureClass = SourceFeatureClass; if (pFeatureClass == null) { MessageHelper.Show("请添加数据源图层!"); return; } else { UCSQLFilterCondition ucSQLFilterContion = new UCSQLFilterCondition(pFeatureClass); ucSQLFilterContion.SetValue += (wheresql) => { btnSQLDataPath.Text = wheresql; }; ucSQLFilterContion.ShowInMainWindow(); } } catch (Exception ex) { MessageHelper.ShowError("添加数据导入源图层异常!"); LogAPI.Debug("添加数据导入源图层异常" + ex); } } } public class FieldMapping { /// /// 目标字段名 /// public string T_FieldName { get; set; } /// /// 目标字段索引 /// public int T_FieldIndex { get; set; } /// /// 源字段名 /// public string S_FieldName { get; set; } /// /// 源字段索引 /// public int S_FieldIndex { get; set; } /// /// 字段集合 /// public List FieldList { get; set; } } }