年度变更建库软件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.

1291 lines
52 KiB

using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using KGIS.Framework.AE;
using KGIS.Framework.AE.Enum;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.OpenData.Control;
using KGIS.Framework.OpenData.Filter;
using KGIS.Framework.OpenData.InterFace;
using KGIS.Framework.Platform;
using KGIS.Framework.Platform.Helper;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Utils.Utility;
using Kingo.Framework.LayerStyleConvert.Common;
using Kingo.Framework.LayerStyleConvert.XSDClass;
using Kingo.OpenData.Filter;
using Kingo.Plugin.DataLoad.Model;
using Kingo.PluginServiceInterface;
using Kingo.PluginServiceInterface.Helper;
using Kingo.PluginServiceInterface.Helper.VCT;
using Kingo.PluginServiceInterface.Model;
using KUI.Windows;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using UIShell.OSGi;
using Path = System.IO.Path;
namespace Kingo.Plugin.DataLoad.View
{
/// <summary>
/// FrmBatchDataImport.xaml 的交互逻辑
/// </summary>
public partial class FrmLoadBaseData : BaseWindow
{
private IDataCatalogService _DataCatalog = null;
public bool shutDown = false;
private IHookHelper hookHelper = null;
/// <summary>
/// 导入数据类型(mdb文件为空,Shape文件为Shape)
/// </summary>
public string ImportDataType { get; set; }
private string SourceMDBPath { get; set; }
private ISystemCfg SystemCfg = null;
private SystemConfig2 Cfg = null;
private SystemConfig2 SystemCfg2 = null;
/// <summary>
/// dgTableMapping.ItemsSource视图匹配项
/// </summary>
List<LayerCfg> MapingData = new List<LayerCfg>();
private ProjectInfo ProInfo = null;
public FrmLoadBaseData(IHookHelper m_hookHelper)
{
InitializeComponent();
hookHelper = m_hookHelper;
try
{
ProInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
if (ProInfo == null) return;
if (_DataCatalog == null)
_DataCatalog = BundleRuntime.Instance.GetFirstOrDefaultService<IDataCatalogService>();
SystemCfg = BundleRuntime.Instance.GetFirstOrDefaultService<ISystemCfg>();
Cfg = SystemCfg.Load();
if (Cfg.JcLayerLoadCfg == null)
{
Cfg.JcLayerLoadCfg = new List<LayerCfg>();
}
BindBaseDataPath();
this.ResizeMode = ResizeMode = ResizeMode.CanResizeWithGrip;
object obj = _DataCatalog.CurrentLayers;
if (obj is LayerCfg)
{
LayerCfg ncsj = (obj as LayerCfg).Layers.FirstOrDefault(f => f.LayerName == "年初数据" && f.LayerType == EnumLayerType.GroupLayer);
if (ncsj != null && ncsj.Layers.Count > 0)
{
foreach (LayerCfg Layeritem in ncsj.Layers)
{
if (string.IsNullOrWhiteSpace(Layeritem.FcName) || string.IsNullOrWhiteSpace(Layeritem.FcPath)) continue;
LayerCfg layerCfg = Cfg.JcLayerLoadCfg.FirstOrDefault(x => x.FcName == Layeritem.FcName);
if (layerCfg != null)
{
layerCfg.FcPath = Layeritem.FcPath;
layerCfg.IsLoad = true;
}
}
//MapingData.ForEach(x => x.Required = true);
//dgTableMapping.ItemsSource = MapingData.OrderByDescending(x => x.Required).ToList();
//return;//根据配置读取目录
}
}
dgTableMapping.ItemsSource = Cfg.JcLayerLoadCfg.OrderByDescending(x => x.Required).ToList();
}
catch (Exception es)
{
LogAPI.Debug(es.Message);
}
}
#region 最新数据加载
private void BindBaseDataPath()
{
try
{
IWorkCatalog workCatalog = BundleRuntime.Instance.GetFirstOrDefaultService<IWorkCatalog>();
string code = (MapsManager.Instance.CurrProjectInfo as ProjectInfo).CODE;
string xzqmc = GetXZQMC(code);
string xzqDir = string.Format("{0}({1})", xzqmc, code);
if (workCatalog != null && !string.IsNullOrWhiteSpace(code))
{
string projectPath = Path.Combine(workCatalog.SaveWorkSapcePath, xzqDir, "年初数据");
if (Directory.Exists(projectPath))
{
List<string> dataPathList = new List<string>();
GetBaseDataPath(projectPath, dataPathList);
if (dataPathList.Count != 0)
{
this.cobDataBase.ItemsSource = dataPathList.FindAll(x => !x.ToUpper().Contains(".MDB"));
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug("获取基础数据文件失败:" + ex);
MessageHelper.Show("获取基础数据文件失败:" + ex);
}
}
//获取行政区名称
private string GetXZQMC(string xzqdm)
{
string xzqmc = string.Empty;
KGIS.Framework.DBOperator.IRDBHelper rdbHelper = null;
try
{
string systemPath = SysAppPath.GetDataBasePath() + "System.mdb";
if (File.Exists(systemPath))
{
string connStr = SysConfigsOprator.GetDBConnectionByName("MDBOledbConnection");
connStr = string.Format(connStr, systemPath);
rdbHelper = RDBFactory.CreateDbHelper(connStr, DatabaseType.MSAccess);
// string strSQL = "select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ Where XZQ LIKE '" + xzqdm + "%'";
string strSQL = string.Format("select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ Where XZQ = '{0}'", xzqdm);
DataTable dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
if (dt != null)
{
List<DataDicTionary> xzqCoderesult = TBToList.ToList<DataDicTionary>(dt);
foreach (var item in xzqCoderesult)
{
if (dt.Rows.Count == 1)
xzqmc = item.NAME;
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex);
}
finally
{
if (rdbHelper != null)
rdbHelper.DisConnect();
}
return xzqmc;
}
private void GetBaseDataPath(string dirPath, List<string> pathList)
{
try
{
string[] dirArr = Directory.GetDirectories(dirPath);
string[] fileArr = Directory.GetFiles(dirPath);
// 遍历所有文件
if (fileArr.Length > 0)
{
string fileName;
foreach (string file in fileArr)
{
fileName = Path.GetFileName(file);
if ((fileName.ToLower().Contains(".vct") || fileName.ToLower().Contains(".mdb")) && !pathList.Contains(file))
{
pathList.Add(file);
}
}
}
// 遍历所有文件夹
if (dirArr.Length > 0)
{
string folderName;
foreach (string dir in dirArr)
{
folderName = Path.GetFileName(dir);
if (folderName.ToLower().Contains(".gdb") && !pathList.Contains(dir))
{
pathList.Add(dir);
}
GetBaseDataPath(dir, pathList);
}
}
}
catch (Exception ex)
{
LogAPI.Debug("获取基础数据文件失败:" + ex);
}
}
/// <summary>
/// 数据路径切换
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CobDataBase_SelectedIndexChanged(object sender, RoutedEventArgs e)
{
if (cobDataBase.ItemsSource != null)
{
try
{
string selectedPath = this.cobDataBase.SelectedItem.ToString();
using (ComReleaser com = new ComReleaser())
{
ImportDataType = Path.GetExtension(selectedPath).ToUpper().Replace('.', ' ').TrimStart();
this.ShowLoading("正在打开数据文件...", 0, 0);
System.Threading.Thread.Sleep(900);
string fileName = string.Empty;
if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("VCT"))
{
string TempMDBFolderPath = Path.GetTempPath();
string TempMDBPath = Path.Combine(TempMDBFolderPath, string.Format("{0}.mdb", Path.GetFileNameWithoutExtension(selectedPath)));
if (File.Exists(TempMDBPath))
{
File.Delete(TempMDBPath);
}
this.ShowLoading("正在解析VCT文件... ...", 0, 0);
VCTToMDBHelper3 vcttomdb = new VCTToMDBHelper3
{
RootPath = TempMDBFolderPath
};
vcttomdb.VCTToMDB(selectedPath);
this.CloseLoading();
if (!File.Exists(TempMDBPath))
{
MessageHelper.ShowError("VCT文件解析失败");
return;
}
SourceMDBPath = TempMDBPath;
}
SetTableMapping();
this.CloseLoading();
}
}
catch (Exception ex)
{
LogAPI.Debug("选择基础数据库失败:" + ex);
this.CloseLoading();
MessageHelper.Show("选择基础数据库失败:" + ex);
}
}
}
private void SetTableMapping()
{
IWorkspaceAPI t_WsAPI = null;
IWorkspaceAPI s_WsAPI = null;
IFeatureClassAPI s_FCAPI = null;
try
{
string s_MdbPath = null;
if (ImportDataType == "VCT")
{
s_MdbPath = SourceMDBPath;
}
else
{
if (this.cobDataBase.SelectedItem != null)
s_MdbPath = this.cobDataBase.SelectedItem.ToString();
}
if ((ImportDataType == "MDB" || ImportDataType == "VCT") && !File.Exists(s_MdbPath))
{
if (!Path.GetFileName(s_MdbPath).Equals(".mdb"))
{
MessageHelper.ShowTips("请确保文件存在,并且为mdb文件!");
return;
}
}
else if (ImportDataType == "GDB" && !Directory.Exists(s_MdbPath))
{
MessageHelper.ShowTips("请确保GDB文件夹存在!");
return;
}
if (ImportDataType == "MDB" || ImportDataType == "VCT")
{
s_WsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.MDBFile);
}
else
{
s_WsAPI = new WorkspaceAPI(s_MdbPath, WorkspaceTypeEnum.GDBFile,true);
}
//源数据获取图层
if (s_WsAPI == null) return;//源数据不能为空
//系统配置图层
List<KeyAndValue> t_TbList = new List<KeyAndValue>();
if (SystemCfg != null)
Cfg = SystemCfg.Load();//根据配置文件是否为必选项
foreach (LayerCfg Tempitem in Cfg.JcLayerLoadCfg)
{
t_TbList.Add(new KeyAndValue() { S_Key = Tempitem.FcName, S_Value = Tempitem.LayerName, IsCheck = Tempitem.Required });
}
List<KeyAndValue> s_TbList = s_WsAPI.GetFeatureClassName(ESRI.ArcGIS.Geodatabase.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(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTFeatureClass);
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 IsMatching = false;
foreach (KeyAndValue item in s_TbList)
{
LayerCfg cfg = Cfg.JcLayerLoadCfg.FirstOrDefault(x => x.FcName == item.S_Key || x.FcName == item.S_Value);
if (cfg != null)
{
cfg.FcPath = s_MdbPath;
IsMatching = true;
}
}
if (!IsMatching)
{
MessageHelper.ShowTips("无匹配项,请重新选择数据!");
return;
}
List<LayerCfg> Mappings = (dgTableMapping.ItemsSource as List<LayerCfg>).FindAll(x => x.FcName != "").ToList();
foreach (LayerCfg UpdateLayerPath in Mappings)
{
LayerCfg layerCfg = Cfg.JcLayerLoadCfg.FirstOrDefault(x => x.FcName == UpdateLayerPath.FcName);
if (layerCfg == null || string.IsNullOrWhiteSpace(layerCfg.FcPath)) continue;
UpdateLayerPath.FcPath = layerCfg.FcPath;
UpdateLayerPath.IsLoad = layerCfg.Required;
}
dgTableMapping.ItemsSource = null;//主要是刷新视图显示效果
//Cfg.JcLayerLoadCfg.ForEach(x => x.IsLoad = x.Required);
dgTableMapping.ItemsSource = (Mappings as List<LayerCfg>).OrderByDescending(x => x.Required).ToList();
dgTableMapping.RefreshData();
}
catch (Exception ex)
{
LogAPI.Debug(ex);
MessageHelper.ShowTips(ex.Message);
}
finally
{
if (s_WsAPI != null)
{
s_WsAPI.CloseWorkspace();
s_WsAPI = null;
}
if (t_WsAPI != null)
{
t_WsAPI.CloseWorkspace();
t_WsAPI= null;
}
if (s_FCAPI != null)
{
s_FCAPI.CloseFeatureClass();
s_FCAPI = null;
}
}
}
#region 判断是否是一样的坐标参考系及容差
/// <summary>
/// 检查当前图层容差是否一致
/// </summary>
/// <param name="classAPI"></param>
private void CheckXYTolerance(IFeatureClassAPI classAPI)
{
if (classAPI != null && classAPI.FeatureClass != null)
{
IFeatureLayer featureLayer = new FeatureLayer() { FeatureClass = classAPI.FeatureClass };
double XYTolerance = AECommonHelper.GetLayerTolerance(featureLayer.FeatureClass);
if (!XYTolerance.Equals(ProInfo.XYResolution))
{
if (MessageHelper.ShowYesNoAndTips("源图层容差与当前工程容差不一致,是否转换将源数据转换为相同容差数据?") != System.Windows.Forms.DialogResult.Yes)
{
string s_Path = this.cobDataBase.SelectedItem.ToString();
PluginServiceInterface.CommonHelper.DirectoryCopy(SysAppPath.GetCurrentAppPath() + string.Format("工作空间\\模板\\新建变更工程\\{0}\\BGDB.gdb", 100000), s_Path);
}
}
}
}
/// <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(TableMapping 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 != null && pTbMaping.S_TableType.ToUpper() != "TABLE")
{
s_FcAPI = pSourceWsAPI.OpenFeatureClass(pTbMaping.S_TableName);
}
IMap map = MapsManager.Instance.MapService.getAxMapControl().Map;
if (s_FcAPI != null && (s_FcAPI.FeatureClass as IGeoDataset) != null && map != null)
{
bool isEqual = GeoDBAPI.SpatialReferenceCompare(map.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();
}
}
#endregion
/// <summary>
/// 全选和反选事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ChkSelectedAll_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
{
try
{
if ((dgTableMapping.ItemsSource as List<LayerCfg>) == null) return;
List<LayerCfg> listTableMapping = (dgTableMapping.ItemsSource as List<LayerCfg>);
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.IsLoad = true);
}
else
{
listTableMapping.ForEach(x => x.IsLoad = false);
}
dgTableMapping.ItemsSource = null;
dgTableMapping.ItemsSource = listTableMapping;
dgTableMapping.RefreshData();
}
catch (Exception ex)
{
MessageHelper.ShowTips("全选发生异常:" + ex.Message);
}
}
/// <summary>
/// 加载 -
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnLoad_Click(object sender, RoutedEventArgs e)
{
this.btnLoad.IsEnabled = false;
IWorkspaceAPI pSourceWsAPI = null;
IWorkspaceAPI pTargetWsAPI = null;
string projectPath = string.Empty;
string s_MdbPath = null;
try
{
if (ImportDataType == "VCT")
{
s_MdbPath = SourceMDBPath;
}
if (dgTableMapping.ItemsSource != null)//新匹配规则
{
this.ShowLoading("正在进行数据加载......", 0, 0);
ILayer layer = MapsManager.Instance.MapService.GetGroupLayer("JCSJ");//获取年初数据图层组
LayerCfg GroupLayerInfo = null;
if (_DataCatalog != null)
{
_DataCatalog.GetNodeByLayer(layer);
LayerCfg rootLayer = _DataCatalog.CurrentLayers as LayerCfg;
List<LayerCfg> AllLayers = rootLayer.GetAllItem();
GroupLayerInfo = AllLayers.FirstOrDefault(f => f.LayerName == layer.Name);
GroupLayerInfo.Layers.Clear();
}
ISystemCfg cfg2 = BundleRuntime.Instance.GetFirstOrDefaultService<ISystemCfg>();
SystemCfg2 = cfg2.Load();
if (SystemCfg2.JcLayerLoadCfg == null)
{
SystemCfg2.JcLayerLoadCfg = new List<LayerCfg>();
}
List<LayerCfg> TempMapingData = (dgTableMapping.ItemsSource as List<LayerCfg>);
if (layer != null) (layer as IGroupLayer).Clear();
string message = string.Empty;
string errorMessage = string.Empty;
int SuccessImportLayerCount = 0;
int DeletedImportLayerCount = 0;
int FailImportLayerCount = 0;
TempMapingData.Reverse();
foreach (LayerCfg itemLayer in TempMapingData)
{
if (GroupLayerInfo.Layers.FirstOrDefault(x => x.LayerName == itemLayer.LayerName) != null && itemLayer.IsLoad == true)
GroupLayerInfo.Layers.RemoveAll(f => f.LayerName == itemLayer.LayerName);//仅替换将要加载的图层
if (itemLayer.IsLoad == false || string.IsNullOrWhiteSpace(itemLayer.FcPath)) continue;//不勾选的/空数据,不导入数据
IWorkspaceAPI workspaceAPI = GetImportDataWorkspace(itemLayer.FcPath);
if (AddLayerToMap(GroupLayerInfo, itemLayer, workspaceAPI, ref message, ref errorMessage, ref FailImportLayerCount))
{
itemLayer.LoadLayerState = PluginServiceInterface.TBState.EndImport;
SuccessImportLayerCount++;
}
else
{
DeletedImportLayerCount++;
}
if (workspaceAPI != null)
{
workspaceAPI.CloseWorkspace();
workspaceAPI = null;
}
}
TempMapingData.Reverse();
dgTableMapping.ItemsSource = null;
dgTableMapping.ItemsSource = TempMapingData;
if (_DataCatalog != null)
{
_DataCatalog.UpdateTree();
}
try
{
SaveProject();
}
catch (Exception ex)
{
LogAPI.Debug("添加图层到地图时发生异常:" + ex);
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
errorMessage = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
DeletedImportLayerCount, FailImportLayerCount) + errorMessage;
this.CloseLoading();
MessageHelper.Show(errorMessage, true);
}
else
{
int TotalImportLayerCount = SuccessImportLayerCount + DeletedImportLayerCount + FailImportLayerCount;
message = string.Format("共导入{0}个图层,成功{1}个,删除{2}个,失败{3}个。", TotalImportLayerCount, SuccessImportLayerCount,
DeletedImportLayerCount, FailImportLayerCount) + message;
this.CloseLoading();
MessageHelper.Show(message, true);
}
if (DeletedImportLayerCount == 0 && FailImportLayerCount == 0) this.Close();
}
}
catch (Exception ex)
{
this.CloseLoading();
LogAPI.Debug("导入 " + ImportDataType + " 数据时失败,异常原因: " + ex + " ; ");
}
finally
{
this.btnLoad.IsEnabled = true;
if (pSourceWsAPI != null)
{
pSourceWsAPI.CloseWorkspace();
}
if (pTargetWsAPI != null)
{
pTargetWsAPI.CloseWorkspace();
}
this.CloseLoading();
}
}
private bool AddLayerToMap(LayerCfg ncsjGroupLayer, LayerCfg pTbMaping, IWorkspaceAPI pSourceWsAPI, ref string message, ref string errorMessage, ref int FailImportLayerCount)
{
if ((pSourceWsAPI == null || pSourceWsAPI.CurrentWorkspace == null || ncsjGroupLayer == null))
return false;
IFeatureClassAPI s_FcAPI = null;
try
{
if (!string.IsNullOrWhiteSpace(pTbMaping.FcName) && pSourceWsAPI.ExistFeatureClass(pTbMaping.FcName))
s_FcAPI = pSourceWsAPI.OpenFeatureClass(pTbMaping.FcName);
if (s_FcAPI != null && s_FcAPI.FeatureClass != null)
{
IFeatureLayer pTargetLayer = new FeatureLayer
{
FeatureClass = s_FcAPI.FeatureClass,
Name = pTbMaping.LayerName
};
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;
}
if (_DataCatalog != null)
{
SetILayerSymbol(pTargetLayer, pTargetLayer.FeatureClass.AliasName);
_DataCatalog.AddLayer(pTargetLayer, ncsjGroupLayer);
//if (workspaceAPI != null && Path.GetExtension(workspaceAPI.CurrentWorkspace.PathName).ToUpper().Replace('.', ' ').TrimStart() == "MDB")
//{ //解决基础数据加载MDB文件锁死
// Marshal.ReleaseComObject(workspaceAPI.CurrentWorkspace);
//}
return true;//执行成功
}
}
return false;
}
catch (Exception ex)
{
FailImportLayerCount++;
errorMessage += (pTbMaping.LayerName + "图层数据导入异常!" + ex.Message);
return false;
}
finally
{
if (s_FcAPI != null)
s_FcAPI.CloseFeatureClass();
}
}
private void SetILayerSymbol(IFeatureLayer tempLayer, string LayerAliseName)
{
IFeatureRenderer result = null;
LayerCfg layerCfg = SystemCfg2.JcLayerLoadCfg.FirstOrDefault(x => x.FcName == LayerAliseName);//默认配置默认不为NULL
if (layerCfg != null && !string.IsNullOrWhiteSpace(layerCfg.Symbol))
{
AdvancedDrawingInfo ad = AdvancedDrawingInfo.FromJson(layerCfg.Symbol);
if (ad != null)
{
if (ad.DrawingInfo.Renderer is Framework.LayerStyleConvert.XSDClass.SimpleRenderer)
{
Symbol symbol1 = (ad.DrawingInfo.Renderer as Framework.LayerStyleConvert.XSDClass.SimpleRenderer).Symbol;
ISimpleRenderer simpleRander2 = SymbolConvert.Instance().GetSimpleRenderer(symbol1, SymbolTypeEnum.Fill);
result = simpleRander2 as IFeatureRenderer;
}
else if (ad.DrawingInfo.Renderer is Framework.LayerStyleConvert.XSDClass.UniqueValueRenderer)
{
Renderer rander = ad.DrawingInfo.Renderer;
IUniqueValueRenderer uniqueValueRander = SymbolConvert.Instance().GetUniqueValueRenderer(rander, SymbolTypeEnum.Fill);
result = uniqueValueRander as IFeatureRenderer;
}
}
#region 样式
if (result != null)
(tempLayer as IGeoFeatureLayer).Renderer = result;
#endregion
#region 显示比例设置
tempLayer.MinimumScale = layerCfg.MinScale;
tempLayer.MaximumScale = layerCfg.MaxScale;
#endregion
#region 图层透明度
if (tempLayer is ILayerEffects mLayerEffects)//透明度
mLayerEffects.Transparency = (short)layerCfg.Transparency;
#endregion
#region 是否显示
tempLayer.Visible = layerCfg.Visible;//是否显示
#endregion
#region 是否可选择
tempLayer.Selectable = layerCfg.Selectable;
#endregion
#region 过滤条件
IFeatureLayerDefinition pFLDefinition = tempLayer as IFeatureLayerDefinition;
if (pFLDefinition != null)
{
pFLDefinition.DefinitionExpression = layerCfg.DefinitionExpression;
}
#endregion
}
}
/// <summary>
/// 选择的文件保存在工程内部(年初数据)
/// </summary>
/// <param name="SavePath"></param>
/// <returns>工程内部文件路径</returns>
private string SaveFileToPrjDic(string SavePath)
{
if (SavePath == null || string.IsNullOrWhiteSpace(SavePath)) return "";
string fileName = string.Empty;
IWorkCatalog workCatalog = BundleRuntime.Instance.GetFirstOrDefaultService<IWorkCatalog>();
string code = (MapsManager.Instance.CurrProjectInfo as ProjectInfo).CODE;
string xzqmc = GetXZQMC(code);
string xzqDir = string.Format("{0}({1})", xzqmc, code);
string projectPath = string.Empty;
if (workCatalog != null && !string.IsNullOrWhiteSpace(code))
{
projectPath = Path.Combine(workCatalog.SaveWorkSapcePath, xzqDir, "年初数据");
if (!Directory.Exists(projectPath))
{
Directory.CreateDirectory(projectPath);
}
fileName = Path.GetFileName(SavePath);
if (!string.IsNullOrWhiteSpace(fileName))
{
if (Path.GetExtension(SavePath).ToUpper().Replace('.', ' ').TrimStart() == "GDB")
{
DirectoryCopy(SavePath, projectPath);
}
else
{
DelFileMDB(Path.Combine(projectPath, fileName), "");//是否保持替换
if (!(File.Exists(SavePath) && SavePath.Contains(projectPath)))
File.Copy(SavePath, projectPath + "\\" + fileName, true);
}
}
}
return Path.Combine(projectPath, fileName);
}
Dictionary<string, IWorkspaceAPI> keyValueWorkAPI = new Dictionary<string, IWorkspaceAPI>();
private IWorkspaceAPI GetImportDataWorkspace(string strS_DataPath)
{
strS_DataPath = SaveFileToPrjDic(strS_DataPath);
if (strS_DataPath != null && keyValueWorkAPI.ContainsKey(strS_DataPath))
return keyValueWorkAPI[strS_DataPath];//在当前工程下打开WorkSpaceAPI
if (!File.Exists(strS_DataPath) && !Directory.Exists(strS_DataPath))
return null;
IWorkspaceAPI workspaceAPI = null;
string DataType = Path.GetExtension(strS_DataPath).ToUpper().Replace('.', ' ').TrimStart();
if (DataType == "MDB" || DataType == "VCT")
{
workspaceAPI = new WorkspaceAPI(strS_DataPath, WorkspaceTypeEnum.MDBFile);
}
else
{
workspaceAPI = new WorkspaceAPI(strS_DataPath, WorkspaceTypeEnum.GDBFile,true);
}
AECommonHelper.SetGeoDatasetSpatialReference(workspaceAPI.CurrentWorkspace, GeoDBAPI.CreteSpatialReference(ProInfo.PrjFileStr), ProInfo.XYResolution);
if (workspaceAPI != null && !keyValueWorkAPI.ContainsKey(strS_DataPath))
keyValueWorkAPI.Add(strS_DataPath, workspaceAPI);
return workspaceAPI;
}
private void DelFileMDB(string MDBPath, string GDBPath)
{
try
{
if (File.Exists(MDBPath))
{
File.Delete(MDBPath);
}
}
catch (Exception)
{
LogAPI.Debug("当前MDB文件删除失败不处理!");
}
}
private void SaveProject()
{
try
{
Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "InitProject" });
}
catch (Exception ex)
{
LogAPI.Debug("添加图层到地图时发生异常,异常信息如下:");
LogAPI.Debug(ex);
}
}
/// <summary>
/// 选择-
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnSelectedBaseData_Click(object sender, RoutedEventArgs e)
{
try
{
using (ComReleaser com = new ComReleaser())
{
List<string> baseDataPathList = new List<string>();
OpenDataDialog pDialog = new OpenDataDialog();
ISpatialDataObjectFilter pOFilter = new FilterGeoDatabasePersonal();
pDialog.AddFilter(pOFilter, true);
pOFilter = new FilterVCTFile();///VCT文件模式
pDialog.AddFilter(pOFilter, true);
pOFilter = new FilterGeoDatabaseFile();
pDialog.AddFilter(pOFilter, true);
pDialog.AllowMultiSelect = false;
pDialog.Title = "选择基础数据";
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)
{
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";
}
this.cobDataBase.ItemsSource = null;
baseDataPathList.Add(pDialog.FinalLocation);
this.cobDataBase.ItemsSource = baseDataPathList;
string fileName = string.Empty;
if (!string.IsNullOrWhiteSpace(ImportDataType) && ImportDataType.Equals("VCT"))
{
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
{
RootPath = TempMDBFolderPath
};
vcttomdb.VCTToMDB(pDialog.FinalLocation);
ProgressHelper.CloseProcessBar();
if (!File.Exists(TempMDBPath))
{
MessageHelper.ShowError("VCT文件解析失败");
return;
}
SourceMDBPath = TempMDBPath;
}
this.cobDataBase.SelectedIndex = 0;
SetTableMapping();
}
}
}
catch (Exception ex)
{
LogAPI.Debug("选择基础数据库失败:" + ex);
MessageHelper.Show("选择基础数据库失败:" + ex);
}
}
public string DirectoryCopy(string sourceDir, string targetDirPath)
{
try
{
if (!Directory.Exists(sourceDir)) return "";
string targetDir = Path.Combine(targetDirPath, Path.GetFileName(sourceDir));
//string targetDir = Path.Combine(targetDirPath, guid.ToString() + "." + Path.GetFileName(sourceDir).Split('.')[1]);
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
else
{
return "";
}
// 文件及文件夹名称数组
string[] dirColl = Directory.GetDirectories(sourceDir);
string[] fileColl = Directory.GetFiles(sourceDir);
// 遍历复制所有文件
if (fileColl.Length > 0)
{
string fileName;
foreach (string fileDir in fileColl)
{
fileName = Path.GetFileName(fileDir);
File.Copy(sourceDir + "\\" + fileName, targetDir + "\\" + fileName, true);
}
}
// 遍历复制所有文件夹
if (dirColl.Length > 0)
{
string folderName;
foreach (string dir in dirColl)
{
folderName = Path.GetFileName(dir);
// 递归调用
Directory.CreateDirectory(targetDir + "\\" + folderName);
DirectoryCopy(dir, targetDir + "\\" + folderName);
}
}
return "";
}
catch (Exception ex)
{
LogAPI.Debug("创建工程目录页面中,文件夹复制时失败,异常原因: " + ex.Message + " ; ");
return "";
throw;
}
}
/// <summary>
/// 图层加载状态栏-事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
if (dgTableMapping.SelectedItem is LayerCfg tbm)
{
switch (tbm.LoadLayerState)
{
case PluginServiceInterface.TBState.Waiting:
tbm.LoadLayerState = PluginServiceInterface.TBState.Waiting;
break;
case PluginServiceInterface.TBState.Delete:
tbm.LoadLayerState = PluginServiceInterface.TBState.Delete;
break;
case PluginServiceInterface.TBState.BeingImport:
tbm.LoadLayerState = PluginServiceInterface.TBState.BeingImport;
break;
case PluginServiceInterface.TBState.EndImport:
tbm.LoadLayerState = PluginServiceInterface.TBState.EndImport;
break;
default:
break;
}
dgTableMapping.RefreshData();
}
}
/// <summary>
/// 取消
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void BaseWindow_Closing(object sender, CancelEventArgs e)
{
this.shutDown = true;
}
#endregion
/// <summary>
/// 列-操作-选择
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Txt_Delete_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
OpenDataDialog pDialog = new OpenDataDialog();
ISpatialDataObjectFilter pOFilter = new FilterGeoDatabasePersonal();
pDialog.AddFilter(pOFilter, true);
pOFilter = new FilterVCTFile();
pDialog.AddFilter(pOFilter, true);
pOFilter = new FilterGeoDatabaseFile();
pDialog.AddFilter(pOFilter, true);
pDialog.AllowMultiSelect = false;
pDialog.Title = "选择基础数据";
pDialog.RestoreLocation = true;
pDialog.StartLocation = pDialog.FinalLocation;
System.Windows.Forms.DialogResult dialogResult = pDialog.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK && pDialog.Selection.Count == 1)
{
string txtBoxTag = (sender as TextBlock).Tag.ToString();
MapingData.Clear();
MapingData = dgTableMapping.ItemsSource as List<LayerCfg>;
if (MapingData != null && MapingData.Count != 0)
{
LayerCfg layerCfg = MapingData.FirstOrDefault(x => x.FcName == txtBoxTag);
if (layerCfg == null) return;
layerCfg.FcPath = pDialog.Selection[0].FullName;
dgTableMapping.ItemsSource = MapingData.OrderByDescending(x => x.Required).ToList();
dgTableMapping.RefreshData();
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex.Message);
MessageHelper.ShowError(ex.Message);
}
}
}
public class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
if (value is TableMapping)
{
return (value as TableMapping).FieldMapping;
}
return null;
}
catch (Exception)
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
public class StateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
if (value is TBState)
{
return (TBState)value == TBState.Waiting;
}
return value;
}
catch (Exception)
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
/// <summary>
/// 表映射关系
/// </summary>
public class TableMapping : 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>
/// 目标排序
/// </summary>
public int OrderIndex { 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;
}
public enum TBState
{
/// <summary>
/// 等待中
/// </summary>
Waiting = 0,
/// <summary>
/// 删除
/// </summary>
Delete = 1,
/// <summary>
/// 开始导入
/// </summary>
BeingImport = 2,
/// <summary>
/// 结束导入
/// </summary>
EndImport = 3
}
}