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

1315 lines
64 KiB

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.AE.Enum;
using KGIS.Framework.AE.GaussCalculate;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using Kingo.PluginServiceInterface.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Kingo.Plugin.General.Helper
{
public class DBLoadHelper
{
/// <summary>
/// 返回db图斑信息:分为自主变更和外业任务图斑
/// </summary>
private Dictionary<DataRow, int> DicTBInfo { get; set; }
private string bh { get; set; }
/// <summary>
/// 加载db,矢量化图形
/// </summary>
/// <param name="dbPath">任务包路径</param>
/// <param name="reload">重新加载原始任务包</param>
public Dictionary<DataRow, int> DBTaskLoad(TaskPackage taskPackage, bool reload = false)
{
IWorkspaceAPI workspaceAPI = null;
IWorkspaceAPI workspaceSchemeAPI = null;
IRDBHelper rdbHelper = null;
string tempPath = string.Empty;
try
{
DicTBInfo = new Dictionary<DataRow, int>();
string openPath = taskPackage.PackagePath;
//已完成的任务包从成果输出文件夹中打开
//if (taskPackage.State.Equals("已输出") && !string.IsNullOrWhiteSpace(taskPackage.OutputPath) && System.IO.File.Exists(taskPackage.OutputPath))
//{
// openPath = taskPackage.OutputPath;
//}
if (string.IsNullOrWhiteSpace(openPath) || !File.Exists(openPath))
{
return DicTBInfo;
}
ProjectInfo projectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
if (projectInfo == null)
{
throw new Exception("未检测到当前打开的工程,请先打开工程!");
}
if (string.IsNullOrWhiteSpace(projectInfo.JCKPath) && Platform.Instance.SystemType == SystemTypeEnum.YCLJK)
{
throw new Exception("请先使用“基础数据加载”功能设置基础库数据!");
}
if (string.IsNullOrWhiteSpace(projectInfo.UserName) && Platform.Instance.SystemType == SystemTypeEnum.YCLJK)
{
throw new Exception("请先使用“用户设置”功能设置用户名!");
}
rdbHelper = RDBFactory.CreateDbHelper($"{openPath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
if (!rdbHelper.TableIsExist("WYRW"))
{
throw new Exception("选择的任务包不存在WYRW(外业任务)表,请确认是否是《预处理任务包》!");
}
DataTable dt = rdbHelper.ExecuteDatatable("ysj", "select * from ysj", true);
if (dt == null || dt.Rows.Count <= 0)
{
throw new Exception("选择的任务包元数据(YSJ)表为空,请检查是否是《预处理任务包》!");
}
long count = (long)rdbHelper.ExecuteScalar("select count(1) from wyrw", CommandType.Text);
if (count <= 0 && !dt.Rows[0]["BLX"].Equals("YSRW_New"))
{
MessageHelper.ShowError("选择的任务包外业任务数据(WYRW)表为空,请检查是否是《预处理任务包》!");
}
//如果wkid为空,则在打开的时候将工程的坐标参考wkid回写到db包中
int wkid = 0;
if (!(dt.Rows[0]["WKID"] is DBNull))
{
wkid = int.Parse(dt.Rows[0]["WKID"].ToString());
}
if (wkid <= 0)
{
wkid = projectInfo.GetCurentProjectedCoordinate().FactoryCode;
if (wkid <= 0)
{
CoordinateReferenceMapping coordinateReferenceMapping = CoordinateHelper.ListCoordinateReference.FirstOrDefault(x => (projectInfo.ZYJD > x.MinX && projectInfo.ZYJD < x.MaxX) || x.Central_Meridian.Equals(projectInfo.ZYJD));
if (coordinateReferenceMapping != null)
{
wkid = coordinateReferenceMapping.WKID;
}
}
rdbHelper.ExecuteNonQuery($"update ysj set wkid={wkid}", CommandType.Text);
}
//任务包包号
bh = taskPackage.BID;
string fileName = System.IO.Path.GetFileName(openPath);
tempPath = System.IO.Path.Combine(projectInfo.TaskPath, "临时", fileName);
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
if (openPath.EndsWith(".encrypt.ysrw", StringComparison.CurrentCultureIgnoreCase))
{
taskPackage.DecryptPackagePath = System.IO.Path.Combine(tempPath, fileName.Substring(0, fileName.Length - 13) + ".ysrw_back");
if (!File.Exists(taskPackage.DecryptPackagePath) || reload)
{
File.Copy(openPath, taskPackage.DecryptPackagePath, true);
DecryptDB(taskPackage.DecryptPackagePath, projectInfo);
}
}
else
{
taskPackage.DecryptPackagePath = System.IO.Path.Combine(tempPath, fileName + "_back");
if (!File.Exists(taskPackage.DecryptPackagePath))
{
File.Copy(openPath, taskPackage.DecryptPackagePath, true);
}
}
//if (taskPackage.PackageTempPath == null || string.IsNullOrWhiteSpace(taskPackage.PackageTempPath) || !System.IO.File.Exists(taskPackage.PackageTempPath))
//{
taskPackage.PackageTempPath = taskPackage.DecryptPackagePath.Substring(0, taskPackage.DecryptPackagePath.Length - 5);
//拷贝临时db
if (!File.Exists(taskPackage.PackageTempPath))
{
DecryptDB(taskPackage.DecryptPackagePath, projectInfo);
File.Copy(taskPackage.DecryptPackagePath, taskPackage.PackageTempPath, true);
}
//}
else if (reload)
{
if (File.Exists(taskPackage.PackageTempPath))
{
File.Copy(taskPackage.PackageTempPath, taskPackage.PackageTempPath + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"), true);
}
File.Copy(taskPackage.DecryptPackagePath, taskPackage.PackageTempPath, true);
}
if (rdbHelper != null)
{
rdbHelper.DisConnect();
rdbHelper = null;
}
rdbHelper = RDBFactory.CreateDbHelper($"{taskPackage.PackageTempPath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
CheckTableExist(rdbHelper);
//DecryptDB(taskPackage.PackageTempPath, rdbHelper);
if (taskPackage.GDBPath == null || string.IsNullOrWhiteSpace(taskPackage.GDBPath) || !System.IO.Directory.Exists(taskPackage.GDBPath))
{
if (Platform.Instance.SystemType == SystemTypeEnum.YCLJK)
taskPackage.GDBPath = SysAppPath.GetCurrentAppPath() + "YCLProject\\Scheme-YCL.gdb";
else
taskPackage.GDBPath = projectInfo.ProjDir + "\\Scheme-YCL.gdb";
if (!Directory.Exists(taskPackage.GDBPath))
{
KGIS.Framework.Utils.Helper.CommonHelper.DirectoryCopy(SysAppPath.GetCurrentAppPath() + "工作空间DTBJK\\DatabaseTemplate\\Scheme-YCL.gdb", System.IO.Path.GetDirectoryName(taskPackage.GDBPath));
}
}
if (taskPackage.SchemeGDBPath == null || string.IsNullOrWhiteSpace(taskPackage.SchemeGDBPath) || !Directory.Exists(taskPackage.SchemeGDBPath))
{
if (Platform.Instance.SystemType == SystemTypeEnum.YCLJK)
taskPackage.SchemeGDBPath = SysAppPath.GetCurrentAppPath() + "YCLProject\\Scheme0.gdb";
else
taskPackage.SchemeGDBPath = projectInfo.DTBYCLYHDatabase;
if (!Directory.Exists(taskPackage.SchemeGDBPath))
{
KGIS.Framework.Utils.Helper.CommonHelper.DirectoryCopy(SysAppPath.GetCurrentAppPath() + "工作空间DTBJK\\DatabaseTemplate\\Scheme0.gdb", System.IO.Path.GetDirectoryName(taskPackage.SchemeGDBPath));
}
}
//projectInfo.Save();
//LogAPI.Debug(taskPackage.GDBPath);
workspaceAPI = new WorkspaceAPI(taskPackage.GDBPath, WorkspaceTypeEnum.GDBFile, true);
workspaceSchemeAPI = new WorkspaceAPI(taskPackage.SchemeGDBPath, WorkspaceTypeEnum.GDBFile, true);
SetISpatialReference(workspaceAPI, projectInfo);
SetISpatialReference(workspaceSchemeAPI, projectInfo);
ImportDB(workspaceAPI, workspaceSchemeAPI, rdbHelper);
}
catch (Exception ex)
{
try
{
if (rdbHelper != null)
{
rdbHelper.DisConnect();
rdbHelper = null;
}
if (Directory.Exists(tempPath))
{
Directory.Delete(tempPath, true);
}
}
catch
{
}
throw ex;
}
finally
{
if (workspaceSchemeAPI != null)
{
workspaceSchemeAPI.CloseWorkspace();
}
if (workspaceAPI != null)
{
workspaceAPI.CloseWorkspace();
}
if (rdbHelper != null)
{
rdbHelper.DisConnect();
}
GC.Collect();
}
return DicTBInfo;
}
/// <summary>
/// 新建任务包
/// </summary>
/// <returns></returns>
public static string AddNewPackage()
{
KGIS.Framework.Utils.Dialog.FolderBrowserDialog folderBrowserDialog = null;
IRDBHelper rdbHelper = null;
try
{
string templetePath = System.IO.Path.Combine(SysAppPath.GetCurrentAppPath(), @"工作空间DTBJK\初始化工程模板\YSRW.sqlite");
if (!System.IO.File.Exists(templetePath))
{
throw new Exception(templetePath + "任务包模板不存在,请联系系统管理员!");
}
ProjectInfo projectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
if (projectInfo == null)
{
throw new Exception("未检测到当前打开工程,无法新建任务包!");
}
if (string.IsNullOrWhiteSpace(projectInfo.UserName))
{
throw new Exception("请先使用“用户设置”功能设置您的用户名!");
}
if (string.IsNullOrWhiteSpace(projectInfo.TaskPath))
{
bool b = AddPackage();
if (!b)
{
return string.Empty;
}
}
string rwpc = "YSRW_" + DateTime.Now.ToString("yyyyMMddHHmmss");
string folderPath = System.IO.Path.Combine(projectInfo.TaskPath, "未完成");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
string filePath = System.IO.Path.Combine(folderPath, $"自主举证任务包_{ DateTime.Now.ToString("yyyyMMddHHmmss")}.ysrw");
System.IO.File.Copy(templetePath, filePath, true);
rdbHelper = RDBFactory.CreateDbHelper($"{filePath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
string excuteSQL = string.Format("INSERT INTO YSJ (BLX, BEdition, Encrypted, Pwd, CreateTime, CreateUser, UpdateUser, LastUpdateTime, WKID, RWPC, RuleVersion, PCTime) VALUES('{0}', '{1}', 0, '', '{2}', '{3}', '{3}', '{2}', 0, '{4}', '', '');", "YSRW_New", SysConfigsOprator.GetAppsetingValueByKey("SystemVersion"), DateTime.Now.ToString("yyyyMMddHHmmss"), projectInfo.UserName, rwpc);
rdbHelper.ExecuteNonQueryWithException(excuteSQL, CommandType.Text);
if (projectInfo.ListTaskPackage == null)
{
projectInfo.ListTaskPackage = new List<TaskPackage>();
}
if (projectInfo.ListTaskPackage.Where(x => x.PackagePath == filePath).Count() <= 0)
{
projectInfo.ListTaskPackage.Add(new TaskPackage() { BID = Guid.NewGuid().ToString(), PackagePath = filePath, State = "未完成" });
}
return filePath;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rdbHelper != null)
{
rdbHelper.DisConnect();
}
if (folderBrowserDialog != null)
{
folderBrowserDialog.Dispose();
}
}
}
/// <summary>
/// 新建任务包
/// </summary>
/// <returns></returns>
public static string AddNewPackageForJK()
{
KGIS.Framework.Utils.Dialog.FolderBrowserDialog folderBrowserDialog = null;
IRDBHelper rdbHelper = null;
try
{
string templetePath = System.IO.Path.Combine(SysAppPath.GetCurrentAppPath(), @"工作空间DTBJK\初始化工程模板\YSRW.sqlite");
if (!File.Exists(templetePath))
throw new Exception(templetePath + "任务包模板不存在,请联系系统管理员!");
if (!(MapsManager.Instance.MapService.GetProjectInfo() is ProjectInfo projectInfo))
throw new Exception("未检测到当前打开工程,无法新建任务包!");
if (string.IsNullOrWhiteSpace(projectInfo.TaskPath))
{
bool b = AddPackageForJK();
if (!b)
return string.Empty;
}
string rwpc = "YSRW_" + DateTime.Now.ToString("yyyyMMddHHmmss");
string folderPath = System.IO.Path.Combine(projectInfo.TaskPath, "未完成");
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
string filePath = System.IO.Path.Combine(folderPath, $"自主举证任务包_{ DateTime.Now.ToString("yyyyMMddHHmmss")}.ysrw");
System.IO.File.Copy(templetePath, filePath, true);
rdbHelper = RDBFactory.CreateDbHelper($"{filePath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
string excuteSQL = string.Format("INSERT INTO YSJ (BLX, BEdition, Encrypted, Pwd, CreateTime, CreateUser, UpdateUser, LastUpdateTime, WKID, RWPC, RuleVersion, PCTime) VALUES('{0}', '{1}', 0, '', '{2}', '{3}', '{3}', '{2}', 0, '{4}', '', '');", "YSRW_New", SysConfigsOprator.GetAppsetingValueByKey("SystemVersion"), DateTime.Now.ToString("yyyyMMddHHmmss"), projectInfo.UserName, rwpc);
rdbHelper.ExecuteNonQueryWithException(excuteSQL, CommandType.Text);
if (projectInfo.ListTaskPackage == null)
{
projectInfo.ListTaskPackage = new List<TaskPackage>();
}
if (projectInfo.ListTaskPackage.Where(x => x.PackagePath == filePath).Count() <= 0)
{
projectInfo.ListTaskPackage.Add(new TaskPackage() { BID = Guid.NewGuid().ToString(), PackagePath = filePath, State = "未完成" });
}
return filePath;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rdbHelper != null)
{
rdbHelper.DisConnect();
}
if (folderBrowserDialog != null)
{
folderBrowserDialog.Dispose();
}
}
}
public static bool AddPackage()
{
KGIS.Framework.Utils.Dialog.FolderBrowserDialog folderBrowserDialog = null;
try
{
ProjectInfo projectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
if (projectInfo == null || string.IsNullOrWhiteSpace(projectInfo.JCKPath))
{
MessageHelper.Show("请先使用“基础数据加载”功能设置基础库数据!");
return false;
}
if (string.IsNullOrWhiteSpace(projectInfo.UserName))
{
MessageHelper.ShowTips("请先使用“用户设置”功能设置用户名!");
return false;
}
folderBrowserDialog = new KGIS.Framework.Utils.Dialog.FolderBrowserDialog();
if (!string.IsNullOrWhiteSpace(projectInfo.TaskPath) && Directory.Exists(projectInfo.TaskPath))
{
folderBrowserDialog.SelectedPath = System.IO.Path.GetDirectoryName(projectInfo.TaskPath);
}
DialogResult dialogResult = folderBrowserDialog.ShowDialog();
if (dialogResult != DialogResult.OK)
{
return false;
}
string folderName = "预处理任务目录(" + projectInfo.UserName + ")";
string basePath = System.IO.Path.Combine(folderBrowserDialog.SelectedPath, folderName);
if (System.IO.Path.GetFileNameWithoutExtension(folderBrowserDialog.SelectedPath).Equals(folderName))
{
basePath = folderBrowserDialog.SelectedPath;
}
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
//isFirstLoad = true;
}
List<string> listFolders = new List<string>() { "未完成", "已输出", "临时" };//"未完成", "已完成", "输出成果", "临时"
DirectoryInfo directory = new DirectoryInfo(basePath);
foreach (var item in listFolders)
{
if (directory.GetDirectories(item, SearchOption.TopDirectoryOnly).Length <= 0)
{
Directory.CreateDirectory(System.IO.Path.Combine(basePath, item));
}
}
directory = new DirectoryInfo(folderBrowserDialog.SelectedPath);
FileInfo[] files = directory.GetFiles("*.ysrw", SearchOption.TopDirectoryOnly);
if (projectInfo.TaskPath != null && (files == null || files.Length <= 0))
{
directory = new DirectoryInfo(basePath);
if (directory.Exists && directory.GetFiles("*.*", SearchOption.AllDirectories).Length <= 0)
{
directory.Delete(true);
}
}
foreach (var item in files)
{
item.MoveTo(System.IO.Path.Combine(basePath, "未完成", item.Name));
}
directory = new DirectoryInfo(System.IO.Path.Combine(basePath, "未完成"));
files = directory.GetFiles("*.ysrw", SearchOption.AllDirectories);
if (projectInfo.TaskPath != null && (files == null || files.Length <= 0))
{
MessageHelper.Show("所选目录中“未完成”文件夹中不存在预处理任务包!");
}
projectInfo.ListTaskPackage = new List<TaskPackage>();
projectInfo.TaskPath = basePath;
projectInfo.Save();
return true;
}
catch (Exception ex)
{
LogAPI.Debug(ex);
MessageHelper.ShowError(ex.Message);
return false;
}
finally
{
if (folderBrowserDialog != null)
{
folderBrowserDialog.Dispose();
}
}
}
public static bool AddPackageForJK()
{
KGIS.Framework.Utils.Dialog.FolderBrowserDialog folderBrowserDialog = null;
try
{
ProjectInfo projectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
folderBrowserDialog = new KGIS.Framework.Utils.Dialog.FolderBrowserDialog();
if (!string.IsNullOrWhiteSpace(projectInfo.TaskPath) && Directory.Exists(projectInfo.TaskPath))
{
folderBrowserDialog.SelectedPath = System.IO.Path.GetDirectoryName(projectInfo.TaskPath);
}
DialogResult dialogResult = folderBrowserDialog.ShowDialog();
if (dialogResult != DialogResult.OK)
{
return false;
}
string folderName = "预处理任务目录(" + projectInfo.CODE + ")";
string basePath = System.IO.Path.Combine(folderBrowserDialog.SelectedPath, folderName);
if (System.IO.Path.GetFileNameWithoutExtension(folderBrowserDialog.SelectedPath).Equals(folderName))
{
basePath = folderBrowserDialog.SelectedPath;
}
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
List<string> listFolders = new List<string>() { "未完成", "已输出", "临时" };
DirectoryInfo directory = new DirectoryInfo(basePath);
foreach (var item in listFolders)
{
if (directory.GetDirectories(item, SearchOption.TopDirectoryOnly).Length <= 0)
{
Directory.CreateDirectory(System.IO.Path.Combine(basePath, item));
}
}
directory = new DirectoryInfo(folderBrowserDialog.SelectedPath);
FileInfo[] files = directory.GetFiles("*.ysrw", SearchOption.TopDirectoryOnly);
if (projectInfo.TaskPath != null && (files == null || files.Length <= 0))
{
directory = new DirectoryInfo(basePath);
if (directory.Exists && directory.GetFiles("*.*", SearchOption.AllDirectories).Length <= 0)
{
directory.Delete(true);
}
}
foreach (var item in files)
{
item.MoveTo(System.IO.Path.Combine(basePath, "未完成", item.Name));
}
directory = new DirectoryInfo(System.IO.Path.Combine(basePath, "未完成"));
files = directory.GetFiles("*.ysrw", SearchOption.AllDirectories);
if (projectInfo.TaskPath != null && (files == null || files.Length <= 0))
{
MessageHelper.Show("所选目录中“未完成”文件夹中不存在预处理任务包!");
}
projectInfo.ListTaskPackage = new List<TaskPackage>();
projectInfo.TaskPath = basePath;
projectInfo.Save();
return true;
}
catch (Exception ex)
{
LogAPI.Debug(ex);
MessageHelper.ShowError(ex.Message);
return false;
}
finally
{
if (folderBrowserDialog != null)
{
folderBrowserDialog.Dispose();
}
}
}
/// <summary>
/// 同步任务目录文件夹任务包文件
/// </summary>
/// <param name="dbPath"></param>
/// <returns></returns>
public void SyncPackage(string taskPath)
{
IRDBHelper rdbHelper = null;
DataTable dataTable = null;
try
{
ProjectInfo projectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
if (projectInfo.ListTaskPackage == null)
{
projectInfo.ListTaskPackage = new List<TaskPackage>();
}
if (string.IsNullOrWhiteSpace(taskPath) || !Directory.Exists(taskPath))
{
return;
}
DirectoryInfo directory = new DirectoryInfo(System.IO.Path.Combine(taskPath, "未完成"));
FileInfo[] files = directory.GetFiles("*.ysrw", SearchOption.AllDirectories);
if (files == null || files.Length <= 0)
{
//MessageHelper.Show("“未完成”文件夹中不存在预处理任务包!");
return;
}
foreach (var item in files)
{
try
{
TaskPackage taskPackage = projectInfo.ListTaskPackage.FirstOrDefault(x => x.PackagePath.Equals(item.FullName));
if (taskPackage != null)
{
//try
//{
// if (taskPackage.State.Equals("已输出"))
// {
// System.IO.File.Delete(item.FullName);
// }
//}
//catch
//{
//}
continue;
}
rdbHelper = RDBFactory.CreateDbHelper($"{item.FullName}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
if (!rdbHelper.TableIsExist("wyrw"))
{
throw new Exception("选择的内业预处理任务包不存在外业任务(WYRW)表!");
}
if (!rdbHelper.TableIsExist("YSJ"))
{
throw new Exception("选择的内业预处理任务包不存在元数据(YSJ)表!");
}
dataTable = rdbHelper.ExecuteDatatable("ysj", "select * from ysj", true);
if (dataTable == null || dataTable.Rows.Count <= 0)
{
throw new Exception("选择的内业预处理任务包元数据(YSJ)表数据为空!");
}
string blx = dataTable.Rows[0]["BLX"] as string;
dataTable = rdbHelper.ExecuteDatatable("wyrw", "select * from wyrw", true);
if ((dataTable == null || dataTable.Rows.Count <= 0) && !blx.Equals("YSRW_New"))
{
throw new Exception("选择的内业预处理任务包外业任务表数据为空!");
}
projectInfo.ListTaskPackage.Add(new TaskPackage() { BID = Guid.NewGuid().ToString(), PackagePath = item.FullName, State = "未完成" });
projectInfo.Save();
}
catch (Exception ex)
{
LogAPI.Debug(item + "无法添加:" + ex.Message);
LogAPI.Debug(item + "无法添加:" + ex.StackTrace);
}
finally
{
if (rdbHelper != null)
{
rdbHelper.DisConnect();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void CheckAddFeature(IGeometry geometry, int oid = -1)
{
try
{
IFeatureLayer featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName("ZZTB");
if (featureLayer != null && featureLayer.FeatureClass != null)
{
Dictionary<IGeometry, IFeature> dic = IdentifyReturnIntersect(geometry, featureLayer as ILayer);
if (dic != null && dic.Count > 0)
{
if (dic.Count == 1 && (dic.First().Value as IFeature).OID == oid)
{
}
else
{
throw new Exception("新增图斑存在与自主图斑图层(ZZTB)数据压盖!");
}
}
}
featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName("WYRW");
if (featureLayer != null && featureLayer.FeatureClass != null)
{
Dictionary<IGeometry, IFeature> dic = IdentifyReturnIntersect(geometry, featureLayer as ILayer);
if (dic != null && dic.Count > 0)
{
throw new Exception("新增图斑存在与外业任务图层(WYRW)数据压盖!");
}
}
List<string> lstLayerName = new List<string>() { "基础_国家下发监测图斑", "基础_专项数据" };
foreach (var layerName in lstLayerName)
{
IFeatureLayer layer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName(layerName);
if (layer == null || !(layer is IFeatureLayer) || (layer as IFeatureLayer).FeatureClass == null)
{
continue;
}
featureLayer = layer as IFeatureLayer;
if (featureLayer != null && featureLayer.FeatureClass != null)
{
Dictionary<IGeometry, IFeature> dic = IdentifyReturnIntersect(geometry, featureLayer as ILayer);
if (dic != null && dic.Count > 0)
{
throw new Exception($"新增图斑存在与【{layerName}】数据压盖!");
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 导出预处理成果包
/// </summary>
/// <param name="savePackagePath"></param>
/// <param name="savePath"></param>
public static string ExportDB(string savePackagePath, string savePath)
{
IRDBHelper rdbHelper = null;
try
{
ProjectInfo projectInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
rdbHelper = RDBFactory.CreateDbHelper($"{savePackagePath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
CheckTableExist(rdbHelper);
//生成对称加密秘钥
string key = EncryptionHelper.GenerKeySM4();
//去除冗余的数据
rdbHelper.ExecuteNonQueryWithException("delete from wyrw where cdtb=1", CommandType.Text);//删除重叠图斑数据
rdbHelper.ExecuteNonQueryWithException("delete from nyysresult where tbbsm not in(select tbbsm from wyrw)", CommandType.Text);
rdbHelper.ExecuteNonQueryWithException("delete from wysketch where tbbsm not in(select tbbsm from wyrw)", CommandType.Text);
rdbHelper.ExecuteNonQueryWithException("delete from ysj", CommandType.Text);
//处理输出成果包文件的名称
string fileReName = string.Empty;
DataTable dataTable = rdbHelper.ExecuteDatatable("wyrw", "select bsm, xzqdm, geometry, egeometry from wyrw", true);
if (dataTable == null || dataTable.Rows.Count <= 0)
{
fileReName = "XZQDM_0个图斑_" + projectInfo.UserName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".yscg";
}
else
{
//处理输出成果包文件的名称
string xzqdm = dataTable.Rows[0][1] as string;
if (string.IsNullOrWhiteSpace(xzqdm))
{
DataRow[] drs = dataTable.Select("xzqdm <> null and xzqdm<>''");
if (drs != null && drs.Length > 0)
{
xzqdm = drs[0][1] as string;
}
}
fileReName = xzqdm + "_" + dataTable.Rows.Count + "个图斑_" + projectInfo.UserName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".yscg";
//对外业任务图形数据加密
string excuteSQL = "update wyrw set geometry=null,egeometry='{0}' where bsm='{1}'";
foreach (DataRow item in dataTable.Rows)
{
rdbHelper.ExecuteNonQueryWithException(string.Format(excuteSQL, EncryptionHelper.SM4Encrypt(item["egeometry"] as string, key), item["bsm"]), CommandType.Text);
}
}
//如果工程坐标参考WKID为空则重新赋值
if (projectInfo.WKID <= 0)
{
projectInfo.WKID = projectInfo.GetCurentProjectedCoordinate().FactoryCode;
if (projectInfo.WKID <= 0)
{
CoordinateReferenceMapping coordinateReferenceMapping = CoordinateHelper.ListCoordinateReference.FirstOrDefault(x => (projectInfo.ZYJD > x.MinX && projectInfo.ZYJD < x.MaxX) || x.Central_Meridian.Equals(projectInfo.ZYJD));
if (coordinateReferenceMapping != null)
{
projectInfo.WKID = coordinateReferenceMapping.WKID;
}
}
projectInfo.Save();
}
//文件元数据信息
FileInfo fileInfo = new FileInfo(savePackagePath);
string insertSQL = string.Format("insert into ysj (blx, bedition, encrypted, pwd, createtime, createuser, updateuser, lastupdatetime,wkid) values('{0}', '{1}', {2}, '{3}','{4}', '{5}', '{6}', '{7}','{8}');", "内业预处理成果包", KGIS.Framework.Utils.SysConfigsOprator.GetAppsetingValueByKey("SystemVersion"), 1, EncryptionHelper.SM2Encrypt(key, 3, projectInfo.CODE), DateTime.Now.ToString(), projectInfo.UserName, projectInfo.UserName, fileInfo.LastWriteTime, projectInfo.WKID);
rdbHelper.ExecuteNonQueryWithException(insertSQL, CommandType.Text);
//压缩输出成果db文件
Kingo.PluginServiceInterface.CommonHelper.ExecuteZip(savePackagePath);
string saveFilePath = System.IO.Path.Combine(savePath, fileReName);
//重命名输出成果包到导出目标文件
System.IO.File.Copy(savePackagePath, saveFilePath, true);
//基础库gdb路径:用来生成基础库数据的签章
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("Result", EncryptionHelper.GetFileSing(saveFilePath, projectInfo.CODE));
dic.Add("JCData", EncryptionHelper.GetFileSing(projectInfo.JCKPath, projectInfo.CODE, "GDB"));
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
string signFileName = System.IO.Path.Combine(savePath, System.IO.Path.GetFileNameWithoutExtension(saveFilePath) + ".sign");
EncryptionHelper.CreateSign(jsonString, signFileName);
return System.IO.Path.Combine(savePath, fileReName);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (rdbHelper != null)
{
rdbHelper.DisConnect();
}
}
}
/// <summary>
/// 验证包表结构是否都存在
/// </summary>
public static void CheckTableExist(IRDBHelper rdbHelper)
{
try
{
if (!rdbHelper.TableIsExist("WYRW"))
{
throw new Exception("选择的任务包不存在WYRW(外业任务)表,请确认是否是《预处理任务包》!");
}
if (!rdbHelper.TableIsExist("YSJ"))
{
throw new Exception("选择的DB不存在YSJ(元数据)表,请确认是否是《预处理任务包》!");
}
string excuteSQL = @"
CREATE TABLE if not exists NYYSResult (
BSM INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
TBBSM TEXT,
NYYPDL TEXT,
SFXYWY INTEGER,
YPSM TEXT,
YPRY TEXT,
YPSJ TEXT
);
CREATE TABLE if not exists YSJ (
BLX TEXT,
BEdition TEXT,
Encrypted INTEGER,
Pwd TEXT,
CreateTime TEXT,
CreateUser TEXT,
UpdateUser TEXT,
LastUpdateTime TEXT
);
CREATE TABLE if not exists WYSketch (
BSM INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
TBBSM TEXT,
BZLX TEXT,
BZMS TEXT,
Geometry TEXT
);
CREATE TABLE if not exists FJGX (
BSM INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
FJARG TEXT NOT NULL,
TBBSM TEXT NOT NULL
);
CREATE TABLE if not exists WYHCFJ(
BSM INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
HCLX TEXT NOT NULL,
HCJLBSM TEXT NOT NULL,
DKID TEXT,
FJMC TEXT NOT NULL,
FJLX TEXT NOT NULL,
FJLJ TEXT, MODE TEXT,
SEQUENCE INTEGER,
SUBTYPE TEXT,
ARG TEXT,
ARG2 TEXT,
ARG3 TEXT,
ARG4 BLOB,
IS_SELECTED INTEGER,
CJSJ DATETIME NOT NULL,
LENGTH INTEGER NOT NULL DEFAULT 0,
POINTS_JSON TEXT,
HCRY TEXT,
GROUP_INDEX INTEGER,
GROUPCODE TEXT,
SUBTASKID TEXT,
AIResult TEXT,
AR_FJ BLOB,
CHECK_CODE TEXT,
UserDelete INTEGER
);";
rdbHelper.ExecuteNonQueryWithException(excuteSQL, CommandType.Text);
//WYHRFJ外业核查附件表增加用户是否标记删除字段
DataTable dataTable = rdbHelper.ExecuteDatatable("wyhcfj", "select * from WYHCFJ where 1=2", true);
if (dataTable != null && !dataTable.Columns.Contains("UserDelete"))
{
rdbHelper.ExecuteNonQueryWithException("ALTER TABLE WYHCFJ ADD 'UserDelete' INTEGER;");
//增加字段后,默认都为0:非删除状态,1是删除状态,删除状态的不展示该附件
rdbHelper.ExecuteNonQueryWithException("UPDATE WYHCFJ SET UserDelete=0;");
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 解密db
/// </summary>
private void DecryptDB(string dbPath, ProjectInfo projectInfo, IRDBHelper rdbHelper = null)
{
bool closeRDBHelper = false;
try
{
if (rdbHelper == null)
{
rdbHelper = RDBFactory.CreateDbHelper($"{dbPath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
closeRDBHelper = true;
}
DataTable dataTable = rdbHelper.ExecuteDatatable("ysj", "select * from ysj", true);
if (dataTable == null || dataTable.Rows.Count == 0)
{
throw new Exception("元数据为空!");
}
YSJ YSJInfo = KGIS.Framework.Utils.Utility.TBToList.ConvertEntity<YSJ>(dataTable.Rows[0]);
if (YSJInfo == null)
{
throw new Exception("获取元数据失败!");
}
string key = string.Empty;
if (YSJInfo.Encrypted == 1)
{
if (string.IsNullOrWhiteSpace(YSJInfo.Pwd))
{
throw new Exception("任务包元数据表Encrypted字段为1(加密包),但Pwd密码字段为空!");
}
key = EncryptionHelper.SM2Decrypt(YSJInfo.Pwd, projectInfo.CODE);
dataTable = rdbHelper.ExecuteDatatable("wyrw", "select bsm,geometry,egeometry from wyrw", true);
if (dataTable == null || dataTable.Rows.Count <= 0)
{
return;
}
string excuteSQL = "update wyrw set geometry='{0}',egeometry='{0}' where bsm='{1}'";
foreach (DataRow item in dataTable.Rows)
{
string geometryStr = item["egeometry"] as string;
try
{
geometryStr = EncryptionHelper.SM4Decrypt(geometryStr, key);
}
catch (Exception ex)
{
try
{
IGeometry geometry = GeometryConvertHelper.ConverJsonToIGeoemtry(geometryStr);
}
catch
{
throw ex;
}
}
rdbHelper.ExecuteNonQueryWithException(string.Format(excuteSQL, geometryStr, item["bsm"]), CommandType.Text);
}
rdbHelper.ExecuteNonQueryWithException("update ysj set Encrypted=0,pwd=null", CommandType.Text);
}
}
catch (Exception ex)
{
throw new Exception("解密任务包异常:" + ex.Message);
}
finally
{
if (closeRDBHelper && rdbHelper != null)
{
rdbHelper.DisConnect();
}
}
}
/// <summary>
/// 设置工程数据库要素集和要素类坐标参考
/// </summary>
/// <param name="workspaceAPI"></param>
private void SetISpatialReference(IWorkspaceAPI workspaceAPI, ProjectInfo projectInfo)
{
ISpatialReference reference = projectInfo.GetCurentProjectedCoordinate();
double Tolerance = 0.0001;
//string ToleranceCfg = ""; //Config.SysConfigsOprator.GetAppsetingValueByKey("Tolerance");
//if (!string.IsNullOrWhiteSpace(ToleranceCfg))
//{
// if (!double.TryParse(ToleranceCfg, out Tolerance))
// {
// Tolerance = 0.0001;
// }
//}
GeoDBAPI.SetGeoDatasetSpatialReference(workspaceAPI.CurrentWorkspace, reference, Tolerance);
//设置坐标参考精度XYUnits 为二万分之一
try
{
workspaceAPI.CurrentWorkspace.ExecuteSQL(string.Format("UPDATE GDB_SpatialRefs SET XYUnits = 20000 ,XYTolerance = {0}", Tolerance));
}
catch (Exception ex)
{
LogAPI.Debug("设置坐标参考坐标精度和容差异常 时失败,异常原因: " + ex + " ; ");
throw new Exception("设置坐标参考坐标精度和容差异常:" + ex.Message);
}
}
private void ImportDB(IWorkspaceAPI workspaceAPI, IWorkspaceAPI workspaceSchemeAPI, IRDBHelper rdbHelper)
{
try
{
//KGIS.Framework.Platform.Helper.ProgressHelper.SetProcessMsg("正在设置坐标参考......");
DataTable hasTable = rdbHelper.ExecuteDatatable("alltables", "SELECT name FROM sqlite_master WHERE type = 'table' and name<>'sqlite_sequence' ORDER BY name;", true);
foreach (DataRow dr in hasTable.Rows)
{
ITableAPI tableAPI = null;
string tableName = dr[0] as string;
try
{
if (tableName.Equals("WYSketch", StringComparison.CurrentCultureIgnoreCase))
{
Dictionary<string, string> dciBZTable = new Dictionary<string, string>();
dciBZTable.Add("点", "MarkPoint");
dciBZTable.Add("线", "MarkLine");
dciBZTable.Add("面", "MarkPolygon");
foreach (var item in dciBZTable)
{
try
{
tableAPI = workspaceSchemeAPI.OpenTable(item.Value);
}
catch
{
continue;
}
//此方法很慢
//if (!workspaceSchemeAPI.ExistFeatureClass(item.Value))
//{
// continue;
//}
workspaceSchemeAPI.CurrentWorkspace.ExecuteSQL(string.Format("DELETE FROM {0} where bid='{1}'", item.Value, this.bh));
DataTable dataTable = rdbHelper.ExecuteDatatable(tableName, "select * from " + tableName + " where bzlx='" + item.Key + "'", true);
if (dataTable == null || dataTable.Rows.Count <= 0)
{
continue;
}
DataTableImportToGDB("外业指导草图[" + tableName + "]", dataTable, tableAPI);
}
}
else if (tableName.Equals("WYRW", StringComparison.CurrentCultureIgnoreCase))
{
//外业任务图斑图层
//if (!workspaceAPI.ExistFeatureClass(tableName))
//{
// continue;
//}
try
{
tableAPI = workspaceAPI.OpenTable(tableName);
}
catch
{
continue;
}
workspaceAPI.CurrentWorkspace.ExecuteSQL(string.Format("DELETE FROM {0} where bid='{1}'", tableName, this.bh));
DataTable dataTable = rdbHelper.ExecuteDatatable(tableName, $"select a.*,(case when length(b.tbbsm)>0 then 'true' else 'false' end) as ybc from {tableName} a left join nyysresult b on a.tbbsm=b.tbbsm WHERE a.SJLY<>'ZZBG' AND a.SJLY IS NOT NULL AND a.SJLY <>'' AND a.CDTB<>1", true);
if (dataTable != null && dataTable.Rows.Count > 0)
{
foreach (DataRow item in dataTable.Rows)
{
DicTBInfo.Add(item, 1);
}
DataTableImportToGDB("外业任务图斑[" + tableName + "]", dataTable, tableAPI);
}
//自主变更图斑图层
//if (!workspaceSchemeAPI.ExistFeatureClass("ZZTB"))
//{
// continue;
//}
try
{
tableAPI = workspaceSchemeAPI.OpenTable("ZZTB");
}
catch
{
continue;
}
workspaceSchemeAPI.CurrentWorkspace.ExecuteSQL(string.Format("DELETE FROM ZZTB where bid='{0}' and SJLY='ZZBG'", this.bh));
dataTable = rdbHelper.ExecuteDatatable(tableName, $"select a.*,(case when length(b.tbbsm)>0 then 'true' else 'false' end) as ybc from {tableName} a left join nyysresult b on a.tbbsm=b.tbbsm WHERE SJLY='ZZBG' AND (CDTB is null or CDTB<>1);", true);
if (dataTable != null && dataTable.Rows.Count > 0)
{
foreach (DataRow item in dataTable.Rows)
{
DicTBInfo.Add(item, 2);
}
DataTableImportToGDB("自主变更图斑[" + tableName + "]", dataTable, tableAPI);
}
try
{
tableAPI = workspaceAPI.OpenTable("CDTB");
}
catch
{
continue;
}
workspaceAPI.CurrentWorkspace.ExecuteSQL(string.Format("DELETE FROM {0} where bid='{1}'", "CDTB", this.bh));
dataTable = rdbHelper.ExecuteDatatable(tableName, "select * from " + tableName + " WHERE CDTB=1", true);
if (dataTable != null && dataTable.Rows.Count > 0)
{
foreach (DataRow item in dataTable.Rows)
{
DicTBInfo.Add(item, 3);
}
DataTableImportToGDB("重叠图斑[" + tableName + "]", dataTable, tableAPI);
}
}
else
{
//if (!workspaceAPI.ExistFeatureClass(tableName))
//{
// continue;
//}
try
{
tableAPI = workspaceAPI.OpenTable(tableName);
}
catch
{
continue;
}
workspaceAPI.CurrentWorkspace.ExecuteSQL(string.Format("DELETE FROM {0} where bid='{1}'", tableName, this.bh));
DataTable dataTable = rdbHelper.ExecuteDatatable(tableName, "select * from " + tableName, true);
if (dataTable == null || dataTable.Rows.Count <= 0)
{
continue;
}
DataTableImportToGDB(tableName, dataTable, tableAPI);
}
}
catch (Exception ex)
{
throw new Exception(tableName + "数据矢量化失败:" + ex.Message);
}
finally
{
if (tableAPI != null)
{
tableAPI.CloseTable();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// DataTable数据插入到GDB
/// </summary>
/// <param name="dataTable"></param>
/// <param name="featureClassAPI"></param>
private void DataTableImportToGDB(string tableName, DataTable dataTable, ITableAPI tableAPI)
{
ICursor cursor = null;
try
{
cursor = tableAPI.ITable.Insert(true);
IRowBuffer rowBuffer = tableAPI.ITable.CreateRowBuffer();
//KGIS.Framework.Platform.Helper.ProgressHelper.SetProcessMsg("正在导入" + tableName + "数据......");
//string message = "正在导入" + tableName + "数据[{0}/" + dataTable.Rows.Count + "]......";
//int i = 0;
int indexShape = tableAPI.ITable.FindField("Shape");
int indexBH = tableAPI.ITable.FindField("BID");
foreach (DataRow dr in dataTable.Rows)
{
//更新包号字段
if (indexBH > -1)
{
rowBuffer.set_Value(indexBH, this.bh.ToString());
}
foreach (DataColumn dc in dataTable.Columns)
{
int index = tableAPI.ITable.FindField(dc.ColumnName);
if (index > -1)
{
if (dr[dc.ColumnName] is DBNull)
{
rowBuffer.set_Value(index, DBNull.Value);
}
else
{
rowBuffer.set_Value(index, dr[dc.ColumnName]);
}
}
//处理图形
if (dc.ColumnName.EndsWith("geometry", StringComparison.CurrentCultureIgnoreCase) && indexShape > -1 && !string.IsNullOrWhiteSpace(dr[dc.ColumnName] as string))
{
IGeometry geometry = null;
IFeatureClass featureClass = tableAPI.ITable as IFeatureClass;
if (featureClass != null)
{
switch (featureClass.ShapeType)
{
case esriGeometryType.esriGeometryPoint:
geometry = GeometryConvertHelper.ConverJsonToIGeoemtry(dr[dc.ColumnName] as string, esriGeometryType.esriGeometryPoint);
break;
case esriGeometryType.esriGeometryPolyline:
geometry = GeometryConvertHelper.ConverJsonToIGeoemtry(dr[dc.ColumnName] as string, esriGeometryType.esriGeometryPolyline);
break;
case esriGeometryType.esriGeometryPolygon:
geometry = GeometryConvertHelper.ConverJsonToIGeoemtry(dr[dc.ColumnName] as string);
break;
}
}
if (geometry != null)
{
geometry.Project((tableAPI.ITable as IGeoDataset).SpatialReference);
rowBuffer.set_Value(indexShape, geometry);
}
}
}
cursor.InsertRow(rowBuffer);
//KGIS.Framework.Platform.Helper.ProgressHelper.SetProcessMsg(string.Format(message, i++));
}
cursor.Flush();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cursor != null)
{
Marshal.ReleaseComObject(cursor);
}
}
}
#region 打开编辑
public static void StartEdit(IEngineEditor EngineEditor, IHookHelper hookHelper, IFeatureLayer featureLayer)
{
try
{
if (EngineEditor == null || hookHelper == null || hookHelper.FocusMap == null || featureLayer == null || featureLayer.FeatureClass == null) return;
if (MapsManager.Instance.MapService.GetProjectInfo() == null || string.IsNullOrWhiteSpace((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).JCKPath))
{
MessageHelper.Show("请先设置工作目录,加载基础库数据!");
return;
}
(featureLayer.FeatureClass as FeatureClass as IFeatureClassLoad).LoadOnlyMode = false;
IWorkspace SchemeWork = (featureLayer.FeatureClass as FeatureClass).Workspace;
if (SchemeWork == null) return;
EngineEditor.StartEditing(SchemeWork, hookHelper.FocusMap);
IEngineEditLayers pEditLayer = EngineEditor as IEngineEditLayers;
pEditLayer.SetTargetLayer(featureLayer, 0);
}
catch (Exception ex)
{
MessageHelper.ShowError("打开编辑失败:" + ex.Message);
}
}
private ControlsEditingSaveCommandClass saveCommandClass { get; set; }
public void SaveEingineEdit(IHookHelper hookHelper)
{
try
{
if (saveCommandClass == null)
{
saveCommandClass = new ControlsEditingSaveCommandClass();
saveCommandClass.OnCreate(hookHelper.Hook);
}
saveCommandClass.OnClick();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
/// <summary>
/// 识别要素
/// </summary>
/// <param name="pGeo">指定图形</param>
/// <param name="pLayer">目标图层</param>
/// <returns>返回目标图层中与指定图形有交集的要素集合(不包含相邻要素)</returns>
public static Dictionary<IGeometry, IFeature> IdentifyReturnIntersect(IGeometry pGeo, ILayer pLayer)
{
Dictionary<IGeometry, IFeature> result = new Dictionary<IGeometry, IFeature>();
try
{
if (pGeo != null && !pGeo.IsEmpty && pLayer != null)
{
IIdentify identify = pLayer as IIdentify;
if (identify == null)
return result;
IArray array = identify.Identify(pGeo);
if (array == null)
return result;
for (int i = 0; i < array.Count; i++)
{
IRowIdentifyObject row = (IRowIdentifyObject)array.get_Element(i);
if (row == null)
{
continue;
}
IFeature f = row.Row as IFeature;
//pGeo.Project(((pLayer as IFeatureLayer).FeatureClass as IGeoDataset).SpatialReference);
IGeometry geometry = f.ShapeCopy;
if (!geometry.SpatialReference.Name.Equals(pGeo.SpatialReference.Name))
{
geometry.Project(pGeo.SpatialReference);
}
IGeometry geo = InterSect(geometry, pGeo);
if (geo != null && !geo.IsEmpty)
{
result.Add(geo, f);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
/// <summary>
/// 求两个图形相交部分
/// </summary>
/// <param name="pGeo1">图形1</param>
/// <param name="pGeo2">图形2</param>
/// <returns></returns>
public static IGeometry InterSect(IGeometry pGeo1, IGeometry pGeo2)
{
try
{
IGeometry result = null;
if (pGeo1 == null || pGeo2 == null)
return null;
ITopologicalOperator topo = pGeo1 as ITopologicalOperator;
if (topo != null)
{
topo.Simplify();
pGeo2.SpatialReference = pGeo1.SpatialReference;
ITopologicalOperator topo2 = pGeo2 as ITopologicalOperator;
topo2.Simplify();
if (pGeo1.GeometryType == esriGeometryType.esriGeometryPoint || pGeo2.GeometryType == esriGeometryType.esriGeometryPoint)
{
result = topo.Intersect(pGeo2, esriGeometryDimension.esriGeometry0Dimension);
}
else if (pGeo1.GeometryType == esriGeometryType.esriGeometryPolyline || pGeo2.GeometryType == esriGeometryType.esriGeometryPolyline)
{
result = topo.Intersect(pGeo2, esriGeometryDimension.esriGeometry1Dimension);
}
else
{
result = topo.Intersect(pGeo2, pGeo2.Dimension);
}
if (result != null)
{
ITopologicalOperator resultTopo = result as ITopologicalOperator;
resultTopo.Simplify();
}
return result;
}
return null;
}
catch (Exception ex)
{
throw ex;
}
}
}
}