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

5294 lines
278 KiB

4 months ago
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geoprocessor;
using KGIS.Framework.AE;
using KGIS.Framework.AE.Enum;
using KGIS.Framework.AE.ExtensionMethod;
using KGIS.Framework.AE.GPHelper;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Platform.Helper;
using KGIS.Framework.ThreadManager;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Views;
using Kingo.PluginServiceInterface;
using Kingo.PluginServiceInterface.Model;
using KUI.Windows;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using UIShell.OSGi;
namespace Kingo.Plugin.DataCheck.View
{
/// <summary>
/// V_DataCheck.xaml 的交互逻辑
/// </summary>
public partial class V_DataCheck : UserControl, IDockPanel2, IDataCheckHelper
{
private DataCheckHelper m_Check = null;
private Style _ExpanderStyle = null;
private string _CheckName = string.Empty;
private IHookHelper m_hookHelper = null;
private string TempfilePath = string.Empty;
/// <summary>
/// 地图视图刷新
/// </summary>
private ControlsMapRefreshViewCommandClass MapRefreshView = new ControlsMapRefreshViewCommandClass();
public V_DataCheck(string CheckName, DataCheckHelper dataCheckHelper = null, IHookHelper _hookHelper = null)
{
try
{
InitializeComponent();
DevExpress.Xpf.Core.ThemeManager.SetTheme(this, DevExpress.Xpf.Core.Theme.Office2013LightGray);
m_hookHelper = _hookHelper;
this.Resources = Application.LoadComponent(new Uri(string.Format("{0}.{1}", "/Kingo.Plugin.DataCheck;component/Views/V_Resources/V_ResDic", "xaml"), UriKind.Relative)) as ResourceDictionary;
//DevExpress.Xpf.Core.ThemeManager.SetTheme(this, DevExpress.Xpf.Core.Theme.Office2013LightGray);
this.DockAreas = DockStyle.DockBottom | DockStyle.Float;
this.FloatSize = new System.Drawing.Size(600, 400);
this.DefaultArea = DockStyle.DockBottom;
this.ShowCloseButton = true;
this.ShowAutoHideButton = true;
//this.Title = "变更数据检查";
this.IsShowInMap = true;
this.DockHeight = 350;
_ExpanderStyle = (Style)this.Resources["ExpanderStyle"];
if (!string.IsNullOrEmpty(CheckName))
_CheckName = CheckName;
#region 设置检查中状态样式-注释
//m_Check = dataCheckHelper;
//this.DataContext = m_Check;
//this.CloseViewHandler += (e, a) =>
//{
// UIShell.OSGi.BundleRuntime.Instance.RemoveService<IDataCheckHelper>(this);
//};
//UIShell.OSGi.BundleRuntime.Instance.AddService<IDataCheckHelper>(this);
//IdataChecks = new List<IDataCheck>();
//IdataChecks.Add(new BGHDataCheck());
//IdataChecks.Add(new BGQDataCheck());
//IdataChecks.Add(new JCDLTBDataCheck());
//IdataChecks.Add(new JCCZCDYDDataCheck());
//DataTemplate datatemplate = this.Resources["TvItemNode"] as DataTemplate;
//foreach (var item in m_Check.CheckGroup)
//{
// Expander exp = new Expander();
// exp.BorderThickness = new Thickness(0);
// exp.Name = item.GroupName;
// exp.DataContext = item;
// exp.VerticalAlignment = VerticalAlignment.Stretch;
// exp.IsExpanded = true;
// exp.Style = _ExpanderStyle;
// exp.SetBinding(Expander.HeaderProperty, new Binding("GroupName"));
// TreeView tv = new TreeView();
// tv.Style = (Style)this.Resources["DefaultTreeView"];
// tv.ItemTemplate = datatemplate;
// tv.ItemsSource = item.CheckRules;
// exp.Content = tv;
// spCheckRule.Children.Add(exp);
//}
#endregion
InitView(out bool isFinishd);
//LoadData();
}
catch (Exception ex)
{
MessageHelper.Show("数据检查界面初始化失败!");
LogAPI.Debug("数据检查界面初始化失败:" + ex.Message);
}
}
public List<DataCheckResult> FieldsTempData = null;
private void InitView(out bool isFinishd)
{
isFinishd = false;
IRDBHelper rdbHelper = null;
try
{
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
DataTable dataTable = null;
string DataCheckResultsSQL = string.Empty;
if (_CheckName == "变更图斑")
{
dataTable = rdbHelper.ExecuteDatatable("tab", " SELECT RuleType from DataCheckResults ", true);
DataCheckResultsSQL = " where ErrorLayer='DLTBBG' or ErrorLayer='地类图斑变更层' ";
}
else if (_CheckName == "增量图斑")
{
dataTable = rdbHelper.ExecuteDatatable("tab", " SELECT RuleType from DataCheckResults ", true);
DataCheckResultsSQL = " where ErrorLayer!='DLTBBG' and ErrorLayer!='DLTB' and ErrorLayer!='地类图斑变更层' and ErrorLayer!='地类图斑' ";
}
else if (_CheckName == "基础图斑")
{
dataTable = rdbHelper.ExecuteDatatable("tab", " SELECT RuleType from DataCheckResults ", true);
DataCheckResultsSQL = " where ErrorLayer='DLTB' or ErrorLayer='地类图斑' ";
}
string Msg = "检查完成:";
dataTable = rdbHelper.ExecuteDatatable("tab", $"select * from DataCheckResults {DataCheckResultsSQL}", true);
DataTable dataTablegroupby = rdbHelper.ExecuteDatatable("dataTablegroupby", " select RuleType,RuleType RuleName from CheckingRule where BGLayerName NOTNULL GROUP BY RuleType ", true);
FieldsTempData = new List<DataCheckResult>();
var _ID = dataTable.Rows.Count + 1;
int FieldsTempDataID = 0;
foreach (DataRow row in dataTablegroupby.Rows)
{
var RuleTypeTab = dataTable.Select($"RuleType = '{row["RuleType"].ToString()}'").ToList();
//当前仅进行图形括扑检查;
if (!row["RuleName"].ToString().ToTrim().Equals("图形拓扑") && _CheckName == "基础图斑") continue;
if (!row["RuleName"].ToString().ToTrim().Equals("图形拓扑") && _CheckName == "增量图斑") continue;
DataCheckResult checkingRule = new DataCheckResult()
{
ID = _ID,
PID = _ID,
ErrorDesc = row["RuleName"].ToString(),
};
FieldsTempData.Add(checkingRule);
if (RuleTypeTab.Count > 0)
{
string MsgItem = string.Format("{0} {1} 个错误;", row["RuleType"].ToString(), RuleTypeTab.Count);
Msg += MsgItem;
foreach (DataRow item in RuleTypeTab)
{
FieldsTempData.Add(new DataCheckResult()
{
//ID = Convert.ToInt32($"{checkingRule.ID}{item["ID"].ToString()}"),
ID = FieldsTempDataID++,
PID = checkingRule.ID,
BSM = item["BSM"].ToString(),
ErrorDesc = $"【{item["BSM"].ToString()}】{item["ErrorName"].ToString()}",
ErrorCode = item["ErrorCode"].ToTrim(),
ErrorLayer = item["ErrorLayer"].ToTrim(),
PrimaryKey = "OBJECTID",
PrimaryKeyValue = item["OBJECTID"].ToInt().ToTrim(),
ErrorArea = item["ErrorArea"].ToTrim(),
PrimaryKeyValue2 = item["MultipartOID"].ToTrim(),
RepairfilePath = item["RepairfilePath"].ToString(),
});
}
}
_ID++;
}
this.treeList.ItemsSource = FieldsTempData;
labCheckMsg.Content = Msg.TrimEnd(";");
isFinishd = true;
#region MyRegion
//spCheckResult.Children.Clear();
//string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
//rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
//DataTable dataTable = null;
//string DataCheckResultsSQL = string.Empty;
//if (_CheckName == "变更图斑")
//{
// dataTable = rdbHelper.ExecuteDatatable("tab", " SELECT RuleType from CheckingRule where BGIsSelect=true GROUP BY RuleType ", true);
// DataCheckResultsSQL = " where ErrorLayer='DLTBBG' ";
//}
//else if (_CheckName == "增量图斑")
//{
// dataTable = rdbHelper.ExecuteDatatable("tab", " SELECT RuleType from CheckingRule where ZLIsSelect=true GROUP BY RuleType ", true);
// DataCheckResultsSQL = " where ErrorLayer!='DLTBBG' and ErrorLayer!='DLTB' ";
//}
//else if (_CheckName == "基础图斑")
//{
// dataTable = rdbHelper.ExecuteDatatable("tab", " SELECT RuleType from CheckingRule where ImplementSQL='Topology_JCDLTB' GROUP BY RuleType ", true);
// DataCheckResultsSQL = " where ErrorLayer='DLTB' ";
//}
//string Msg = "检查完成:";
//var MaxHeight = 200;
//foreach (DataRow row in dataTable.Rows)
//{
// List<DataCheckResult> CheckResults = new List<DataCheckResult>();
// Expander exp = new Expander();
// exp.Name = row["RuleType"].ToString();
// exp.DataContext = row;
// exp.VerticalAlignment = VerticalAlignment.Stretch;
// exp.Style = _ExpanderStyle;
// exp.IsExpanded = true;
// //exp.SetBinding(Expander.HeaderProperty, new Binding("GroupDesc"));
// exp.Header = row["RuleType"].ToString();
// ContextMenu cm = new ContextMenu();
// cm.Opened += (s, e) =>
// {
// var list = (cm.PlacementTarget as ListBox);
// DataCheckResult data = list.SelectedItem as DataCheckResult;
// if (data != null)
// {
// for (int i = 0; i < cm.Items.Count; i++)
// {
// MenuItem item = cm.Items[i] as MenuItem;
// if (item.Header.ToTrim() == "自动修复")
// {
// continue;
// }
// item.IsEnabled = false;
// }
// for (int i = 0; i < cm.Items.Count; i++)
// {
// MenuItem item = cm.Items[i] as MenuItem;
// if (data.PrimaryKeyValue == "-1" || data.PrimaryKeyValue == "0")
// {
// if (item.Header.ToTrim() == "合并")
// {
// item.IsEnabled = true;
// }
// }
// else
// {
// if (item.Header.ToTrim() == "删除" || item.Header.ToTrim() == "擦除")
// {
// item.IsEnabled = true;
// }
// }
// }
// }
// };
// MenuItem mitem = null;
// if (row["RuleType"].ToString() == "图形拓扑")
// {
// mitem = new MenuItem { Header = "删除", IsEnabled = false };
// mitem.Click += new RoutedEventHandler(Delete_Click);
// cm.Items.Add(mitem);
// mitem = new MenuItem { Header = "合并", IsEnabled = false };
// mitem.Click += new RoutedEventHandler(Merge_Click);
// cm.Items.Add(mitem);
// mitem = new MenuItem { Header = "擦除", IsEnabled = false };
// mitem.Click += new RoutedEventHandler(Erase_Click);
// cm.Items.Add(mitem);
// }
// else
// {
// mitem = new MenuItem { Header = "自动修复" };
// mitem.Click += new RoutedEventHandler(RepairItem_Click);
// cm.Items.Add(mitem);
// }
// ListBox dg = new ListBox();
// dg.ContextMenu = cm;
// dg.PreviewMouseDoubleClick += Dg_PreviewMouseDoubleClick;//双击
// dg.BorderThickness = new Thickness(0);
// DataTemplate datatemplate = this.Resources["ItemNode"] as DataTemplate;
// dg.ItemTemplate = datatemplate;
// dg.VerticalAlignment = VerticalAlignment.Stretch;
// dg.MaxHeight = MaxHeight;
// dg.SetBinding(ListBox.ItemsSourceProperty, new Binding("CheckResults"));
// exp.Content = dg;
// DataTable dtFJ = rdbHelper.ExecuteDatatable("tab", $"select * from DataCheckResults {DataCheckResultsSQL} and RuleType='{row["RuleType"].ToString()}' ", true);
// if (dtFJ == null) return;
// string MsgItem = string.Format("{0} {1} 个错误;", row["RuleType"].ToString(), dtFJ.Rows.Count);
// Msg += MsgItem;
// for (int i = 0; i < dtFJ.Rows.Count; i++)
// {
// int id = dtFJ.Rows[i]["ID"].ToInt();
// int bgoid = dtFJ.Rows[i]["OBJECTID"].ToInt();
// string errorDesc = dtFJ.Rows[i]["ErrorName"].ToTrim();
// string jcErrorCode = dtFJ.Rows[i]["ErrorCode"].ToTrim();
// string errorLayer = dtFJ.Rows[i]["ErrorLayer"].ToTrim();
// string BSM = dtFJ.Rows[i]["BSM"].ToTrim();
// string ErrorArea = dtFJ.Rows[i]["ErrorArea"].ToTrim();
// string MultipartOID = dtFJ.Rows[i]["MultipartOID"].ToTrim();
// string RepairfilePath = dtFJ.Rows[i]["RepairfilePath"].ToTrim();
// EnumErrorType errType = (EnumErrorType)Enum.Parse(typeof(EnumErrorType), "错误");
// CheckResults.Add(new DataCheckResult()
// {
// ID = id,
// ErrorDesc = $"【{BSM}】{errorDesc}",
// ErrorCode = jcErrorCode,
// ErrorLayer = errorLayer,
// PrimaryKey = "OBJECTID",
// PrimaryKeyValue = bgoid.ToTrim(),
// ErrorType = errType,
// ErrorArea = ErrorArea,
// BSM = BSM,
// PrimaryKeyValue2 = MultipartOID,
// RepairfilePath = RepairfilePath,
// Icon = string.Format("pack://siteoforigin:,,,/Images/{0}.{1}", errType.ToString(), "png")
// });
// }
// dg.ItemsSource = CheckResults;
// spCheckResult.Children.Add(exp);
// if (MaxHeight > 0)
// MaxHeight = MaxHeight - 50;
//}
//labCheckMsg.Content = Msg.TrimEnd(";");
#endregion
#region MyRegion
//spCheckResult.Children.Clear();
//foreach (var item in m_Check.CheckGroup)
//{
// Expander exp = new Expander();
// exp.Name = item.GroupName;
// exp.DataContext = item;
// exp.VerticalAlignment = VerticalAlignment.Stretch;
// exp.Style = _ExpanderStyle;
// exp.IsExpanded = true;
// exp.SetBinding(Expander.HeaderProperty, new Binding("GroupDesc"));
// ContextMenu cm = new ContextMenu();
// if (item.GroupName.StartsWith("城镇村与图斑边界套合性检查"))
// {
// MenuItem extBGTBItem = new MenuItem
// {
// Header = "提取为变更图斑,并标记203属性"
// };
// extBGTBItem.Click += ExtBGTBItem_Click;
// cm.Items.Add(extBGTBItem);
// }
// else if (item.GroupName.StartsWith("变更图斑拓扑检查"))
// {
// MenuItem mitem = new MenuItem
// {
// Header = "删除"
// };
// mitem.Click += new RoutedEventHandler(Mitem_Click);
// cm.Items.Add(mitem);
// MenuItem titem = new MenuItem
// {
// Header = "合并"
// };
// titem.Click += new RoutedEventHandler(Titem_Click);
// cm.Items.Add(titem);
// }
// MenuItem sitem = new MenuItem
// {
// Header = "例外"
// };
// sitem.Click += new RoutedEventHandler(Sitem_Click);
// cm.Items.Add(sitem);
// ListBox dg = new ListBox();
// dg.ContextMenu = cm;
// dg.PreviewMouseDoubleClick += Dg_PreviewMouseDoubleClick;//双击
// dg.BorderThickness = new Thickness(0);
// DataTemplate datatemplate = this.Resources["ItemNode"] as DataTemplate;
// dg.ItemTemplate = datatemplate;
// dg.VerticalAlignment = VerticalAlignment.Stretch;
// dg.MaxHeight = 200;
// dg.SetBinding(ListBox.ItemsSourceProperty, new Binding("CheckResults"));
// exp.Content = dg;
// spCheckResult.Children.Add(exp);
//}
#endregion
}
catch (Exception ex)
{
isFinishd = false;
MessageHelper.Show("加载界面视图时发生错误,错误信息请查看系统日志!");
LogAPI.Debug("加载界面视图时发生异常,异常信息如下:");
LogAPI.Debug(ex);
}
finally
{
if (rdbHelper != null && rdbHelper.State != System.Data.ConnectionState.Closed)
rdbHelper.DisConnect();
}
}
private void ExtBGTBItem_Click(object sender, RoutedEventArgs e)
{
try
{
List<DataCheckResult> ts = new List<DataCheckResult>();
IFeatureLayer dltbbg_Layer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
IFeatureLayer jcDLTB_Layer = MapsManager.Instance.MapService.GetFeatureLayerByName("JC_DLTB");
object obj = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedValue;
int sd = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedIndex;
if (obj != null)
{
if (!(obj is DataCheckResult result)) return;
if (!string.IsNullOrWhiteSpace(result.ErrorArea))
{
//result.ErrorArea = result.ErrorArea.Replace(".0,", ".0006,");
IGeometry geo = result.ErrorArea.ToGeometry();
if (geo != null && !geo.IsEmpty)
{
ITopologicalOperator topo = geo as ITopologicalOperator;
topo.Simplify();
IGeometry tempGeo = topo.Buffer(-0.001);
List<IFeature> bgFeatures = FeatureAPI.Identify(tempGeo, jcDLTB_Layer);
IFeatureCursor insCursor = dltbbg_Layer.FeatureClass.Insert(true);
for (int i = 0; i < bgFeatures.Count;)
{
IFeature jcFeature = bgFeatures[0];
IFeatureBuffer buf = dltbbg_Layer.FeatureClass.CreateFeatureBuffer();
buf.Shape = geo;
for (int fIdx = 0; fIdx < jcFeature.Fields.FieldCount; fIdx++)
{
IField field = jcFeature.Fields.Field[fIdx];
if (!field.Editable || field.Name.ToUpper() == "SHAPE") continue;
int bufIdx = buf.Fields.FindField(field.Name);
if (bufIdx == -1) continue;
if (field.Name.ToUpper() == "CZCSXM")
{
buf.Value[bufIdx] = result.ErrorData;
}
else
{
buf.Value[bufIdx] = jcFeature.Value[fIdx];
}
}
insCursor.InsertFeature(buf);
insCursor.Flush();
DelDataCheck(result);
((((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).ItemsSource as List<DataCheckResult>).RemoveAt(sd);
(((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).Items.Refresh();
Marshal.ReleaseComObject(jcFeature);
MessageHelper.ShowTips("提取成功!");
return;
}
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex.Message);
}
}
/// <summary>
/// 修复-例外
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Sitem_Click(object sender, RoutedEventArgs e)
{
try
{
string dbPath = System.IO.Path.Combine((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir, "DataCheckrResult.db");
object obj = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedValue;
if (obj != null)
{
DataCheckResult result = obj as DataCheckResult;
string sql = string.Format("UPDATE DataCheckResults SET ErrorType='{0}' WHERE ID='{1}'", EnumErrorType., result.ID);
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, sql, null);
result.ErrorType = EnumErrorType.;
DataCheckRuleGroup group = ((((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).Parent as Expander).DataContext as DataCheckRuleGroup;
group.UpdateInfo(null);
MessageHelper.ShowTips("标记例外成功!");
}
}
catch (Exception ex)
{
LogAPI.Debug(ex.Message);
MessageHelper.ShowTips("标记例外失败:" + ex.Message);
}
}
private void Erase_Click(object sender, RoutedEventArgs e)
{
IGeometry geometry = null;
IRDBHelper rdbHelper = null;
try
{
IFeatureLayer dltbbg_Layer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
object obj = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedValue;
if (obj != null)
{
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
DataCheckResult result = obj as DataCheckResult;
#region Topology
if (result.ErrorCode == "32074304000007")//拓扑错误
{
try
{ geometry = IPolygonExtension.ToGeometry(result.ErrorArea, true, esriGeometryType.esriGeometryPolygon); }
catch
{ geometry = IPolygonExtension.ToGeometry(result.ErrorArea, false, esriGeometryType.esriGeometryPolyline); }
if (geometry != null && geometry.IsEmpty) return;
if (result.BSM == null || result.BSM == "")
{
MessageHelper.ShowError("此条标识码是空,未能找到对应矢量图斑,请设置后重试!");
return;
}
var OriginOID = result.BSM.Split('-')[0].ToInt();
var DestinationOID = result.BSM.Split('-')[1].ToInt();
IFeature OriginFC = dltbbg_Layer.FeatureClass.GetFeature(OriginOID);
IFeature DestinationFC = dltbbg_Layer.FeatureClass.GetFeature(DestinationOID);
if (geometry.GeometryType == esriGeometryType.esriGeometryPolyline)
{
var geo = RepairGeometry(OriginFC, geometry);
IGeometry Union = FeatureAPI.Union(OriginFC.ShapeCopy, geo);
OriginFC.Shape = Union;
OriginFC.Store();
IGeometry difference = FeatureAPI.Difference(DestinationFC.ShapeCopy, Union);//擦除
DestinationFC.Shape = difference;
DestinationFC.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={result.ID}");
}
else if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon && geometry.GetEllipseArea() < 20)
{
IGeometry Union = FeatureAPI.Union(OriginFC.Shape, geometry);
List<IGeometry> geoList = FeatureAPI.DissolveGeometryByRing(Union);
if (geoList.Count > 1)
{
}
OriginFC.Shape = Union;
OriginFC.Store();
IGeometry difference = FeatureAPI.Difference(DestinationFC.Shape, Union);//擦除
geoList = FeatureAPI.DissolveGeometryByRing(difference);
if (geoList.Count > 1)
{
}
DestinationFC.Shape = difference;
DestinationFC.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
}
else if (result.ErrorCode == "32074304000006")//变更图斑与基础库联合出的错误
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(TempfilePath, WorkspaceTypeEnum.GDBFile);
IFeatureClassAPI featureClassAPI = workspaceAPI.OpenFeatureClass("Multipart");
geometry = featureClassAPI.GetFeature(result.PrimaryKeyValue2.ToInt()).ShapeCopy;
if (geometry != null && geometry.IsEmpty) return;
if (result.PrimaryKeyValue == "-1")//OBJECTID 为-1 的 需要与变更图斑合并
{
var togologic = geometry as ITopologicalOperator;
togologic.Simplify();
List<IFeature> bgFeatures = FeatureAPI.Identify(geometry, dltbbg_Layer);
if (bgFeatures.Count == 1)
{
IGeometry geometrys = FeatureAPI.Union(bgFeatures[0].ShapeCopy, geometry);
if (geometrys != null && !geometrys.IsEmpty)
{
bgFeatures[0].Shape = geometrys;
bgFeatures[0].Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
}
else if (bgFeatures.Count > 1)
{
//图形相邻与共边最长的图斑合并
IFeature UnionFeature = null;
var Unionlength = 0.00;
foreach (IFeature ifeature in bgFeatures)
{
var length = FeatureAPI.LengthOfSide(geometry, ifeature.Shape);
if (length > Unionlength)
{
Unionlength = length;
UnionFeature = ifeature;
}
}
if (UnionFeature != null)
{
IGeometry geometrys = FeatureAPI.Union(UnionFeature.ShapeCopy, geometry);
if (geometrys != null && !geometrys.IsEmpty)
{
UnionFeature.Shape = geometrys;
UnionFeature.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
}
}
}
else //OBJECTID >-1的 需要将碎图斑擦除
{
IFeature OriginFC = dltbbg_Layer.FeatureClass.GetFeature(result.PrimaryKeyValue.ToInt());
List<IFeature> bgFeatures = FeatureAPI.Identify(geometry, dltbbg_Layer);
if (bgFeatures.Count == 1)
{
OriginFC.Shape = FeatureAPI.Difference(OriginFC.ShapeCopy, geometry);//擦除
OriginFC.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
else if (bgFeatures.Count > 1)
{
//图形相邻与共边最长的图斑合并
IFeature UnionFeature = null;
var Unionlength = 0.00;
foreach (IFeature ifeature in bgFeatures)
{
if (ifeature.OID == result.PrimaryKeyValue.ToInt()) continue;
var length = FeatureAPI.LengthOfSide(geometry, ifeature.Shape);
if (length > Unionlength)
{
Unionlength = length;
UnionFeature = ifeature;
}
}
if (UnionFeature != null)
{
//IGeometry geometrys = FeatureAPI.Union(UnionFeature.ShapeCopy, geometry);
//if (geometrys != null && !geometrys.IsEmpty)
//{
OriginFC.Shape = FeatureAPI.Difference(OriginFC.ShapeCopy, geometry);//擦除
OriginFC.Store();
//UnionFeature.Shape = geometrys;
//UnionFeature.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
//}
}
}
}
}
#endregion
}
}
catch (Exception)
{ }
InitView(out bool isFinishd);
//try
//{
// string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
// object obj = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedValue;
// if (obj != null)
// {
// DataCheckResult result = obj as DataCheckResult;
// string sql = string.Format("UPDATE DataCheckResults SET ErrorType='{0}' WHERE ID='{1}'", EnumErrorType.例外, result.ID);
// SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, sql, null);
// MessageHelper.ShowTips("标记例外成功!");
// }
//}
//catch (Exception ex)
//{
// LogAPI.Debug(ex.Message);
// MessageHelper.ShowTips("属性修复失败:" + ex.Message);
//}
}
/// <summary>
/// 修复单条
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RepairItem_Click(object sender, RoutedEventArgs e)
{
try
{
object obj = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedValue;
int sum = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).Items.Count;
int sd = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedIndex;
if (obj == null) return;
if (!(obj is DataCheckResult result)) return;
string errorCode = result.ErrorCode.ToString();
string errorLayerEngish = result.ErrorLayer.ToString();
string errorBSM = result.BSM.ToString();
string errorDesc = result.ErrorDesc.ToString();
string objectId = result.ID.ToString();
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
DataTable dicDt = rdbHelper.ExecuteDatatable("CheckingRule", string.Format($"SELECT * from CheckingRule where RuleCode = '{errorCode}' "), true);
if (dicDt == null) return;
foreach (DataRow row in dicDt.Rows)
{
string repairSql = row["RepairSQL"].ToString();
if (string.IsNullOrWhiteSpace(repairSql) || string.IsNullOrEmpty(repairSql)) continue;
repairSql = string.Format(repairSql, errorLayerEngish, errorBSM, (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).CODE);
IFeatureLayer errorFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(errorLayerEngish);
(errorFeatureLayer as FeatureClass).Workspace.ExecuteSQL(repairSql);
DelDataCheck(result);
result.ErrorType = EnumErrorType.;
((((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).ItemsSource as List<DataCheckResult>).RemoveAt(sd);
(((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).Items.Refresh();
rdbHelper.ExecuteSQL($"delete from DataCheckResults where ID = '{objectId}' ");
}
}
catch (Exception ex)
{
LogAPI.Debug(ex.Message);
MessageHelper.ShowTips("修复失败,请查看日志!");
}
}
/// <summary>
/// 修复-合并
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Merge_Click(object sender, RoutedEventArgs e)
{
V_Repair.FrmBGFeaterMerge bGFeaterMerge = null;
IRDBHelper rdbHelper = null;
try
{
IFeatureLayer dltbbg_Layer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
object obj = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedValue;
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
if (obj != null)
{
DataCheckResult result = obj as DataCheckResult;
if (result.BSM.Contains("-"))//相交图形合并
{
var OriginOID = result.BSM.Split('-')[0].ToInt();
var DestinationOID = result.BSM.Split('-')[1].ToInt();
IFeature OriginFC = dltbbg_Layer.FeatureClass.GetFeature(OriginOID);
IFeature DestinationFC = dltbbg_Layer.FeatureClass.GetFeature(DestinationOID);
List<IFeature> bgFeatures = new List<IFeature>();
bgFeatures.Add(OriginFC);
bgFeatures.Add(DestinationFC);
bGFeaterMerge = new V_Repair.FrmBGFeaterMerge();
bGFeaterMerge.GetViewData(bgFeatures, result);
bGFeaterMerge.WindowStartupLocation = WindowStartupLocation.CenterScreen;
bGFeaterMerge.Closed += (s1, e1) =>
{
if (bGFeaterMerge.IsMerge)//是否合并成功
{
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={result.ID}");
}
};
bGFeaterMerge.ShowInMainForm(false);
//if (MessageHelper.ShowYesNoAndTips($"确定变更图斑【OBJECTID={OriginOID}】与变更图斑【OBJECTID={DestinationOID}】合并?") == System.Windows.Forms.DialogResult.Yes)
//{
// IGeometry geometrys = FeatureAPI.Union(OriginFC.ShapeCopy, DestinationFC.ShapeCopy);
// OriginFC.Shape = geometrys;
// OriginFC.Store();
// ITable dltbbg = dltbbg_Layer.FeatureClass as ITable;
// dltbbg.DeleteSearchedRows(new QueryFilterClass() { WhereClause = $"OBJECTID ={DestinationOID}" });
// rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={result.ID}");
//}
}
else if (!string.IsNullOrWhiteSpace(result.ErrorArea))
{
IWorkspaceAPI wsAPI = new WorkspaceAPI(result.RepairfilePath, WorkspaceTypeEnum.GDBFile);
IFeatureClassAPI featureClassAPI = wsAPI.OpenFeatureClass("Multipart");
var MultipartOID = result.PrimaryKeyValue2.ToInt();
IFeature f = featureClassAPI.GetFeature(MultipartOID);
IGeometry geo = f.ShapeCopy;
if (geo != null && !geo.IsEmpty)
{
List<IFeature> bgFeatures = FeatureAPI.Identify(geo, dltbbg_Layer);
if (bgFeatures.Count > 0)
{
bGFeaterMerge = new V_Repair.FrmBGFeaterMerge();
bGFeaterMerge.GetViewData(bgFeatures, result);
bGFeaterMerge.WindowStartupLocation = WindowStartupLocation.CenterScreen;
bGFeaterMerge.ShowInMainForm(false);
return;
}
}
//if (bgFeatures.Count == 1)
//{
// if (FeatureAPI.IsAdjacent(bgFeatures[0].ShapeCopy, geo) && !FeatureAPI.IsContains(bgFeatures[0].ShapeCopy, geo))
// {
// if (MessageHelper.ShowYesNoAndTips(string.Format("确定变更图斑【OBJECTID={0}】与零碎图斑合并?", bgFeatures[0].OID)) == System.Windows.Forms.DialogResult.Yes)
// {
// int FOID = bgFeatures[0].OID;
// IGeometry geometrys = FeatureAPI.Union(bgFeatures[0].Shape, geo);
// bgFeatures[0].Shape = geometrys;
// bgFeatures[0].Store();
// //刷新数据
// //((listBoxItem as ListBox).ItemsSource as List<DataCheckResult>).RemoveAt(sd);
// (listBoxItem as ListBox).Items.Refresh();
// DelDataCheck(result);//删除数据
// result.ErrorType = EnumErrorType.已修复;
// //刷新组头部信息
// DataCheckRuleGroup group = (assa as Expander).DataContext as DataCheckRuleGroup;
// group.UpdateInfo(null);
// MessageHelper.ShowTips(string.Format("变更图斑【OBJECTID={0}】与零碎图斑合并成功!", FOID));
// }
// }
// else
// {
// MessageHelper.ShowTips("合并失败,选择的图斑可能为不相邻或包含关系!");
// }
//}
//else
//{
// for (int i = 0; i < bgFeatures.Count; i++)
// {
// if (!FeatureAPI.IsContains(bgFeatures[i].ShapeCopy, geo) && FeatureAPI.IsAdjacent(bgFeatures[i].ShapeCopy, geo))
// {
// if (bGFeaterMerge == null)
// {
// bGFeaterMerge = new V_Repair.FrmBGFeaterMerge();
// bGFeaterMerge.GetViewData(bgFeatures, result);
// bGFeaterMerge.WindowStartupLocation = WindowStartupLocation.CenterScreen;
// bGFeaterMerge.Closed += (s1, e1) =>
// {
// if (bGFeaterMerge.IsMerge)//是否合并成功
// {
// //((listBoxItem as ListBox).ItemsSource as List<DataCheckResult>).RemoveAt(sd);
// (listBoxItem as ListBox).Items.Refresh();
// DelDataCheck(result);//删除数据
// result.ErrorType = EnumErrorType.已修复;
// DataCheckRuleGroup group = ((listBoxItem as ListBox).Parent as Expander).DataContext as DataCheckRuleGroup;
// group.UpdateInfo(null);
// }
// };
// bGFeaterMerge.ShowInMainForm(false);
// return;
// }
// }
// }
//}
//}
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex.Message);
MessageHelper.ShowTips("合并图斑失败,请查看日志!");
}
}
#region 删除
private void Delete_Click(object sender, RoutedEventArgs e)
{
IRDBHelper rdbHelper = null;
try
{
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
IFeatureLayer dltbbg_Layer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
object obj = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedValue;
int sd = (((sender as MenuItem).Parent as ContextMenu).PlacementTarget as ListBox).SelectedIndex;
if (obj != null)
{
DataCheckResult result = obj as DataCheckResult;
if (result.BSM == null || result.BSM == "")
{
MessageHelper.ShowError("此条标识码是空,未能找到对应矢量图斑,请设置后重试!");
return;
}
var OriginOID = result.BSM.Split('-')[0].ToInt();
var DestinationOID = result.BSM.Split('-')[1].ToInt();
if (MessageHelper.ShowYesNoAndTips(string.Format("确认删除变更图斑【OBJECTID={0}】?", DestinationOID)) == System.Windows.Forms.DialogResult.Yes)
{
ITable dltbbg = dltbbg_Layer.FeatureClass as ITable;
dltbbg.DeleteSearchedRows(new QueryFilterClass() { WhereClause = $"OBJECTID ={DestinationOID}" });
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={result.ID}");
InitView(out bool isFinishd);
}
}
}
catch (Exception ex)
{
LogAPI.Debug($"删除图斑失败:{ex.Message}");
LogAPI.Debug(ex);
MessageHelper.ShowTips("删除图斑失败,请查看日志!");
}
}
#endregion
/// <summary>
/// 删除擦除后数据
/// </summary>
/// <param name="result"></param>
public void DelDataCheck(DataCheckResult result)
{
try
{
string dbPath = System.IO.Path.Combine((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir, "DataCheckrResult.db");
string sql = string.Format("update DataCheckResults set ErrorType='已修复' where ID = '{0}'", result.ID);
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, sql, null);
}
catch (Exception ex)
{
LogAPI.Debug("删除数据失败:" + ex.Message);
}
}
/// <summary>
/// 双击高亮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Dg_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
object obj = (sender as ListBox).SelectedValue;
if (obj != null)
{
DataCheckResult result = obj as DataCheckResult;
if (result == null) return;
if (result.BSM.Contains("-"))
{
IFeature feature = GetErrorFeatures(result.RepairfilePath, result.BSM.Split('-')[0].ToInt(), result.BSM.Split('-')[1].ToInt());
{
if (feature != null)
{
IGeometry geometry = feature.ShapeCopy;
if (geometry != null && !geometry.IsEmpty)
{
MapsManager.Instance.MapService.DrawGraph(geometry, true);
MapsManager.Instance.MapService.Zoom(geometry);
return;
}
}
}
}
else if (!string.IsNullOrEmpty(result.PrimaryKeyValue2))
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(result.RepairfilePath, WorkspaceTypeEnum.GDBFile);
IFeatureClassAPI featureClassAPI = workspaceAPI.OpenFeatureClass("Multipart");
IGeometry geometry = featureClassAPI.GetFeature(result.PrimaryKeyValue2.ToInt()).ShapeCopy;
if (geometry != null && !geometry.IsEmpty)
{
MapsManager.Instance.MapService.DrawGraph(geometry, true);
MapsManager.Instance.MapService.Zoom(geometry);
return;
}
}
else if (!string.IsNullOrWhiteSpace(result.ErrorArea))
{
IGeometry geometry = null;
try
{ geometry = IPolygonExtension.ToGeometry(result.ErrorArea, true, esriGeometryType.esriGeometryPolygon); }
catch
{ geometry = IPolygonExtension.ToGeometry(result.ErrorArea, false, esriGeometryType.esriGeometryPolyline); }
if (geometry != null && !geometry.IsEmpty)
{
MapsManager.Instance.MapService.DrawGraph(geometry, true);
MapsManager.Instance.MapService.Zoom(geometry);
}
}
else
{
if (!string.IsNullOrWhiteSpace(result.BSM) && !string.IsNullOrWhiteSpace(result.ErrorLayer))
{
var layer = MapsManager.Instance.MapService.GetFeatureClassByName(result.ErrorLayer);
if (layer != null && layer.FeatureCount(null) > 0)
{
IFeatureCursor pCursor = null;
pCursor = layer.Search(new QueryFilterClass() { WhereClause = $"BSM='{result.BSM}' " }, true);
IFeature feature = pCursor.NextFeature();
if (feature != null)
MapsManager.Instance.MapService.SelectFeature(result.ErrorLayer, feature.OID.ToString());
}
}
else if (string.IsNullOrWhiteSpace(result.ErrorLayer) || string.IsNullOrWhiteSpace(result.PrimaryKey) || string.IsNullOrWhiteSpace(result.PrimaryKeyValue)) return;
else if (result.PrimaryKey.ToUpper() == "OBJECTID")
{
MapsManager.Instance.MapService.SelectFeature(result.ErrorLayer, result.PrimaryKeyValue);
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug("Dg_PreviewMouseDoubleClick错误:" + ex.Message);
}
}
public IFeature GetErrorFeatures(string RepairfilePath, int OriginOID, int DestinationOID)
{
IFeature pFeature = null;
try
{
string fcName = "DLTBBG";
string topoName = "TopologyCheck_DLTBBG";
if (_CheckName == "基础图斑")
{
fcName = "DLTB";
topoName = "TopologyCheck_DLTB";
}
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(RepairfilePath, WorkspaceTypeEnum.GDBFile);
var api = workspaceAPI.OpenFeatureClass(fcName);
IFeatureDataset featureDataset = api.FeatureClass.FeatureDataset;
ITopologyContainer topologyContainer = (ITopologyContainer)featureDataset;
ITopology topology = topologyContainer.get_TopologyByName(topoName);
IErrorFeatureContainer errorFeatureContainer = (IErrorFeatureContainer)topology;
IGeoDataset geoDataset = (IGeoDataset)topology;
ISpatialReference spatialReference = geoDataset.SpatialReference;
ITopologyRuleContainer topologyRuleContainer = (ITopologyRuleContainer)topology;
bool bTopExists = (featureDataset.Workspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTTopology, topoName);
if (bTopExists)
{
var topologyErrorFeature = errorFeatureContainer.get_ErrorFeature(spatialReference, esriTopologyRuleType.esriTRTAreaNoOverlap, esriGeometryType.esriGeometryPolygon, api.FeatureClass.ObjectClassID, OriginOID, api.FeatureClass.ObjectClassID, DestinationOID);
if (topologyErrorFeature == null)
topologyErrorFeature = errorFeatureContainer.get_ErrorFeature(spatialReference, esriTopologyRuleType.esriTRTAreaNoOverlap, esriGeometryType.esriGeometryPolyline, api.FeatureClass.ObjectClassID, OriginOID, api.FeatureClass.ObjectClassID, DestinationOID);
pFeature = topologyErrorFeature as IFeature;
}
}
catch (Exception ex)
{
}
return pFeature;
}
public IFeature GetErrorFeatures(string RepairfilePath, int OriginOID, int DestinationOID, string fcName, string topoName)
{
IFeature pFeature = null;
try
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(RepairfilePath, WorkspaceTypeEnum.GDBFile);
var api = workspaceAPI.OpenFeatureClass(fcName);
IFeatureDataset featureDataset = api.FeatureClass.FeatureDataset;
ITopologyContainer topologyContainer = (ITopologyContainer)featureDataset;
ITopology topology = topologyContainer.get_TopologyByName(topoName);
IErrorFeatureContainer errorFeatureContainer = (IErrorFeatureContainer)topology;
IGeoDataset geoDataset = (IGeoDataset)topology;
ISpatialReference spatialReference = geoDataset.SpatialReference;
ITopologyRuleContainer topologyRuleContainer = (ITopologyRuleContainer)topology;
bool bTopExists = (featureDataset.Workspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTTopology, topoName);
if (bTopExists)
{
var topologyErrorFeature = errorFeatureContainer.get_ErrorFeature(spatialReference, esriTopologyRuleType.esriTRTAreaNoOverlap, esriGeometryType.esriGeometryPolygon, api.FeatureClass.ObjectClassID, OriginOID, api.FeatureClass.ObjectClassID, DestinationOID);
if (topologyErrorFeature == null)
topologyErrorFeature = errorFeatureContainer.get_ErrorFeature(spatialReference, esriTopologyRuleType.esriTRTAreaNoOverlap, esriGeometryType.esriGeometryPolyline, api.FeatureClass.ObjectClassID, OriginOID, api.FeatureClass.ObjectClassID, DestinationOID);
pFeature = topologyErrorFeature as IFeature;
}
}
catch (Exception ex)
{
}
return pFeature;
}
public bool IsShowInMap { get; set; }
public Guid ID { get; set; }
public DockStyle DockAreas { get; set; }
public System.Drawing.Size FloatSize { get; set; }
public int DockWidth { get; set; }
public int DockHeight { get; set; }
public DockStyle DefaultArea { get; set; }
public bool ShowCloseButton { get; set; }
public bool ShowAutoHideButton { get; set; }
public string Title { get; set; }
public IDataCheck IDataCheck { get; set; }
public List<IDataCheck> IdataChecks { get; set; }
public event EventHandler CloseViewHandler;
public void ShowPanel()
{
Platform.Instance.OpenView(this, false);
if (MapsManager.Instance.MapService != null)
{
MapsManager.Instance.MapService.ProjectClosed += (sender, e) =>
{
ClosePanel();
};
}
}
public void ClosePanel()
{
Platform.Instance.CloseView(this);
}
public void ClosePanelInvoke()
{
CloseViewHandler?.Invoke(this, null);
}
private string CreateTempDB(string mPrjDbPath, string pTargetFolder)
{
string result = System.IO.Path.Combine(pTargetFolder, "Temp" + ".sqlite");
try
{
//string dbPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Temp" + ".db");
string dbPath = mPrjDbPath;
if (!Directory.Exists(pTargetFolder))
Directory.CreateDirectory(pTargetFolder);
//try
//{
// DelectDirect(pTargetFolder);
//}
//catch
//{
// //删除临时数据异常 不做处理
//}
if (File.Exists(dbPath))
{
File.Copy(dbPath, result, true);
}
else
{
Console.WriteLine(string.Format("文件{0}不存在!", dbPath));
}
//result;// System.IO.Path.Combine(path, "TempGDB.gdb");//临时数据存放路径
}
catch (Exception ex)
{
Console.WriteLine("创建临时数据库失败!" + ex.Message);
throw ex;
}
return result;
}
List<string> sqlList = null;
private void BtnSetCheckState_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
ExtensionShowWindow.MainWinForm.Enabled = false;
IRDBHelper rdbHelper = null;
IRDBHelper errdbHelper = null;
IFeatureCursor cursur = null;
IFeature f = null;
try
{
this.ShowLoading($"正在进行【{_CheckName}】数据检查...", 0, 0);
ProjectInfo prjInfo = MapsManager.Instance.CurrProjectInfo as ProjectInfo;
IDGParameter Parm = new IDGParameter();
Parm.StrProjInfo = System.IO.Path.Combine(prjInfo.ProjDir, prjInfo.ProjName + prjInfo.ProjSuffix);
string mOutLocation = string.Empty;
FileInfo fInfo = null;
if (_CheckName == "变更图斑")
{
Parm.CheckType = "BGDB";
if (!Directory.Exists(prjInfo.BGDatabase) && !File.Exists(prjInfo.BGDatabase))
{
Console.WriteLine("参数路径不存在!");
MessageHelper.ShowWarning("参数路径不存在!请先创建变更数据库!");
return;
}
fInfo = new FileInfo(prjInfo.BGDatabase);
}
else if (_CheckName == "增量图斑")
{
Parm.CheckType = "ZLDB";
if (!Directory.Exists(prjInfo.ZLDatabase) && !File.Exists(prjInfo.ZLDatabase))
{
Console.WriteLine("参数路径不存在!");
MessageHelper.ShowWarning("参数路径不存在!请先创建增量数据库!");
return;
}
fInfo = new FileInfo(prjInfo.ZLDatabase);
}
string dbPrjPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
#region 将图层数据写入到db中
rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPrjPath, DatabaseType.SQLite);
string Sqlwhere = " where 1=2 ";
if (_CheckName == "变更图斑")
Sqlwhere = " where BGIsSelect=true and BGLayerName NOTNULL ";
else if (_CheckName == "增量图斑")
Sqlwhere = " where ZLIsSelect=true AND BGLayerName ISNULL AND RuleType='图形拓扑'";
else if (_CheckName == "基础图斑")
Sqlwhere = " where ImplementSQL='Topology_JCDLTB' AND RuleType='图形拓扑' ";
DataTable dataTable = rdbHelper.ExecuteDatatable("tab", $" SELECT * from CheckingRule {Sqlwhere} ", true);
if (dataTable == null || dataTable.Rows.Count == 0)
{
MessageHelper.ShowTips("至少要在系统设置中,选择图形括扑中的一条!");
return;
}
CopyTable(rdbHelper, dbPrjPath, dataTable);
#endregion
if (dataTable.Rows.Count > 0)
rdbHelper.ExecuteSQL("delete from DataCheckResults ");
if (_CheckName != "基础图斑" && _CheckName != "增量图斑")
{
this.UpdateMsg($"正在进行【{_CheckName}】数据GP检查...");
mOutLocation = System.IO.Path.Combine(fInfo.DirectoryName, "DataCheck", Parm.CheckType);
if (Directory.Exists(mOutLocation))
{
DelectDirect(mOutLocation);
}
else
{
Directory.CreateDirectory(mOutLocation);
}
StopProcess("KDataCheck");
StopProcess("GPHelper");
mOutLocation = System.IO.Path.Combine(mOutLocation, DateTime.Now.ToString("yyyyMMddHHmmssfff"));
string tempdbPath = CreateTempDB(dbPrjPath, mOutLocation);
Parm.OutLocation = mOutLocation;
Parm.TempdbPath = tempdbPath;
Parm.PrjDbPath = dbPrjPath;
ProcesHelper.Instance.ExeGPForProces(Parm);
}
sqlList = new List<string>();
string LayerName = string.Empty; //变更图斑图层名称
string Alias = string.Empty;//别名
List<string> list = new List<string>();
Dictionary<string, List<ThreadParam>> ThreadParamDic = new Dictionary<string, List<ThreadParam>>();
List<string> errorList = new List<string>();
var ImplementSQL = string.Empty;
var RuleCode = string.Empty;
var RuleType = string.Empty;
var RuleName = string.Empty;
DataTable dt = null;
string sqlStr = null;
int i = 0;
this.UpdateMsg($"正在进行【{_CheckName}】数据逻辑检查...");
foreach (DataRow row in dataTable.Rows)
{
if (sqlList.Count > 10000)
{
InsertSQLiteData(dbPrjPath, sqlList);
sqlList.Clear();
}
if (errorList != null)
errorList.Clear();
ImplementSQL = row["ImplementSQL"].ToTrim();//执行语句
LogAPI.Debug(ImplementSQL);
if (_CheckName != "基础图斑" && ImplementSQL == "Topology_JCDLTB") continue;
RuleCode = row["RuleCode"].ToTrim();//规则编码
RuleType = row["RuleType"].ToTrim();//规则类别
RuleName = row["RuleName"].ToTrim();//规则名称
try
{
if (_CheckName == "变更图斑" || _CheckName == "基础图斑")
{
LayerName = row["BGLayerName"].ToTrim().Split('_')[0];
Alias = row["BGLayerName"].ToTrim().Split('_')[1];
}
else if (_CheckName == "增量图斑")
{
LayerName = row["ZLLayerName"].ToTrim().Split('_')[0];
Alias = row["ZLLayerName"].ToTrim().Split('_')[1];
}
switch (ImplementSQL)
{
case "SameGraphic"://无变化和灭失要素的图形与基础库对应图形一致
GetJCLayerName(LayerName, out string JCLayerName);
errorList = SameGraphic(LayerName, JCLayerName, RuleCode, RuleName, mOutLocation);
if (errorList != null)
sqlList.AddRange(errorList);
break;
case "SameBSM"://无变化、灭失的标识码与基础库界线标识码一致
GetJCLayerName(LayerName, out string JcLayerName);
errorList = SameBSM(LayerName, JcLayerName, RuleCode, RuleName, mOutLocation);
if (errorList != null)
sqlList.AddRange(errorList);
break;
case "LMFWGXKD"://路面范围更新层KD取值大于等于0,且不能为空值(允许新增道路不填宽度)
errorList = JudgeNewRoad(LayerName, "LMFW", RuleCode, RuleName, RuleType);
if (errorList != null)
sqlList.AddRange(errorList);
break;
case "SameGDPDJB"://地类图斑更新层耕地图斑GDPDJB字段取值与对应 坡度图更新层 或 坡度图层 PDJB字段取值一致
errorList = SameGDPDJB(LayerName, RuleName.Contains("坡度图更新层") ? "PDTGX" : "PDT", RuleCode, RuleName, RuleType);
if (errorList != null)
sqlList.AddRange(errorList);
break;
case "Topology_JCDLTB"://基础地类图斑重叠,缝隙
errorList = GetTopology_DLTB(RuleCode);
if (errorList != null)
sqlList.AddRange(errorList);
break;
case "Topology"://增量图斑重叠
errorList = GetTopology_DLTBBG(RuleCode, LayerName);
if (errorList != null)
sqlList.AddRange(errorList);
break;
case "LineNoDangles"://悬挂线
errorList = LineNoDangles(RuleCode, LayerName, Alias);
if (errorList != null)
sqlList.AddRange(errorList);
break;
default:
#region 源代码
if (string.IsNullOrEmpty(ImplementSQL) || !ImplementSQL.ToLower().Contains("select")) continue;
IFeatureClass featureClass = MapsManager.Instance.MapService.GetFeatureClassByName(LayerName);
if (featureClass == null) continue;
errdbHelper = RDBFactory.CreateDbHelper("Data Source=" + Parm.PrjDbPath, DatabaseType.SQLite);
dt = errdbHelper.ExecuteDatatable("tab", string.Format(ImplementSQL, LayerName, Alias, RuleCode, RuleType, prjInfo.CODE), true);
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow item in dt.Rows)
{
if (dt.Columns.Contains("MC"))
{
if (string.IsNullOrEmpty(item["MC"].ToString())) continue;
if (Regex.IsMatch(item["MC"].ToString(), @"^[0-9]+$")
|| Regex.IsMatch(item["MC"].ToString().Substring(0, 1), @"^[A-Za-z]+$")
|| Regex.IsMatch(item["MC"].ToString(), "[^0-9a-zA-Z\u4e00-\u9fa5-_()()]")
)
{
if (item["BSM"] == null || string.IsNullOrEmpty(item["BSM"].ToString()))
sqlStr = $" (BSM is null or BSM = '' or BSM = ' ') ";
else
sqlStr = $" BSM = '{item["BSM"]}' ";
cursur = featureClass.Search(new QueryFilterClass() { WhereClause = sqlStr }, true);
while ((f = cursur.NextFeature()) != null)
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}');", item["ObjectID"], item["BSM"], item["ErrorLayer"], item["ErrorCode"], item["ErrorName"], item["RuleType"], f.Shape.ToJson()));
}
}
continue;
}
if (item["BSM"] == null || string.IsNullOrEmpty(item["BSM"].ToString()))
sqlStr = $" (BSM is null or BSM = '' or BSM = ' ') ";
else
sqlStr = $" BSM = '{item["BSM"]}' ";
cursur = featureClass.Search(new QueryFilterClass() { WhereClause = sqlStr }, true);
string CheckFeatureClassName = featureClass.AliasName;
while ((f = cursur.NextFeature()) != null)
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}');", item["ObjectID"], item["BSM"], item["ErrorLayer"], item["ErrorCode"], item["ErrorName"], item["RuleType"]));
}
}
}
#endregion
break;
}
}
catch (Exception ex)
{
LogAPI.Debug($"错误代码【{RuleCode}】对应的查询语句错误:[{ex.Message}]");
continue;
}
}
this.UpdateMsg($"正在进行【{_CheckName}】数据检查...");
InsertSQLiteData(dbPrjPath, sqlList);
this.UpdateMsg($"正在进行【{_CheckName}】数据检查...");
InitView(out bool isFinishd);
this.CloseLoading();
if (isFinishd)
{
MapRefreshView.OnCreate(m_hookHelper.Hook);
MapRefreshView.OnClick();
MessageHelper.ShowTips("数据检查完成。");
}
}
catch (Exception ex)
{
MessageHelper.ShowError("数据检查时发生异常,详情请查看系统日志!");
LogAPI.Debug("数据检查时发生异常,异常信息如下:");
LogAPI.Debug(ex);
}
finally
{
this.CloseLoading();
(sender as Button).IsEnabled = true;
ExtensionShowWindow.MainWinForm.Enabled = true;
if (rdbHelper != null && rdbHelper.State != ConnectionState.Closed)
rdbHelper.DisConnect();
if (errdbHelper != null && errdbHelper.State != ConnectionState.Closed)
errdbHelper.DisConnect();
if (cursur != null)
Marshal.ReleaseComObject(cursur);
if (f != null)
Marshal.ReleaseComObject(f);
StopProcess("KDataCheck");
}
}
private void CopyTable(IRDBHelper rdbHelper, string dbPrjPath, DataTable dataTable)
{
IFeatureClass DLTBBG = null;
IFeatureClass CCWJQGX = null;
IWorkspaceFactory pOutWorkFactory = new SqlWorkspaceFactoryClass();
try
{
IWorkspace pOutWork = pOutWorkFactory.OpenFromFile(dbPrjPath, 0);
if (_CheckName == "变更图斑")
{
#region 变更图斑
DLTBBG = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBBG");
//JudgeNullBSMAssign(DLTBBG);
if (DLTBBG != null)
{
Geoprocessor gp = new Geoprocessor();
gp.OverwriteOutput = true;
CalculateField calc = new CalculateField();
calc.in_table = DLTBBG;
calc.field = "BSM";
calc.expression = "!OBJECTID!";
calc.expression_type = "PYTHON";
gp.Execute(calc, null);
rdbHelper.ExecuteSQL(" Drop Table DLTBBG");
TableToTable((DLTBBG as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "DLTBBG");
//CopyTableToDB((DLTBBG as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "DLTBBG");
}
#endregion
}
else if (_CheckName == "增量图斑")
{
#region 拆除未尽区更新层
if (dataTable.Select(" LayerName='拆除未尽区更新层' ").Length > 0)
{
CCWJQGX = MapsManager.Instance.MapService.GetFeatureClassByName("CCWJQGX");
rdbHelper.ExecuteSQL(" Drop Table CCWJQGX");
if (CCWJQGX != null && CCWJQGX.FeatureCount(null) != 0)
{
TableToTable((CCWJQGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "CCWJQGX");
//CopyTableToDB((CCWJQGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "CCWJQGX");
}
}
#endregion
#region 城镇村等用地更新层
if (dataTable.Select(" LayerName='城镇村等用地更新层' ").Length > 0)
{
IFeatureClass CZCDYDGX = MapsManager.Instance.MapService.GetFeatureClassByName("CZCDYDGX");
rdbHelper.ExecuteSQL(" Drop Table CZCDYDGX");
if (CZCDYDGX != null && CZCDYDGX.FeatureCount(null) != 0)
{
TableToTable((CZCDYDGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "CZCDYDGX");
//CopyTableToDB((CZCDYDGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "CZCDYDGX");
}
}
#endregion
#region 城镇村等用地更新过程层
if (dataTable.Select(" LayerName='城镇村等用地更新过程层' ").Length > 0)
{
IFeatureClass CZCDYDGXGC = MapsManager.Instance.MapService.GetFeatureClassByName("CZCDYDGXGC");
rdbHelper.ExecuteSQL(" Drop Table CZCDYDGXGC");
if (CZCDYDGXGC != null && CZCDYDGXGC.FeatureCount(null) != 0)
{
TableToTable((CZCDYDGXGC as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "CZCDYDGXGC");
//CopyTableToDB((CZCDYDGXGC as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "CZCDYDGXGC");
}
}
#endregion
#region 村级调查区更新层
if (dataTable.Select(" LayerName='村级调查区更新层' ").Length > 0)
{
IFeatureClass CJDCQGX = MapsManager.Instance.MapService.GetFeatureClassByName("CJDCQGX");
rdbHelper.ExecuteSQL(" Drop Table CJDCQGX");
if (CJDCQGX != null && CJDCQGX.FeatureCount(null) != 0)
{
TableToTable((CJDCQGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "CJDCQGX");
//CopyTableToDB((CJDCQGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "CJDCQGX");
}
}
#endregion
#region 村级调查区更新过程层
if (dataTable.Select(" LayerName='村级调查区更新过程层' ").Length > 0)
{
IFeatureClass CJDCQGXGC = MapsManager.Instance.MapService.GetFeatureClassByName("CJDCQGXGC");
rdbHelper.ExecuteSQL(" Drop Table CJDCQGXGC");
if (CJDCQGXGC != null && CJDCQGXGC.FeatureCount(null) != 0)
{
TableToTable((CJDCQGXGC as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "CJDCQGXGC");
//CopyTableToDB((CJDCQGXGC as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "CJDCQGXGC");
}
}
#endregion
#region 村级调查区界线更新层
if (dataTable.Select(" LayerName='村级调查区界线更新层' ").Length > 0)
{
IFeatureClass CJDCQJXGX = MapsManager.Instance.MapService.GetFeatureClassByName("CJDCQJXGX");
rdbHelper.ExecuteSQL(" Drop Table CJDCQJXGX");
if (CJDCQJXGX != null && CJDCQJXGX.FeatureCount(null) != 0)
{
TableToTable((CJDCQJXGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "CJDCQJXGX");
//CopyTableToDB((CJDCQJXGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "CJDCQJXGX");
}
if (dataTable.Select(" Requirement like '%基础库%' ").Length > 0)
{
IFeatureClass CJDCQJX = MapsManager.Instance.MapService.GetFeatureClassByName("CJDCQJX");
rdbHelper.ExecuteSQL(" Drop Table CJDCQJX");
if (CJDCQJX != null && CJDCQJX.FeatureCount(null) != 0)
{
TableToTable((CJDCQJX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "CJDCQJX");
//CopyTableToDB((CJDCQJX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "CJDCQJX");
}
}
}
#endregion
#region 地类图斑更新层
if (dataTable.Select(" LayerName='地类图斑更新层' ").Length > 0)
{
IFeatureClass DLTBGX = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGX");
rdbHelper.ExecuteSQL(" Drop Table DLTBGX");
if (DLTBGX != null && DLTBGX.FeatureCount(null) != 0)
{
TableToTable((DLTBGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "DLTBGX");
//CopyTableToDB((DLTBGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "DLTBGX");
}
if (dataTable.Select(" RuleName like '%坡度图更新层%' ").Length > 0)
{
IFeatureClass PDTGX = MapsManager.Instance.MapService.GetFeatureClassByName("PDTGX");
rdbHelper.ExecuteSQL(" Drop Table PDTGX");
if (PDTGX != null && PDTGX.FeatureCount(null) != 0)
{
TableToTable((PDTGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "PDTGX");
//CopyTableToDB((PDTGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "PDTGX");
}
}
if (dataTable.Select(" RuleName like '%坡度图层%' ").Length > 0)
{
IFeatureClass PDT = MapsManager.Instance.MapService.GetFeatureClassByName("PDT");
rdbHelper.ExecuteSQL(" Drop Table PDT");
if (PDT != null && PDT.FeatureCount(null) != 0)
{
TableToTable((PDT as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "PDT");
//CopyTableToDB((PDT as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "PDT");
}
}
}
#endregion
#region 地类图斑更新过程层
if (dataTable.Select(" LayerName='地类图斑更新过程层' ").Length > 0)
{
IFeatureClass DLTBGXGC = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBGXGC");
rdbHelper.ExecuteSQL(" Drop Table DLTBGXGC");
if (DLTBGXGC != null && DLTBGXGC.FeatureCount(null) != 0)
{
TableToTable((DLTBGXGC as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "DLTBGXGC");
//CopyTableToDB((DLTBGXGC as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "DLTBGXGC");
}
}
#endregion
#region 耕地等别更新层
if (dataTable.Select(" LayerName='耕地等别更新层' ").Length > 0)
{
IFeatureClass GDDBGX = MapsManager.Instance.MapService.GetFeatureClassByName("GDDBGX");
rdbHelper.ExecuteSQL(" Drop Table GDDBGX");
if (GDDBGX != null && GDDBGX.FeatureCount(null) != 0)
{
TableToTable((GDDBGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "GDDBGX");
//CopyTableToDB((GDDBGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "GDDBGX");
}
}
#endregion
#region 光伏板区更新层
if (dataTable.Select(" LayerName='光伏板区更新层' ").Length > 0)
{
IFeatureClass GFBQGX = MapsManager.Instance.MapService.GetFeatureClassByName("GFBQGX");
rdbHelper.ExecuteSQL(" Drop Table GFBQGX");
if (GFBQGX != null && GFBQGX.FeatureCount(null) != 0)
{
TableToTable((GFBQGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "GFBQGX");
//CopyTableToDB((GFBQGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "GFBQGX");
}
}
#endregion
#region 路面范围更新层
if (dataTable.Select(" LayerName='路面范围更新层' ").Length > 0)
{
IFeatureClass LMFWGX = MapsManager.Instance.MapService.GetFeatureClassByName("LMFWGX");
rdbHelper.ExecuteSQL(" Drop Table LMFWGX");
if (LMFWGX != null && LMFWGX.FeatureCount(null) != 0)
{
TableToTable((LMFWGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "LMFWGX");
//CopyTableToDB((LMFWGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "LMFWGX");
}
if (dataTable.Select(" Requirement like '%KD取值%' ").Length > 0)
{
IFeatureClass LMFW = MapsManager.Instance.MapService.GetFeatureClassByName("LMFW");
rdbHelper.ExecuteSQL(" Drop Table LMFW");
if (LMFW != null && LMFW.FeatureCount(null) != 0)
{
TableToTable((LMFW as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "LMFW");
//CopyTableToDB((LMFW as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "LMFW");
}
}
}
#endregion
#region 推土区更新层
if (dataTable.Select(" LayerName='推土区更新层' ").Length > 0)
{
IFeatureClass TTQGX = MapsManager.Instance.MapService.GetFeatureClassByName("TTQGX");
rdbHelper.ExecuteSQL(" Drop Table TTQGX");
if (TTQGX != null && TTQGX.FeatureCount(null) != 0)
{
TableToTable((TTQGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "TTQGX");
//CopyTableToDB((TTQGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "TTQGX");
}
}
#endregion
#region 行政区更新层
if (dataTable.Select(" LayerName='行政区更新层' ").Length > 0)
{
IFeatureClass XZQGX = MapsManager.Instance.MapService.GetFeatureClassByName("XZQGX");
rdbHelper.ExecuteSQL(" Drop Table XZQGX");
if (XZQGX != null && XZQGX.FeatureCount(null) != 0)
{
TableToTable((XZQGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "XZQGX");
//CopyTableToDB((XZQGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "XZQGX");
}
}
#endregion
#region 行政区更新过程层
if (dataTable.Select(" LayerName='行政区更新过程层' ").Length > 0)
{
IFeatureClass XZQGXGC = MapsManager.Instance.MapService.GetFeatureClassByName("XZQGXGC");
rdbHelper.ExecuteSQL(" Drop Table XZQGXGC");
if (XZQGXGC != null && XZQGXGC.FeatureCount(null) != 0)
{
TableToTable((XZQGXGC as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "XZQGXGC");
//CopyTableToDB((XZQGXGC as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "XZQGXGC");
}
}
#endregion
#region 行政区界线更新层
if (dataTable.Select(" LayerName='行政区界线更新层' ").Length > 0)
{
IFeatureClass XZQJXGX = MapsManager.Instance.MapService.GetFeatureClassByName("XZQJXGX");
rdbHelper.ExecuteSQL(" Drop Table XZQJXGX");
if (XZQJXGX != null && XZQJXGX.FeatureCount(null) != 0)
{
TableToTable((XZQJXGX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "XZQJXGX");
//CopyTableToDB((XZQJXGX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "XZQJXGX");
}
if (dataTable.Select(" Requirement like '%基础库%' ").Length > 0)
{
IFeatureClass XZQJX = MapsManager.Instance.MapService.GetFeatureClassByName("XZQJX");
rdbHelper.ExecuteSQL(" Drop Table XZQJX");
if (XZQJX != null && XZQJX.FeatureCount(null) != 0)
{
TableToTable((XZQJX as FeatureClass).Workspace as IFeatureWorkspace, pOutWork, "XZQJX");
//CopyTableToDB((XZQJX as FeatureClass).Workspace as IFeatureWorkspace, rdbHelper, "XZQJX");
}
}
}
#endregion
}
}
catch (Exception ex)
{
LogAPI.Debug(ex);
return;
}
}
private void JudgeNullBSMAssign(IFeatureClass featureClass)
{
IFeatureCursor pCursor = null;
IFeature feature = null;
try
{
IFeatureCursor jcCursor = featureClass.Search(new QueryFilter() { WhereClause = "BSM='' or BSM=' ' or BSM is NULL" }, true);
if (jcCursor.NextFeature() == null) return;
int iBSM = featureClass.Fields.FindField("BSM");//标识码
pCursor = featureClass.Update(null, true);
int bsm = 1;
while ((feature = pCursor.NextFeature()) != null)
{
feature.Value[iBSM] = $"{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).CODE}2110{(bsm++).ToString().PadLeft(8, '0')}";
feature.Store();
}
pCursor.Flush();
}
catch (Exception ex)
{
LogAPI.Debug("JudgeNullBSMAssign 异常:" + ex.Message);
LogAPI.Debug("JudgeNullBSMAssign 异常:" + ex.StackTrace);
}
finally
{
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
if (feature != null)
Marshal.ReleaseComObject(feature);
}
}
private List<string> LineNoDangles(string ErrorCode, string LayerName, string AliasName)
{
IEnvelope envelope = null;
string topologyName = "LineNoDangles";
try
{
IFeatureLayer JC_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(LayerName);
TopologyVerification(topologyName, JC_featureLayer.FeatureClass, new List<esriTopologyRuleType> { esriTopologyRuleType.esriTRTLineNoDangles }, ref envelope);
return FindAllError(topologyName, envelope, JC_featureLayer.FeatureClass, LayerName, ErrorCode, AliasName);
}
catch (Exception ex)
{
throw ex;
}
}
public void StopProcess(string processName)
{
try
{
System.Diagnostics.Process[] ps = Process.GetProcessesByName(processName);
foreach (Process p in ps)
{
p.Kill();
}
}
catch (Exception ex)
{
LogAPI.Debug("停止进程失败:" + ex.Message);
return;
}
}
private void GetJCLayerName(string layerName, out string JCLayerName)
{
JCLayerName = null;
if (layerName.Contains("XZQJXGX"))
JCLayerName = "XZQJX";
else if (layerName.Contains("CJDCQJXGX"))
JCLayerName = "CJDCQJX";
}
private List<string> SameGraphic(string layerName, string JC_layerName, string RuleCode, string RuleName, string TempfilePath)
{
GPParamClass paramClass = null;
IFeatureLayer SameGraphic_Intersect = null;
IFeatureLayer multipartToSingleFeatureLayer = null;
List<string> sqlList = new List<string>();
IFeatureLayer GXFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(layerName);
IFeatureLayer JC_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(JC_layerName);
ICursor nmkCur = null;
IRow nmkRow = null;
IFeatureCursor pCursor = null;
IFeature feature = null;
try
{
if (GXFeatureLayer == null || GXFeatureLayer.FeatureClass.FeatureCount(null) == 0 || JC_featureLayer == null || JC_featureLayer.FeatureClass.FeatureCount(null) == 0)
{
return sqlList;
}
paramClass = new GPParamClass()
{
FirstFeatureLayer = GXFeatureLayer,
GPType = EnumGPType.UnsplitLine,
SecondFeatureLayer = JC_featureLayer,
OutFeatureClassPath = $"{TempfilePath}\\SameGraphic_Intersect",
FcName = GXFeatureLayer.Name,
IsGetOutPutFeature = true
};
GeoprocessorHelper.IntersectAnalysis(paramClass, ref SameGraphic_Intersect);
paramClass = new GPParamClass();
paramClass.FirstFeatureLayer = SameGraphic_Intersect;
paramClass.OutFeatureClassPath = $"{TempfilePath}\\SameGraphic_Multipart";
paramClass.IsGetOutPutFeature = true;
GeoprocessorHelper.MultipartToSinglePath(paramClass, ref multipartToSingleFeatureLayer);
if (multipartToSingleFeatureLayer.FeatureClass == null) return null;
int fid_DLTBBGIndex = 0;
for (int i = 0; i < multipartToSingleFeatureLayer.FeatureClass.Fields.FieldCount; i++)
{
if (multipartToSingleFeatureLayer.FeatureClass.Fields.Field[i].Name.Contains("FID_"))
{
fid_DLTBBGIndex = i;
break;
}
}
ITable nmkTable = multipartToSingleFeatureLayer.FeatureClass as ITable;
int rowCount = nmkTable.RowCount(new QueryFilterClass() { WhereClause = "BGXW in ('0','4')" });
if (rowCount <= 0) return null;
nmkCur = nmkTable.Update(new QueryFilterClass() { WhereClause = "BGXW in ('0','4')" }, true);
List<string> allIntersectObjectId = new List<string>();
while ((nmkRow = nmkCur.NextRow()) != null)
{
allIntersectObjectId.Add(nmkRow.Value[fid_DLTBBGIndex].ToString());
}
pCursor = GXFeatureLayer.FeatureClass.Search(new QueryFilterClass() { WhereClause = "BGXW in ('0','4')" }, true);
int iTableBSM = GXFeatureLayer.FeatureClass.FindField("BSM");
int objectid = GXFeatureLayer.FeatureClass.FindField("OBJECTID");
var FID_DLTBBG = string.Empty;
var BSM = string.Empty;
while ((feature = pCursor.NextFeature()) != null)
{
FID_DLTBBG = feature.Value[objectid].ToString();
BSM = feature.Value[iTableBSM].ToString();
if (!allIntersectObjectId.Contains(FID_DLTBBG.ToString()))
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults (OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}','值域规范性','{5}');", FID_DLTBBG, BSM, layerName, RuleCode, RuleName, feature.Shape.ToJson()));
}
}
//删除临时文件
DeleteTempFeatureLayer(multipartToSingleFeatureLayer);
DeleteTempFeatureLayer(SameGraphic_Intersect);
}
catch (Exception ex)
{
LogAPI.Debug($"SameGraphic执行错误:{ex.Message}");
LogAPI.Debug(ex);
}
finally
{
if (SameGraphic_Intersect != null)
Marshal.ReleaseComObject(SameGraphic_Intersect);
if (multipartToSingleFeatureLayer != null)
Marshal.ReleaseComObject(multipartToSingleFeatureLayer);
if (GXFeatureLayer != null)
Marshal.ReleaseComObject(GXFeatureLayer);
if (JC_featureLayer != null)
Marshal.ReleaseComObject(JC_featureLayer);
if (nmkCur != null)
Marshal.ReleaseComObject(nmkCur);
if (nmkRow != null)
Marshal.ReleaseComObject(nmkRow);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
if (feature != null)
Marshal.ReleaseComObject(feature);
GC.Collect();
}
return sqlList;
}
private List<string> SameBSM(string layerName, string JC_layerName, string RuleCode, string RuleName, string TempfilePath)
{
GPParamClass paramClass = null;
IFeatureLayer SameBSM_Intersect = null;
IFeatureLayer multipartToSingleFeatureLayer = null;
List<string> sqlList = new List<string>();
IFeatureLayer GXFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(layerName);
IFeatureLayer JC_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(JC_layerName);
IFeatureCursor pCursor = null;
IFeature feature = null;
try
{
if (GXFeatureLayer == null || GXFeatureLayer.FeatureClass.FeatureCount(null) == 0 || JC_featureLayer == null || JC_featureLayer.FeatureClass.FeatureCount(null) == 0)
{
return sqlList;
}
paramClass = new GPParamClass()
{
FirstFeatureLayer = GXFeatureLayer,
GPType = EnumGPType.UnsplitLine,
SecondFeatureLayer = JC_featureLayer,
OutFeatureClassPath = $"{TempfilePath}\\SameBSM_Intersect",
FcName = GXFeatureLayer.Name,
IsGetOutPutFeature = true
};
GeoprocessorHelper.IntersectAnalysis(paramClass, ref SameBSM_Intersect);
paramClass = new GPParamClass();
paramClass.FirstFeatureLayer = SameBSM_Intersect;
paramClass.OutFeatureClassPath = $"{TempfilePath}\\SameBSM_Multipart";
paramClass.IsGetOutPutFeature = true;
GeoprocessorHelper.MultipartToSinglePath(paramClass, ref multipartToSingleFeatureLayer);
if (multipartToSingleFeatureLayer.FeatureClass == null) return null;
int fid_BGXWIndex = multipartToSingleFeatureLayer.FeatureClass.Fields.FindField("BGXW");
int fid_DLTBBGIndex = 0;
for (int i = 0; i < multipartToSingleFeatureLayer.FeatureClass.Fields.FieldCount; i++)
{
if (multipartToSingleFeatureLayer.FeatureClass.Fields.Field[i].Name.Contains("FID_"))
{
fid_DLTBBGIndex = i;
break;
}
}
int iBSM = multipartToSingleFeatureLayer.FeatureClass.FindField("BSM");
int iBSM_1 = multipartToSingleFeatureLayer.FeatureClass.FindField("BSM_1");
ITable nmkTable = multipartToSingleFeatureLayer.FeatureClass as ITable;
int rowCount = nmkTable.RowCount(new QueryFilterClass() { WhereClause = "BGXW in ('0','4')" });
if (rowCount <= 0) return null;
pCursor = multipartToSingleFeatureLayer.FeatureClass.Search(new QueryFilterClass() { WhereClause = "BGXW in ('0','4')" }, true);
var FID_OBJECTID = string.Empty;
var BSM = string.Empty;
var BGXW = string.Empty;
while ((feature = pCursor.NextFeature()) != null)
{
FID_OBJECTID = feature.Value[fid_DLTBBGIndex].ToString();
BSM = feature.Value[iBSM].ToString();
BGXW = feature.Value[fid_BGXWIndex].ToString();
if (string.IsNullOrEmpty(BGXW.ToString()) || (BGXW.ToString() != "0" && BGXW.ToString() != "4")) continue;
if (BSM.ToString() != feature.Value[iBSM_1].ToString())
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults (OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}','值域规范性','{5}');", FID_OBJECTID, BSM, layerName, RuleCode, RuleName, feature.Shape.ToJson()));
}
}
//删除临时文件
DeleteTempFeatureLayer(multipartToSingleFeatureLayer);
DeleteTempFeatureLayer(SameBSM_Intersect);
}
catch (Exception ex)
{
LogAPI.Debug($"SameBSM执行错误:{ex.Message}");
LogAPI.Debug(ex);
}
finally
{
if (SameBSM_Intersect != null)
Marshal.ReleaseComObject(SameBSM_Intersect);
if (multipartToSingleFeatureLayer != null)
Marshal.ReleaseComObject(multipartToSingleFeatureLayer);
if (GXFeatureLayer != null)
Marshal.ReleaseComObject(GXFeatureLayer);
if (JC_featureLayer != null)
Marshal.ReleaseComObject(JC_featureLayer);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
if (feature != null)
Marshal.ReleaseComObject(feature);
GC.Collect();
}
return sqlList;
}
private List<string> JudgeNewRoad(string layerName, string JC_layerName, string RuleCode, string RuleName, string RuleType)
{
GPParamClass paramClass = null;
IFeatureLayer SameLMFW_Intersect = null;
IFeatureLayer LMFW_Intersect = null;
List<string> sqlList = new List<string>();
IFeatureLayer GXFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(layerName);
IFeatureLayer JC_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(JC_layerName);
ICursor nmkCur = null;
IRow nmkRow = null;
IFeatureCursor pCursor = null;
IFeature feature = null;
try
{
if (GXFeatureLayer == null || GXFeatureLayer.FeatureClass.FeatureCount(null) == 0 || JC_featureLayer == null || JC_featureLayer.FeatureClass.FeatureCount(null) == 0)
return null;
paramClass = new GPParamClass()
{
FirstFeatureLayer = GXFeatureLayer,
SecondFeatureLayer = JC_featureLayer,
FcName = GXFeatureLayer.Name,
IsGetOutPutFeature = true
};
GeoprocessorHelper.IntersectAnalysis(paramClass, ref SameLMFW_Intersect);
paramClass = new GPParamClass();
paramClass.FirstFeatureLayer = SameLMFW_Intersect;
paramClass.IsGetOutPutFeature = true;
GeoprocessorHelper.MultipartToSinglePath(paramClass, ref LMFW_Intersect);
if (LMFW_Intersect.FeatureClass == null) return null;
int fid_gxIndex = 0;
for (int i = 0; i < LMFW_Intersect.FeatureClass.Fields.FieldCount; i++)
{
if (LMFW_Intersect.FeatureClass.Fields.Field[i].Name.Contains("FID_"))
{
fid_gxIndex = i;
break;
}
}
ITable nmkTable = LMFW_Intersect.FeatureClass as ITable;
int rowCount = nmkTable.RowCount(null);
if (rowCount <= 0) return null;
nmkCur = nmkTable.Update(null, true);
List<string> allIntersectObjectId = new List<string>();
while ((nmkRow = nmkCur.NextRow()) != null)
{
allIntersectObjectId.Add(nmkRow.Value[fid_gxIndex].ToString());
}
pCursor = GXFeatureLayer.FeatureClass.Search(null, true);
int iTableBSM = GXFeatureLayer.FeatureClass.FindField("BSM");
int objectid = GXFeatureLayer.FeatureClass.FindField("OBJECTID");
int iKD = GXFeatureLayer.FeatureClass.FindField("KD");
var FID_LMFWGX = string.Empty;
var BSM = string.Empty;
var kdValue = string.Empty;
while ((feature = pCursor.NextFeature()) != null)
{
FID_LMFWGX = feature.Value[objectid].ToString();
BSM = feature.Value[iTableBSM].ToString();
kdValue = feature.Value[iKD].ToString();
if (!allIntersectObjectId.Contains(FID_LMFWGX.ToString()))//新增道路 允许为空
{
if (!string.IsNullOrEmpty(kdValue.ToString()) && double.Parse(kdValue.ToString()) < 0)
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}');",
FID_LMFWGX.ToString(), BSM.ToString(), layerName, RuleCode, RuleName, RuleType, feature.Shape.ToJson()));
}
}
else //不是新增 不允许为空
{
if (string.IsNullOrEmpty(kdValue.ToString()) || double.Parse(kdValue.ToString()) < 0)
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}');",
FID_LMFWGX.ToString(), BSM.ToString(), layerName, RuleCode, RuleName, RuleType, feature.Shape.ToJson()));
}
}
}
DeleteTempFeatureLayer(LMFW_Intersect);
DeleteTempFeatureLayer(SameLMFW_Intersect);
}
catch (Exception ex)
{
LogAPI.Debug($"JudgeNewRoad执行错误:{ex.Message}");
LogAPI.Debug(ex);
}
finally
{
if (LMFW_Intersect != null)
Marshal.ReleaseComObject(LMFW_Intersect);
if (SameLMFW_Intersect != null)
Marshal.ReleaseComObject(SameLMFW_Intersect);
if (GXFeatureLayer != null)
Marshal.ReleaseComObject(GXFeatureLayer);
if (JC_featureLayer != null)
Marshal.ReleaseComObject(JC_featureLayer);
if (nmkCur != null)
Marshal.ReleaseComObject(nmkCur);
if (nmkRow != null)
Marshal.ReleaseComObject(nmkRow);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
if (feature != null)
Marshal.ReleaseComObject(feature);
GC.Collect();
}
return sqlList;
}
private List<string> SameGDPDJB(string layerName, string PDT_layerName, string RuleCode, string RuleName, string RuleType)
{
GPParamClass paramClass = null;
IFeatureLayer GDPDJB_Union = null;
List<string> sqlList = new List<string>();
IFeatureLayer DLTBGXFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(layerName);
IFeatureLayer PDT_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(PDT_layerName);
ICursor nmkCur = null;
IRow nmkRow = null;
IFeatureCursor pCursor = null;
IFeature feature = null;
try
{
if (DLTBGXFeatureLayer == null || DLTBGXFeatureLayer.FeatureClass.FeatureCount(null) == 0 || PDT_featureLayer == null || PDT_featureLayer.FeatureClass.FeatureCount(null) == 0)
return null;
paramClass = new GPParamClass()
{
FirstFeatureLayer = DLTBGXFeatureLayer,
GPType = EnumGPType.Union,
SecondFeatureLayer = PDT_featureLayer,
FcName = DLTBGXFeatureLayer.Name,
IsGetOutPutFeature = true
};
GeoprocessorHelper.UnionAnalysis(paramClass, ref GDPDJB_Union);
if (GDPDJB_Union == null) return null;
int fid_DLTBGXIndex = GDPDJB_Union.FeatureClass.Fields.FindField("FID_" + layerName);
int fid_PDTIndex = GDPDJB_Union.FeatureClass.Fields.FindField("FID_" + PDT_layerName);
int iDLTBGXPDJB = GDPDJB_Union.FeatureClass.FindField("GDPDJB");
int iPDTPDJB = GDPDJB_Union.FeatureClass.FindField("PDJB");
int bsmIndex = GDPDJB_Union.FeatureClass.Fields.FindField("BSM");
int shapeAreaIndex = GDPDJB_Union.FeatureClass.Fields.FindField("SHAPE_AREA");
ITable nmkTable = GDPDJB_Union.FeatureClass as ITable;
IQueryFilter queryfilter = new QueryFilterClass();
queryfilter.WhereClause = string.Format("DLBM like '01%' ");
nmkCur = nmkTable.Search(queryfilter, true);
if (iDLTBGXPDJB == -1 || iPDTPDJB == -1) return null;
double shapeArea = 0.00;
List<GDPDJBInfo> gDPDJBInfoList = new List<GDPDJBInfo>();
bool changedInfo = false;
var dltbgxValue = string.Empty;
var pdtValue = string.Empty;
string bsmValue = string.Empty;
string pdjbValue = string.Empty;
List<GDPDJBInfo> tempGDPDJBInfo = new List<GDPDJBInfo>();
while ((nmkRow = nmkCur.NextRow()) != null)
{
dltbgxValue = nmkRow.Value[fid_DLTBGXIndex].ToString();
pdtValue = nmkRow.Value[fid_PDTIndex].ToString();
if (dltbgxValue.ToString() == "-1" || pdtValue.ToString() == "-1") continue;
bsmValue = nmkRow.Value[bsmIndex].ToString();
pdjbValue = nmkRow.Value[iPDTPDJB].ToString();
shapeArea = nmkRow.Value[shapeAreaIndex].ToDouble();
changedInfo = false;
if (gDPDJBInfoList.Exists(a => a.BSM == bsmValue))
{
tempGDPDJBInfo.Clear();
tempGDPDJBInfo = gDPDJBInfoList.FindAll(a => a.BSM == bsmValue);
foreach (GDPDJBInfo item in tempGDPDJBInfo)
{
if (item.PDJB == pdjbValue)
{
item.Area += shapeArea;
changedInfo = true;
break;
}
}
if (!changedInfo)
gDPDJBInfoList.Add(new GDPDJBInfo() { BSM = bsmValue, PDJB = pdjbValue, Area = shapeArea });
}
else
{
gDPDJBInfoList.Add(new GDPDJBInfo() { BSM = bsmValue, PDJB = pdjbValue, Area = shapeArea });
}
}
List<string> areaList = new List<string>();
double maxArea = 0;
string maxAreaPDJB = "-1";
pCursor = DLTBGXFeatureLayer.FeatureClass.Search(queryfilter, true);
fid_DLTBGXIndex = DLTBGXFeatureLayer.FeatureClass.Fields.FindField("OBJECTID");
iDLTBGXPDJB = DLTBGXFeatureLayer.FeatureClass.FindField("GDPDJB");
bsmIndex = DLTBGXFeatureLayer.FeatureClass.Fields.FindField("BSM");
var dltbPDJBValue = string.Empty;
while ((feature = pCursor.NextFeature()) != null)
{
areaList.Clear();
maxArea = 0;
maxAreaPDJB = "-1";
dltbgxValue = feature.Value[fid_DLTBGXIndex].ToString();
dltbPDJBValue = feature.Value[iDLTBGXPDJB].ToString();
bsmValue = feature.Value[bsmIndex].ToString();
tempGDPDJBInfo.Clear();
tempGDPDJBInfo = gDPDJBInfoList.FindAll(a => a.BSM == bsmValue);
foreach (GDPDJBInfo item in tempGDPDJBInfo)
{
if (maxArea < item.Area)
{
maxArea = item.Area;
maxAreaPDJB = item.PDJB;
}
}
if (!string.IsNullOrEmpty(maxAreaPDJB) && maxAreaPDJB != "-1" && !string.IsNullOrEmpty(dltbPDJBValue.ToString()) && !string.IsNullOrEmpty(dltbPDJBValue.ToString()) && dltbPDJBValue.ToString() != maxAreaPDJB)
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}','{5}','{6}');", dltbgxValue.ToString(), feature.Value[bsmIndex], layerName, RuleCode, RuleName, RuleType, feature.Shape.ToJson()));
}
}
DeleteTempFeatureLayer(GDPDJB_Union);
}
catch (Exception ex)
{
LogAPI.Debug($"SameGDPDJB执行错误:{ex.Message}");
LogAPI.Debug(ex);
}
finally
{
if (GDPDJB_Union != null)
Marshal.ReleaseComObject(GDPDJB_Union);
if (DLTBGXFeatureLayer != null)
Marshal.ReleaseComObject(DLTBGXFeatureLayer);
if (PDT_featureLayer != null)
Marshal.ReleaseComObject(PDT_featureLayer);
if (nmkCur != null)
Marshal.ReleaseComObject(nmkCur);
if (nmkRow != null)
Marshal.ReleaseComObject(nmkRow);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
if (feature != null)
Marshal.ReleaseComObject(feature);
GC.Collect();
}
return sqlList;
}
//删除临时文件
public static void DeleteTempFeatureLayer(IFeatureLayer pFeatureLayer)
{
if (pFeatureLayer == null) return;
try
{
ITable tempTable = pFeatureLayer.FeatureClass as ITable;
if (tempTable == null) return;
IFeatureWorkspaceManage pWorkspaceManager = (pFeatureLayer.FeatureClass as FeatureClass).Workspace as IFeatureWorkspace as IFeatureWorkspaceManage;
pWorkspaceManager.DeleteByName((IDatasetName)((IDataset)tempTable).FullName);
}
catch (Exception ex)
{
LogAPI.Debug("删除临时文件异常:" + ex);
}
}
#region TableToTable
public bool TableToTable(IFeatureWorkspace pInWork, IWorkspace pOutWork, string tableName, IQueryFilter queryFilter = null)
{
try
{
if (pInWork == null || pOutWork == null || string.IsNullOrEmpty(tableName)) return false;
if (pInWork is IWorkspace2 workspace2)
{
if (!workspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, tableName))
{
return false;
}
}
ITable pInTable = pInWork.OpenTable(tableName);
if (pInTable == null) return false;
IDataset pIndataset = (IDataset)pInTable;
IDatasetName pInDatasetName = (IDatasetName)pIndataset.FullName;
IEnumDataset enumDataset = pOutWork.get_Datasets(esriDatasetType.esriDTTable);
IDataset dataset;
enumDataset.Reset();
while ((dataset = enumDataset.Next()) != null)
{
string[] names = dataset.Name.Split('.');
if (string.Equals(names[names.Length - 1], tableName, StringComparison.CurrentCultureIgnoreCase))
{
dataset.Delete();
break;
}
}
IDataset pOutDataset = (IDataset)pOutWork;
IDatasetName pOutDatasetName = new TableNameClass();
pOutDatasetName.WorkspaceName = (IWorkspaceName)pOutDataset.FullName;
pOutDatasetName.Name = tableName;
IFieldChecker fieldChecker = new FieldCheckerClass();
IFields targetFeatureClassFields = pInTable.Fields;
IFields sourceFeatureClassFields = pInTable.Fields;
IEnumFieldError enumFieldError;
fieldChecker.InputWorkspace = pInWork as IWorkspace;
fieldChecker.ValidateWorkspace = pOutWork;
fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields);
IFeatureDataConverter one2another = new FeatureDataConverterClass();
try
{
one2another.ConvertTable(pInDatasetName, queryFilter, pOutDatasetName, targetFeatureClassFields, "", 1000, 0);
}
finally
{
Marshal.ReleaseComObject(one2another);
}
return true;
}
catch (Exception ex)
{
LogAPI.Debug(ex);
throw ex;
}
}
#endregion
#region 其他方式复制矢量到DB表
private void CopyTableToDB(IFeatureWorkspace pInWork, IRDBHelper rdbHelper, string tableName)
{
ICursor pCursor = null;
IRow pRow = null;
try
{
if (pInWork == null || string.IsNullOrEmpty(tableName)) return;
IWorkspace2 workspace2 = pInWork as IWorkspace2;
if (workspace2 != null)
{
if (!workspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, tableName)) return;
}
ITable pInTable = pInWork.OpenTable(tableName);
if (pInTable == null) return;
int shapeIndex = pInTable.Fields.FindField("SHAPE");
if (shapeIndex < 0)
{
throw new Exception("未找到SHAPE字段");
}
List<string> listSQL = new List<string>();
string fieldStr = string.Empty;
string insertField = string.Empty;
Dictionary<int, bool> listFieldIndex = new Dictionary<int, bool>();
for (int f = 0; f < pInTable.Fields.FieldCount; f++)
{
IField field = pInTable.Fields.Field[f];
if (field.Name.ToUpper() == "SHAPE")
{
continue;
}
switch (field.Type)
{
case esriFieldType.esriFieldTypeSmallInteger:
fieldStr += field.Name + " INTEGER,";
insertField += field.Name + ",";
listFieldIndex.Add(f, false);
break;
case esriFieldType.esriFieldTypeInteger:
fieldStr += field.Name + " INTEGER,";
insertField += field.Name + ",";
listFieldIndex.Add(f, false);
break;
case esriFieldType.esriFieldTypeOID:
fieldStr += field.Name + " INTEGER,";
insertField += field.Name + ",";
listFieldIndex.Add(f, false);
break;
case esriFieldType.esriFieldTypeDouble:
fieldStr += field.Name + " INTEGER,";
insertField += field.Name + ",";
listFieldIndex.Add(f, false);
break;
case esriFieldType.esriFieldTypeSingle:
fieldStr += field.Name + " NUMERIC,";
insertField += field.Name + ",";
listFieldIndex.Add(f, false);
break;
case esriFieldType.esriFieldTypeString:
fieldStr += field.Name + " TEXT,";
insertField += field.Name + ",";
listFieldIndex.Add(f, true);
break;
case esriFieldType.esriFieldTypeDate:
fieldStr += field.Name + " TEXT,";
insertField += field.Name + ",";
listFieldIndex.Add(f, true);
break;
default:
fieldStr += field.Name + " TEXT,";
insertField += field.Name + ",";
listFieldIndex.Add(f, true);
break;
}
}
//rdbHelper.ExecuteSQL($"Drop table {tableName}");
string createTableSQL = string.Format("CREATE TABLE if not exists {1} ({0})", fieldStr.TrimEnd(','), tableName);
rdbHelper.ExecuteNonQueryWithException(createTableSQL, CommandType.Text);
string insertSQL = "insert into " + tableName + "(" + insertField.TrimEnd(',') + ")values({0});";
int count = pInTable.RowCount(null);
int i = 0;
pCursor = pInTable.Search(null, true);
while ((pRow = pCursor.NextRow()) != null)
{
string value = string.Empty;
foreach (var item in listFieldIndex)
{
object obj = pRow.get_Value(item.Key);
if (item.Value)
{
if (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))
{
value += "'',";
}
else
{
value += "'" + obj.ToString().Replace("'", "") + "',";
}
}
else
{
if (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))
{
obj = 0;
}
value += obj + ",";
}
}
listSQL.Add(string.Format(insertSQL, value.TrimEnd(',')));
//i++;
//if (i % 100 == 0 || i == count)
//{
// this.UpdateMsg($"正在数据写入...【{i}/{count}】");
// rdbHelper.ExecuteNonQueryWithException(item, CommandType.Text);
//}
//if (listSQL.Count > 10)
//{
// InsertDB(listSQL, rdbHelper);
// listSQL.Clear();
//}
//else if (i == count)
//{
// InsertDB(listSQL, rdbHelper);
// listSQL.Clear();
//}
}
for (int m = 0; m < listSQL.Count; m++)
{
this.UpdateMsg($"正在数据写入...【{m}/{count}】");
rdbHelper.ExecuteNonQueryWithException(listSQL[m], CommandType.Text);
}
}
catch (Exception ex)
{
LogAPI.Debug("CopyTableToDB 异常:" + ex.Message);
LogAPI.Debug("CopyTableToDB 异常:" + ex.StackTrace);
}
finally
{
if (pCursor != null)
{
Marshal.ReleaseComObject(pCursor);
}
if (pRow != null)
{
Marshal.ReleaseComObject(pRow);
}
}
}
#endregion
/// <summary>
/// 将检查数据存储在DB中
/// </summary>
public void SaveDataToDB()
{
string dbPath = System.IO.Path.Combine((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir, "DataCheckrResult.db");
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, "drop table DataCheckResults", null);
string sql = "CREATE TABLE " + " DataCheckResults " + " (`ID` INTEGER, `ErrorLayer` TEXT,`PrimaryKey` TEXT, `PrimaryKeyValue` TEXT,`PrimaryKey2` TEXT, `PrimaryKeyValue2` TEXT,`ErrorType` TEXT,`ErrorCode` TEXT,`ErrorDesc` TEXT,`ErrorData` TEXT,`ErrorArea` TEXT,`ErrorMJ` NUMERIC,PRIMARY KEY(`ID`))";
//if (!_IsExit)//不存在,则创建该表
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, sql, null);
List<string> sqlList = new List<string>();
sqlList.Add("delete from DataCheckResults");
foreach (var item in m_Check.CheckResults)
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults (ErrorLayer,PrimaryKey, PrimaryKeyValue,PrimaryKey2, PrimaryKeyValue2,ErrorType,ErrorCode,ErrorDesc,ErrorData,ErrorArea,ErrorMJ) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}',{10})", item.ErrorLayer, item.PrimaryKey, item.PrimaryKeyValue, item.BSM, item.PrimaryKeyValue2, item.ErrorType, item.ErrorCode, item.ErrorDesc, item.ErrorData, item.ErrorArea, item.ErrorMJ));
}
InsertSQLiteData(dbPath, sqlList);
ProgressHelper.CloseProcessBar();
MessageHelper.Show("数据检查完成。");
LoadData();
}
public void InsertSQLiteData(string dbPath, List<string> sqlList)
{
try
{
//DateTime dtS = DateTime.Now;
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + dbPath))
{
conn.Open();
using (SQLiteTransaction pTrans = conn.BeginTransaction())
{
using (SQLiteCommand cmd = new SQLiteCommand(conn))
{
for (int i = 0; i < sqlList.Count(); i++)
{
cmd.CommandText = sqlList[i];
cmd.ExecuteNonQuery();
}
pTrans.Commit();
}
}
conn.Close();
}
}
catch (Exception ex)
{
LogAPI.Debug("批量插入SQLite数据(地址:" + dbPath + ") 执行失败,异常原因: " + ex.Message + " ; ");
return;
}
}
V_Repair.FrmBachRepair repairView = null;
/// <summary>
/// 批量修复
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnBatchRepair_Click(object sender, RoutedEventArgs e)
{
IGeometry geometry = null;
IRDBHelper rdbHelper = null;
IFeatureLayer dltbbg_Layer = null;
IFeatureLayer JcTb_Layer = null;
IFeatureLayer mErrLayer = null;
try
{
(sender as Button).IsEnabled = false;
ExtensionShowWindow.MainWinForm.Enabled = false;
this.ShowLoading($"正在进行批量修复...", 0, 0);
System.Threading.Thread.Sleep(1000);
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
string DataCheckResultsSQL = string.Empty;
if (_CheckName == "变更图斑")
{
DataCheckResultsSQL = " where ErrorLayer='DLTBBG' or ErrorLayer='地类图斑变更层' ";
}
DataTable DataCheckResults = rdbHelper.ExecuteDatatable("tab", $"select * from DataCheckResults {DataCheckResultsSQL} order by BSM desc", true);
if (DataCheckResults != null && DataCheckResults.Rows.Count > 0)
{
dltbbg_Layer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
JcTb_Layer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("地类图斑");
if (_CheckName == "基础图斑")
{
dltbbg_Layer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("地类图斑");
//PluginServiceInterface.CommonHelper.RemoveReadOnly((JcTb_Layer.FeatureClass as FeatureClass).Workspace.PathName);
//修复几何
try
{
GeoprocessorHelper.RepairGeo(JcTb_Layer.FeatureClass, true);
}
catch { }
}
IWorkspaceAPI workspaceAPI = null;// new WorkspaceAPI((MapsManager.Instance.CurrProjectInfo as ProjectInfo).DataCheckPath, WorkspaceTypeEnum.GDBFile);
IFeatureClassAPI featureClassAPI = null;// workspaceAPI.OpenFeatureClass("Multipart");
List<RepairEntity> repairEntities = new List<RepairEntity>();
var ErrorCode = string.Empty;
var BSM = string.Empty;
var OBJECTID = string.Empty;
var ID = string.Empty;
var ErrorArea = string.Empty;
var ErrorName = string.Empty;
var errorLayerEngish = string.Empty;
var mOID = string.Empty;
foreach (DataRow row in DataCheckResults.Rows)
{
try
{
ErrorCode = row["ErrorCode"].ToString();
BSM = row["BSM"].ToString();
OBJECTID = row["OBJECTID"].ToString();
ErrorName = row["ErrorName"].ToString();
if (ErrorName.Contains("批量不处理")) continue;
ID = row["ID"].ToString();
ErrorArea = row["ErrorArea"].ToString();
errorLayerEngish = row["ErrorLayer"].ToString();
mOID = row["MultipartOID"].ToString();
#region Topology
if (ErrorCode == "32074304000007")//拓扑错误
{
try
{ geometry = IPolygonExtension.ToGeometry(ErrorArea, true, esriGeometryType.esriGeometryPolygon); }
catch
{ geometry = IPolygonExtension.ToGeometry(ErrorArea, false, esriGeometryType.esriGeometryPolyline); }
//geometry = feature.ShapeCopy;
if (geometry == null || geometry.IsEmpty) continue;
var OriginOID = BSM.Split('-')[0].ToInt();
var DestinationOID = BSM.Split('-')[1].ToInt();
IFeature OriginFC = dltbbg_Layer.FeatureClass.GetFeature(OriginOID);
IFeature DestinationFC = dltbbg_Layer.FeatureClass.GetFeature(DestinationOID);
if (geometry.GeometryType == esriGeometryType.esriGeometryPolyline)
{
var geo = RepairGeometry(OriginFC, geometry);
IGeometry Union = FeatureAPI.Union(OriginFC.ShapeCopy, geo);
OriginFC.Shape = Union;
OriginFC.Store();
IGeometry difference = FeatureAPI.Difference(DestinationFC.ShapeCopy, Union);//擦除
DestinationFC.Shape = difference;
DestinationFC.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
else if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon && geometry.GetEllipseArea() < 20)
{
IGeometry Union = FeatureAPI.Union(OriginFC.Shape, geometry);
List<IGeometry> geoList = FeatureAPI.DissolveGeometryByRing(Union);
OriginFC.Shape = Union;
OriginFC.Store();
IGeometry difference = FeatureAPI.Difference(DestinationFC.Shape, Union);//擦除
geoList = FeatureAPI.DissolveGeometryByRing(difference);
DestinationFC.Shape = difference;
DestinationFC.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
}
else if (ErrorCode == "32074304000006")//变更图斑与基础库联合出的错误
{
if (workspaceAPI == null)
{
workspaceAPI = new WorkspaceAPI(row["RepairfilePath"].ToString(), WorkspaceTypeEnum.GDBFile);
if (featureClassAPI == null)
featureClassAPI = workspaceAPI.OpenFeatureClass("DLTBBG_Err");
}
var MultipartOID = row["MultipartOID"].ToString();
if (string.IsNullOrEmpty(MultipartOID)) continue;
IFeature ErrorFeature = featureClassAPI.GetFeature(MultipartOID.ToInt());
geometry = ErrorFeature.ShapeCopy;
if (geometry != null && geometry.IsEmpty) continue;
if (OBJECTID == "-1")//OBJECTID 为-1 的 需要与变更图斑合并
{
var togologic = geometry as ITopologicalOperator;
togologic.Simplify();
IPointCollection bgFeatures = GetSplitFeatures2(ErrorFeature, dltbbg_Layer, JcTb_Layer);
if (RepairBgtbForPoint(ErrorFeature, dltbbg_Layer, bgFeatures))
{
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
else
{
int idx = ErrorFeature.Fields.FindField("FID_DLTB");
if (idx == -1)
idx = ErrorFeature.Fields.FindField("FID_JCDLTB");
var errJcOID = ErrorFeature.Value[idx].ToTrim();
if (mErrLayer == null)
{
mErrLayer = new FeatureLayerClass() { FeatureClass = featureClassAPI.FeatureClass, SpatialReference = ErrorFeature.ShapeCopy.SpatialReference };
}
List<IFeature> TempFeatures = FeatureAPI.Identify(ErrorFeature.ShapeCopy, dltbbg_Layer);
List<IFeature> JCTempFeatures = FeatureAPI.Identify(ErrorFeature.ShapeCopy, mErrLayer);
int bgOID = -1;
int idxBgOID = ErrorFeature.Fields.FindField("FID_DLTBBG");
//List<int> unOIDs = new List<int>();
//foreach (var item in JCTempFeatures)
//{
// var jcOID = item.Value[idx].ToTrim();
// if (jcOID == errJcOID)
// {
// bgOID = item.Value[idxBgOID].ToInt();
// if (bgOID != -1 && !unOIDs.Contains(bgOID))
// unOIDs.Add(bgOID);
// }
//}
if (JCTempFeatures.Count == 1)
{
//图形相邻与共边最长的图斑合并
IFeature UnionFeature = null;
var Unionlength = 0.00;
foreach (IFeature ifeature in TempFeatures)
{
var length = FeatureAPI.LengthOfSide(ErrorFeature.ShapeCopy, ifeature.Shape);
if (length > Unionlength)
{
Unionlength = length;
UnionFeature = ifeature;
}
}
if (UnionFeature != null)
{
IGeometry geometrys = FeatureAPI.Union(UnionFeature.ShapeCopy, ErrorFeature.ShapeCopy);
if (geometrys != null && !geometrys.IsEmpty)
{
UnionFeature.Shape = geometrys;
UnionFeature.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
}
}
}
#region 代码注释
//List<IFeature> bgFeatures = GetSplitFeatures(ErrorFeature, dltbbg_Layer);// FeatureAPI.Identify(geometry, dltbbg_Layer);
//if (bgFeatures == null)
// continue;
//if (bgFeatures.Count == 1)
//{
// IGeometry geometrys = FeatureAPI.Union(bgFeatures[0].ShapeCopy, geometry);
// if (geometrys != null && !geometrys.IsEmpty)
// {
// bgFeatures[0].Shape = geometrys;
// bgFeatures[0].Store();
// rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
// }
//}
//else if (bgFeatures.Count > 1)
//{
// foreach (var item in bgFeatures)
// {
// List<IFeature> TempFeatures = FeatureAPI.Identify(item.ShapeCopy, dltbbg_Layer);
// //图形相邻与共边最长的图斑合并
// IFeature UnionFeature = null;
// var Unionlength = 0.00;
// foreach (IFeature ifeature in TempFeatures)
// {
// var length = FeatureAPI.LengthOfSide(item.ShapeCopy, ifeature.Shape);
// if (length > Unionlength)
// {
// Unionlength = length;
// UnionFeature = ifeature;
// }
// }
// if (UnionFeature != null)
// {
// IGeometry geometrys = FeatureAPI.Union(UnionFeature.ShapeCopy, item.ShapeCopy);
// if (geometrys != null && !geometrys.IsEmpty)
// {
// UnionFeature.Shape = geometrys;
// UnionFeature.Store();
// rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
// }
// }
// }
//}
//else
//{
// List<IFeature> TempFeatures = FeatureAPI.Identify(geometry, dltbbg_Layer);
// //图形相邻与共边最长的图斑合并
// IFeature UnionFeature = null;
// var Unionlength = 0.00;
// foreach (IFeature ifeature in TempFeatures)
// {
// var length = FeatureAPI.LengthOfSide(geometry, ifeature.Shape);
// if (length > Unionlength)
// {
// Unionlength = length;
// UnionFeature = ifeature;
// }
// }
// if (UnionFeature != null)
// {
// IGeometry geometrys = FeatureAPI.Union(UnionFeature.ShapeCopy, geometry);
// if (geometrys != null && !geometrys.IsEmpty)
// {
// UnionFeature.Shape = geometrys;
// UnionFeature.Store();
// rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
// }
// }
//}
#endregion
}
else //OBJECTID >-1的 需要将碎图斑擦除
{
//continue;
IFeature OriginFC = null;
try
{
if (Convert.ToInt32(BSM) > 0)
{
OriginFC = dltbbg_Layer.FeatureClass.GetFeature(BSM.ToInt());
}
}
catch (Exception ex) { throw; }
OriginFC.Shape = FeatureAPI.Difference(OriginFC.ShapeCopy, geometry);//擦除
OriginFC.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
List<IFeature> bgFeatures = FeatureAPI.Identify(geometry, dltbbg_Layer);
#region 碎图斑与相邻共边长的图斑合并
if (bgFeatures.Count > 1)
{
IFeature UnionFeature = null;
var Unionlength = 0.00;
foreach (IFeature ifeature in bgFeatures)
{
if (ifeature.OID == BSM.ToInt()) continue;
var length = FeatureAPI.LengthOfSide(ErrorFeature.ShapeCopy, ifeature.Shape);
if (length > Unionlength)
{
Unionlength = length;
UnionFeature = ifeature;
}
}
if (UnionFeature != null)
{
IGeometry geometrys = FeatureAPI.Union(UnionFeature.ShapeCopy, ErrorFeature.ShapeCopy);
if (geometrys != null && !geometrys.IsEmpty)
{
UnionFeature.Shape = geometrys;
UnionFeature.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
}
}
#endregion
//if (bgFeatures.Count > 1)
//{
// int idxDLBM = ErrorFeature.Fields.FindField("DLBM_1");
// string dl = ErrorFeature.Value[idxDLBM].ToTrim();
// ITopologicalOperator tempTopo = geometry as ITopologicalOperator;
// IPolyline tempLine = tempTopo.Boundary as IPolyline;
// var Length = tempLine.Length;
// int idxBgDLBM = dltbbg_Layer.FeatureClass.FindField("DLBM");
// foreach (IFeature ifeature in bgFeatures)
// {
// if (ifeature.OID == BSM.ToInt()) continue;
// string bgDL = ifeature.Value[idxBgDLBM].ToTrim();
// if (dl == bgDL)
// {
// var length = FeatureAPI.LengthOfSide(geometry, ifeature.Shape);
// if (length / Length > 0.3)
// {
// IGeometry geometrys = FeatureAPI.Union(ifeature.ShapeCopy, geometry);
// if (geometrys != null && !geometrys.IsEmpty)
// {
// ifeature.Shape = geometrys;
// ifeature.Store();
// rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
// }
// break;
// }
// }
// }
//}
//if (bgFeatures.Count == 1)
//{
// OriginFC.Shape = FeatureAPI.Difference(OriginFC.ShapeCopy, geometry);//擦除
// OriginFC.Store();
// rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
//}
//else if (bgFeatures.Count > 1)
//{
// //图形相邻与共边最长的图斑合并
// IFeature UnionFeature = null;
// var Unionlength = 0.00;
// foreach (IFeature ifeature in bgFeatures)
// {
// if (ifeature.OID == OBJECTID.ToInt()) continue;
// var length = FeatureAPI.LengthOfSide(geometry, ifeature.Shape);
// IPolyline polyline;
// ITopologicalOperator topoOper = geometry as ITopologicalOperator;
// polyline = topoOper.Intersect(ifeature.ShapeCopy, esriGeometryDimension.esriGeometry1Dimension) as IPolyline;
// if (polyline.IsEmpty)
// {
// }
// if (length > Unionlength)
// {
// Unionlength = length;
// UnionFeature = ifeature;
// }
// }
// if (UnionFeature != null)
// {
// IGeometry geometrys = FeatureAPI.Union(UnionFeature.ShapeCopy, geometry);
// if (geometrys != null && !geometrys.IsEmpty)
// {
// OriginFC.Shape = FeatureAPI.Difference(OriginFC.ShapeCopy, geometry);//擦除
// OriginFC.Store();
// UnionFeature.Shape = geometrys;
// UnionFeature.Store();
// rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
// }
// }
//}
}
}
else if (ErrorCode == "32074304000008")//基础地类图斑图层内部存在缝隙,根据错误图形,与相邻的 同一行政区的图形合并
{
IFeatureLayer CJDCQLayer = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("村级调查区");
try
{
//图形转化模式 默认大地坐标系4900
geometry = GeometryConvertHelper.ConvertWKTToIGeometry(ErrorArea);
geometry.SpatialReference = m_hookHelper.FocusMap.SpatialReference;
//geometry = IPolygonExtension.ToGeometry(ErrorArea, true, esriGeometryType.esriGeometryPolygon);
}
catch
{
geometry = IPolygonExtension.ToGeometry(ErrorArea, false, esriGeometryType.esriGeometryPolyline);
}
if (geometry == null || geometry.IsEmpty) continue;
List<IFeature> bgFeatures = FeatureAPI.Identify(geometry, JcTb_Layer);//相邻的基础地类图斑
List<IFeature> cjdcqFeatures = FeatureAPI.Identify2(geometry, CJDCQLayer);//图斑所在村级调查区
IFeature UnionFeature = null;
var Unionlength = 0.00;
foreach (IFeature ifeature in bgFeatures)
{
var length = FeatureAPI.LengthOfSide(geometry, ifeature.Shape);
if (length > Unionlength)
{
var cjdcq = FeatureAPI.Identify2(geometry, CJDCQLayer);//图斑所在村级调查区
if (cjdcqFeatures.Count == 1 && cjdcq.Count == 1 && cjdcqFeatures[0].OID == cjdcq[0].OID)
{
Unionlength = length;
UnionFeature = ifeature;
}
else if (cjdcqFeatures.Count >= 2)
{
rdbHelper.ExecuteSQL($"update DataCheckResults set ErrorName = '{ErrorName}(存在跨村界批量不处理)' where ID in ({ID}) ");
break;
}
}
}
if (UnionFeature != null)
{
try
{
if (geometry.GeometryType == esriGeometryType.esriGeometryPolyline)
{
//IGeometry Union = FeatureAPI.Union(UnionFeature.ShapeCopy, FeatureAPI.ConstructPolygonFromPolyline(geometry as IPolyline));
//UnionFeature.Shape = Union;
}
else if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon)
{
IGeometry Union = FeatureAPI.Union(UnionFeature.ShapeCopy, geometry);
UnionFeature.Shape = Union;
}
UnionFeature.Store();
rdbHelper.ExecuteSQL($" delete from DataCheckResults where ID={ID}");
}
catch (Exception ex)
{
LogAPI.Debug("基础数据库文件发生占用,可重启系统再试!异常信息如下:" + ex);
MessageHelper.ShowWarning("基础数据库文件发生占用,可重启系统再试!");
return;
}
}
}
else
{
DataTable ruleDt = rdbHelper.ExecuteDatatable("CheckingRule", string.Format($"SELECT * from CheckingRule where RuleCode = '{ErrorCode}' "), true);
if (ruleDt != null && ruleDt.Rows.Count > 0)
{
foreach (DataRow ruleRow in ruleDt.Rows)
{
string repairSql = ruleRow["RepairSQL"].ToString();
if (string.IsNullOrWhiteSpace(repairSql) || string.IsNullOrEmpty(repairSql)) continue;
IFeatureLayer errorFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(errorLayerEngish);
RepairEntity repairEntity = new RepairEntity
{
RepairSQL = repairSql,
LayerName = errorLayerEngish,
BSMList = new List<string>() { BSM },
IDList = new List<string>() { ID }
};
RepairEntity repair = repairEntities.Where(x => x.RepairSQL == repairSql && x.LayerName == errorLayerEngish).FirstOrDefault();
if (repair != null)
{
repair.BSMList.Add(BSM);
repair.IDList.Add(ID);
}
else
{
repairEntities.Add(repairEntity);
}
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex.Message + ex.StackTrace);
continue;
}
#endregion
}
if (repairEntities.Count > 0)
{
foreach (RepairEntity item in repairEntities)
{
//string newRepairSQL = item.RepairSQL.Replace("BSM =''", "BSM in ({1})");
string repairSql = string.Format(item.RepairSQL, item.LayerName, string.Join(",", item.BSMList.Select(x => $"'{x}'")), (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).CODE);
IFeatureLayer errorFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(item.LayerName);
(errorFeatureLayer as FeatureClass).Workspace.ExecuteSQL(repairSql);
rdbHelper.ExecuteSQL($"delete from DataCheckResults where ID in ({string.Join(",", item.IDList.Select(x => $"'{x}'"))}) ");
}
}
InitView(out bool isFinishd);
if (isFinishd)
{
this.CloseLoading();
MessageHelper.Show("修复完成!");
}
}
else
MessageHelper.ShowTips("没有可修复的数据!");
this.CloseLoading();
}
catch (Exception ex)
{
MessageHelper.Show("批量修复时发生错误,错误信息请查看系统日志!");
this.CloseLoading();
LogAPI.Debug("批量修复时发生异常,异常信息如下:");
LogAPI.Debug(ex.Message);
LogAPI.Debug(ex.StackTrace);
}
finally
{
this.CloseLoading();
(sender as Button).IsEnabled = true;
ExtensionShowWindow.MainWinForm.Enabled = true;
if (rdbHelper != null && rdbHelper.State != ConnectionState.Closed)
rdbHelper.DisConnect();
if (dltbbg_Layer != null)
Marshal.ReleaseComObject(dltbbg_Layer);
if (JcTb_Layer != null)
Marshal.ReleaseComObject(JcTb_Layer);
if (mErrLayer != null)
Marshal.ReleaseComObject(mErrLayer);
if (geometry != null)
Marshal.ReleaseComObject(geometry);
GC.Collect();
}
}
private List<IFeature> GetSplitFeatures(IFeature pF, IFeatureLayer dltbbg_Layer)
{
List<IFeature> result = new List<IFeature>();
try
{
List<IFeature> bgFeatures = FeatureAPI.Identify(pF.ShapeCopy, dltbbg_Layer);
if (bgFeatures.Count == 1)
{
result = bgFeatures;
}
else if (bgFeatures.Count > 1)
{
ITopologicalOperator topo = pF.ShapeCopy as ITopologicalOperator;
IPolyline tempLine = topo.Boundary as IPolyline;
//图形相邻与共边最长的图斑合并
//IFeature UnionFeature = null;
var Unionlength = 0.00;
List<IPolyline> lines = new List<IPolyline>();
IFeature tempFeature = null;
for (int i = 0; i < bgFeatures.Count; i++)
{
IGeometry geo1 = bgFeatures[i].ShapeCopy;
Unionlength = FeatureAPI.LengthOfSide(geo1, pF.ShapeCopy);
if (Unionlength < 0.0001)
{
continue;
}
tempFeature = bgFeatures[i];
topo = geo1 as ITopologicalOperator;
geo1 = topo.Boundary;
for (int j = i + 1; j < bgFeatures.Count; j++)
{
IGeometry geo2 = bgFeatures[j].ShapeCopy;
Unionlength = FeatureAPI.LengthOfSide(geo2, pF.ShapeCopy);
if (Unionlength < 0.0001)
{
continue;
}
IGeometry line1 = FeatureAPI.InterSect(geo1, geo2);
if (line1.IsEmpty)
continue;
lines.Add(line1 as IPolyline);
}
}
if (lines.Count == 0)
{
if (tempFeature != null)
result.Add(tempFeature);
return result;
}
List<IGeometry> SplitLines = new List<IGeometry>();
IPointCollection temps = pF.ShapeCopy as IPointCollection;
for (int i = 0; i < lines.Count; i++)
{
IPointCollection ps = lines[i] as IPointCollection;
IPolyline line = new PolylineClass();
line.FromPoint = ps.Point[1];
line.ToPoint = ps.Point[0];
IPoint newPoint = GeometryAPI.GetExtendedLinePoint(line, 1);
line.ToPoint = newPoint;
SplitLines.Add(line);
SplitLines.Add(lines[i]);
IPolyline line2 = new PolylineClass();
line2.FromPoint = ps.Point[ps.PointCount - 2];
line2.ToPoint = ps.Point[ps.PointCount - 1];
IPoint newPoint2 = GeometryAPI.GetExtendedLinePoint(line2, 1);
line2.ToPoint = newPoint2;
SplitLines.Add(line2);
}
IGeometry spGeo = FeatureAPI.MergeGeometry(SplitLines);
IFeatureEdit featureEdit = pF as IFeatureEdit;
try
{
MapsManager.Instance.MapService.DrawGraph(spGeo, true);
MapsManager.Instance.MapService.Zoom(spGeo);
//List<IFeature> list = SplitFeature(pF, spGeo as IPolyline);
//return list;
ESRI.ArcGIS.esriSystem.ISet newFeaturesSet = featureEdit.Split(spGeo);
if (newFeaturesSet != null)
{
newFeaturesSet.Reset();
IFeature pSplitFeature = null;
pSplitFeature = newFeaturesSet.Next() as IFeature;
while (pSplitFeature != null)
{
result.Add(pSplitFeature);
pSplitFeature = newFeaturesSet.Next() as IFeature;
}
}
}
catch (Exception ex)
{
return result;
}
}
return result;
}
catch (Exception ex)
{
return null;
}
}
private IPointCollection GetSplitFeatures(IFeature pF, IFeatureLayer dltbbg_Layer, IFeatureLayer pJcTb_Layer)
{
IPointCollection result = null;// new List<IFeature>();
try
{
//IPointCollection bgPoint = null;
{
List<IGeometry> lines = new List<IGeometry>();
List<IGeometry> points = new List<IGeometry>();
List<IFeature> bgFeatures = FeatureAPI.Identify(pF.ShapeCopy, pJcTb_Layer);
ITopologicalOperator eTopo = pF.ShapeCopy as ITopologicalOperator;
foreach (var item in bgFeatures)
{
ITopologicalOperator bgTopo = item.ShapeCopy as ITopologicalOperator;
IGeometry bound = bgTopo.Boundary;
IGeometry geo = eTopo.Intersect(bound, esriGeometryDimension.esriGeometry1Dimension);
if (!geo.IsEmpty && (geo as IPolyline).Length > 0.0001)
{
IPointCollection tempPs = geo as IPointCollection;
Dictionary<IPoint, int> pCount = new Dictionary<IPoint, int>();
for (int i = 0; i < tempPs.PointCount; i++)
{
List<IFeature> tempFs = FeatureAPI.Identify(tempPs.Point[i], pJcTb_Layer);
if (tempFs.Count > 0)
{
if (!pCount.ContainsKey(tempPs.Point[i]))
pCount.Add(tempPs.Point[i], tempFs.Count);
else
pCount[tempPs.Point[i]] = tempFs.Count;
}
}
int num = pCount.Max(m => m.Value);
lines.Add(geo);
continue;
}
if (lines.Count == 0)
{
geo = eTopo.Intersect(bound, esriGeometryDimension.esriGeometry0Dimension);
if (!geo.IsEmpty)
{
IPointCollection tempPs = geo as IPointCollection;
for (int i = 0; i < tempPs.PointCount; i++)
{
points.Add(tempPs.Point[i]);
}
}
}
}
if (lines.Count > 0)
{
IGeometry spGeo = FeatureAPI.MergeGeometry(lines);
//MapsManager.Instance.MapService.DrawGraph(spGeo, true);
//MapsManager.Instance.MapService.Zoom(spGeo);
result = spGeo as IPointCollection;
//foreach (var item in lines)
//{
// result.AddPoint((item as IPolyline).FromPoint);
// result.AddPoint((item as IPolyline).ToPoint);
//}
}
else
{
result = new PolylineClass();
foreach (var p in points)
{
result.AddPoint(p as IPoint);
}
}
}
return result;
}
catch (Exception ex)
{
return null;
}
}
private IPointCollection GetSplitFeatures2(IFeature pF, IFeatureLayer dltbbg_Layer, IFeatureLayer pJcTb_Layer)
{
IPointCollection result = null;// new List<IFeature>();
try
{
//IPointCollection bgPoint = null;
{
List<IGeometry> lines = new List<IGeometry>();
List<IGeometry> points = new List<IGeometry>();
List<IFeature> bgFeatures = FeatureAPI.Identify(pF.ShapeCopy, pJcTb_Layer);
ITopologicalOperator eTopo = pF.ShapeCopy as ITopologicalOperator;
IPointCollection resultLine = new PolylineClass();
{
IPointCollection tempPs = pF.ShapeCopy as IPointCollection;
if (tempPs.PointCount > 3)
{
tempPs.RemovePoints(tempPs.PointCount - 1, 1);
}
//if (tempPs.PointCount == 3)
//{
// tempPs.RemovePoints(1, 1);
// resultLine = new PolylineClass();
// for (int i = 0; i < tempPs.PointCount; i++)
// {
// resultLine.AddPoint(tempPs.Point[i]);
// }
// return resultLine;
//}
Dictionary<int, int> mDicCount = new Dictionary<int, int>();
int num = 0;
int idx = 0;
int bgNum = -1;
for (int i = 0; i < tempPs.PointCount; i++)
{
List<IFeature> tempFs = FeatureAPI.Identify(tempPs.Point[i], pJcTb_Layer);
List<IFeature> tempFs2 = FeatureAPI.Identify(tempPs.Point[i], dltbbg_Layer);
if (tempFs.Count > tempFs2.Count && num < tempFs.Count)
{
num = tempFs.Count;
if (resultLine.PointCount > 0)
resultLine.RemovePoints(resultLine.PointCount - 1, 1);
resultLine.AddPoint(tempPs.Point[i]);
}
//if ((tempFs.Count > 0 && tempFs2.Count == 0) || (tempFs.Count == bgFeatures.Count && tempFs2.Count != 0))
//{
// bgNum = tempFs2.Count;
// idx = i;
// resultLine.AddPoint(tempPs.Point[i]);
//}
}
//if (resultLine.PointCount == 1 && bgNum > 0)
//{
// tempPs.RemovePoints(idx, 1);
// tempPs.RemovePoints(tempPs.PointCount - 1, 1);
// resultLine = new PolylineClass();
// for (int i = 0; i < tempPs.PointCount; i++)
// {
// resultLine.AddPoint(tempPs.Point[i]);
// }
//}
}
return resultLine;
//foreach (var item in bgFeatures)
//{
// ITopologicalOperator bgTopo = item.ShapeCopy as ITopologicalOperator;
// IGeometry bound = bgTopo.Boundary;
// IGeometry geo = eTopo.Intersect(bound, esriGeometryDimension.esriGeometry1Dimension);
// if (!geo.IsEmpty && (geo as IPolyline).Length > 0.0001)
// {
// IPointCollection tempPs = geo as IPointCollection;
// Dictionary<IPoint, int> pCount = new Dictionary<IPoint, int>();
// for (int i = 0; i < tempPs.PointCount; i++)
// {
// List<IFeature> tempFs = FeatureAPI.Identify(tempPs.Point[i], pJcTb_Layer);
// if (tempFs.Count > 0)
// {
// if (!pCount.ContainsKey(tempPs.Point[i]))
// pCount.Add(tempPs.Point[i], tempFs.Count);
// else
// pCount[tempPs.Point[i]] = tempFs.Count;
// }
// }
// int num = pCount.Max(m => m.Value);
// lines.Add(geo);
// continue;
// }
// if (lines.Count == 0)
// {
// geo = eTopo.Intersect(bound, esriGeometryDimension.esriGeometry0Dimension);
// if (!geo.IsEmpty)
// {
// IPointCollection tempPs = geo as IPointCollection;
// for (int i = 0; i < tempPs.PointCount; i++)
// {
// points.Add(tempPs.Point[i]);
// }
// }
// }
//}
//if (lines.Count > 0)
//{
// IGeometry spGeo = FeatureAPI.MergeGeometry(lines);
// //MapsManager.Instance.MapService.DrawGraph(spGeo, true);
// //MapsManager.Instance.MapService.Zoom(spGeo);
// result = spGeo as IPointCollection;
// //foreach (var item in lines)
// //{
// // result.AddPoint((item as IPolyline).FromPoint);
// // result.AddPoint((item as IPolyline).ToPoint);
// //}
//}
//else
//{
// result = new PolylineClass();
// foreach (var p in points)
// {
// result.AddPoint(p as IPoint);
// }
//}
}
return result;
}
catch (Exception ex)
{
return null;
}
}
private bool RepairBgtbForPoint(IFeature pF, IFeatureLayer dltbbg_Layer, IPointCollection pPs)
{
bool result = false;// new List<IFeature>();
try
{
{
List<IFeature> bgFeatures = FeatureAPI.Identify(pF.ShapeCopy, dltbbg_Layer);
ITopologicalOperator eTopo = pF.ShapeCopy as ITopologicalOperator;
IPolyline Errline = pPs as IPolyline;
if (Errline.IsEmpty) return false;
foreach (var item in bgFeatures)
{
IPointCollection bgPs = item.ShapeCopy as IPointCollection;
for (int j = 0; j < bgPs.PointCount; j++)
{
//IPoint temp1 = bgPs.Point[j];
IPoint temp1 = null;// GeometryAPI.GetCrossPnt(Errline, bgPs.Point[j]);
if (Errline.Length == 0)
{
temp1 = Errline.FromPoint;
}
else
{
temp1 = GeometryAPI.GetCrossPnt(Errline, bgPs.Point[j]);
}
if (temp1 == null) continue;
IPolyline line = new PolylineClass();
line.FromPoint = bgPs.Point[j];
line.ToPoint = temp1;
line.SpatialReference = item.ShapeCopy.SpatialReference;
if ((line.Length < (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).XYResolution * 1000 && line.Length > (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).XYResolution))
{
bgPs.UpdatePoint(j, temp1);
}
}
IPolygon newShp = bgPs as IPolygon;
ITopologicalOperator newTopo = newShp as ITopologicalOperator;
newTopo.Simplify();
item.Shape = newShp;
item.Store();
}
}
return result;
}
catch (Exception ex)
{
return false;
}
}
private void RepairErrorResults()
{
try
{
this.ShowLoading($"正在进行【{_CheckName}】数据修复...", 0, 0);
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
DataTable dicDt = rdbHelper.ExecuteDatatable("DataCheckResults", string.Format($"SELECT * from DataCheckResults"), true);
if (dicDt == null) return;
foreach (DataRow row in dicDt.Rows)
{
string errorCode = row["ErrorCode"].ToString();
string errorLayerEngish = row["ErrorLayer"].ToString();
string errorBSM = row["BSM"].ToString();
string errorDesc = row["ErrorName"].ToString();
string objectId = row["ID"].ToString();
DataTable ruleDt = rdbHelper.ExecuteDatatable("CheckingRule", string.Format($"SELECT * from CheckingRule where RuleCode = '{errorCode}' "), true);
if (ruleDt == null) return;
foreach (DataRow ruleRow in ruleDt.Rows)
{
string repairSql = ruleRow["RepairSQL"].ToString();
if (string.IsNullOrWhiteSpace(repairSql) || string.IsNullOrEmpty(repairSql)) continue;
repairSql = string.Format(repairSql, errorLayerEngish, errorBSM, (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).CODE);
IFeatureLayer errorFeatureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(errorLayerEngish);
(errorFeatureLayer as FeatureClass).Workspace.ExecuteSQL(repairSql);
string dbPa = System.IO.Path.Combine((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir, "DataCheckrResult.db");
string sql = string.Format("update DataCheckResults set ErrorType='已修复' where ID = '{0}'", objectId);
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPa, sql, null);
rdbHelper.ExecuteSQL($"delete from DataCheckResults where ID = '{objectId}' ");
}
}
// 页面刷新
InitView(out bool isFinishd);
this.CloseLoading();
}
catch (Exception ex)
{
this.CloseLoading();
LogAPI.Debug(ex.Message);
MessageHelper.ShowTips($"批量修复【{_CheckName}】失败,请查看日志!");
}
}
#region RepairGeometry
private IGeometry RepairGeometry(IFeature feature, IGeometry geometry)
{
IGeometry geometrys = null;
try
{
IPolyline tempLine = geometry as IPolyline;
IPoint p1 = GeometryAPI.GetExtendedLinePoint(tempLine, 50);
tempLine.ToPoint = p1;
IPoint p2 = GeometryAPI.GetExtendedLinePoint(tempLine, -50);
tempLine.FromPoint = p2;
geometry = tempLine;
geometrys = feature.ShapeCopy;
IPointCollection ps = geometry as IPointCollection;
IPointCollection reshapePath = new PathClass();
reshapePath.AddPointCollection(ps);
IGeometryCollection geometryCollection = feature.ShapeCopy as IGeometryCollection;
IRing ring = null;
for (int i = 0; i < geometryCollection.GeometryCount; i++)
{
ring = geometryCollection.get_Geometry(i) as IRing;
ring.Reshape(reshapePath as IPath);
}
geometrys = geometryCollection as IGeometry;
if (geometrys == null || geometrys.IsEmpty)
{
return geometrys;
}
}
catch (Exception ex)
{
LogAPI.Debug($"RepairGeometry异常,异常信息如下:{ex.Message}");
LogAPI.Debug(ex);
}
return geometrys;
}
#endregion
private void RepairView_Closed(object sender, EventArgs e)
{
repairView = null;
}
/// <summary>
/// 变更结果导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnBatchImprot_Click(object sender, RoutedEventArgs e)
{
try
{
(sender as Button).IsEnabled = false;
ExtensionShowWindow.MainWinForm.Enabled = false;
WorkspaceAPI wsAPI = null;
IWorkspaceFactory pSaveFct = null;
IWorkspaceName workspaceName = null;
pSaveFct = new FileGDBWorkspaceFactory();
IFeatureLayer dltbbg_Layer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTBBG");
ISpatialReference pSR = null;
string dbPath = System.IO.Path.GetDirectoryName((MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).GetProjFilePath()) + @"\BGTJ.sqlite";
//错误地类图斑ID与错误信息
//DataTable dtFJ = SQLiteDBOperate.Instance.ExceDataTable(dbPath, $"select * from DataCheckResults where ErrorLayer='{m_Check.DataCheckName}' ");
DataTable dtFJ = SQLiteDBOperate.Instance.ExceDataTable(dbPath, $"select * from DataCheckResults");
if (dtFJ == null || dtFJ.Rows.Count == 0)
{
MessageHelper.ShowTips("当前无检查结果数据导出!");
return;
}
string saveFile = "";
//弹出文件选择对话框
System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
this.ShowLoading("进行检查结果数据导出……", 0, 0);
saveFile = dialog.SelectedPath;
string gdbFileName = "检查数据导出结果" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".gdb";//创建储存的GDB文件
string path = System.IO.Path.Combine(saveFile, gdbFileName);
workspaceName = pSaveFct.Create(saveFile, gdbFileName, null, 0);//创建数据库
wsAPI = new WorkspaceAPI(path, WorkspaceTypeEnum.GDBFile);
pSR = (dltbbg_Layer.FeatureClass as IGeoDataset).SpatialReference;
GeoDBAPI.CreateFields(dltbbg_Layer.FeatureClass.Fields, out IFields fields);
//括扑/城镇村检查结果导出
IFeatureClass KPCZC_featureClass = wsAPI.CreateFeatureClass("Check_Result", pSR, null).FeatureClass;//创建数据集
IFeatureClassAPI KPCZC_FcAPI = new FeatureClassAPI(KPCZC_featureClass);
IFeatureCursor KPCZC_featureCursor = KPCZC_featureClass.Insert(true);
KPCZC_FcAPI.AddField("SHAPE", esriFieldType.esriFieldTypeGeometry, "SHAPE");
KPCZC_FcAPI.AddField("OBJECTID", esriFieldType.esriFieldTypeString, "OBJECTID");
KPCZC_FcAPI.AddField("ErrorType", esriFieldType.esriFieldTypeString, "错误类型");
KPCZC_FcAPI.AddField("ErrorCode", esriFieldType.esriFieldTypeString, "错误代码");
KPCZC_FcAPI.AddField("ErrorDesc", esriFieldType.esriFieldTypeString, "错误信息");
KPCZC_FcAPI.AddField("ErrorData", esriFieldType.esriFieldTypeString, "ErrorData");
IFeatureBuffer featureBuffer = KPCZC_featureClass.CreateFeatureBuffer();
int ErrorTypeIndex = featureBuffer.Fields.FindField("ErrorType");
int ErrorCodeIndex = featureBuffer.Fields.FindField("ErrorCode");
int ErrorDescIndex = featureBuffer.Fields.FindField("ErrorDesc");
int ErroDataIndex = featureBuffer.Fields.FindField("ErrorData");
IGeometry geo = null;
for (int i = 0; i < dtFJ.Rows.Count; i++)
{
this.UpdateMsg("检查数据导出已处理【" + i + "/" + dtFJ.Rows.Count + "】");
try
{
geo = FeatureAPI.ConstructPolygonFromPolyline(IPolygonExtension.ToGeometry(dtFJ.Rows[i]["ErrorArea"].ToString(), true, esriGeometryType.esriGeometryPolyline) as IPolyline);
}
catch
{
geo = IPolygonExtension.ToGeometry(dtFJ.Rows[i]["ErrorArea"].ToString(), false, esriGeometryType.esriGeometryPolygon);
}
if (geo != null)
{
featureBuffer.Shape = geo;
featureBuffer.set_Value(ErrorTypeIndex, dtFJ.Rows[i]["RuleType"].ToString().Trim());
featureBuffer.set_Value(ErrorCodeIndex, dtFJ.Rows[i]["ErrorCode"].ToString().Trim());
featureBuffer.set_Value(ErrorDescIndex, dtFJ.Rows[i]["ErrorName"].ToString().Trim());
featureBuffer.set_Value(ErroDataIndex, dtFJ.Rows[i]["ErrorLayer"].ToString().Trim() + ",标识码_" + dtFJ.Rows[i]["BSM"].ToString().Trim());
KPCZC_featureCursor.InsertFeature(featureBuffer);
featureBuffer = KPCZC_featureClass.CreateFeatureBuffer();
KPCZC_featureCursor.Flush();
}
}
KPCZC_featureCursor.Flush();
this.CloseLoading();
MessageHelper.ShowTips("检查结果导出成功!");
}
}
catch (Exception ex)
{
this.CloseLoading();
LogAPI.Debug(ex);
MessageHelper.ShowTips("检查结果导出异常:" + ex.Message);
}
finally
{
(sender as Button).IsEnabled = true;
ExtensionShowWindow.MainWinForm.Enabled = true;
}
}
/// <summary>
/// 加载检查结果视图数据
/// </summary>
private void LoadData()
{
try
{
if (m_Check != null)
{
m_Check.StartLoadData(null);
}
}
catch (Exception ex)
{
MessageHelper.ShowError("加载检查结果视图数据失败,请查看日志!");
LogAPI.Debug(ex.Message);
}
}
public void DataCheckByThread(CheckParametr pParm)
{
try
{
IDataCheck = IdataChecks.FirstOrDefault(x => x.IDataCheckName == pParm.IDataCheckName);
if (IDataCheck != null)
{
if (pParm.DataSource as IFeature != null)
{
ThreadManager2.QueueUserWorkItem(new WaitCallback(IDataCheck.FeatureCheck), pParm, null);
}
else if (pParm.DataSource as IFeatureClass != null)
{
ThreadManager2.QueueUserWorkItem(new WaitCallback(IDataCheck.FeatureCheck), pParm, null);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void DataCheck(CheckParametr pParm)
{
try
{
IDataCheck = IdataChecks.FirstOrDefault(x => x.IDataCheckName == pParm.IDataCheckName);
if (IDataCheck != null)
{
IDataCheck.DataCheckComplate += _CheckInterface_InspectionCompleted;
if (pParm.DataSource as IFeature != null)
{
IDataCheck.FeatureCheck(pParm);
}
else if (pParm.DataSource as IFeatureClass != null)
{
IDataCheck.FeatureClassCheck(pParm);
}
IDataCheck.DataCheckComplate -= _CheckInterface_InspectionCompleted;
}
}
catch (Exception ex)
{
throw ex;
}
}
void _CheckInterface_InspectionCompleted(List<CheckResult> Result, CheckParametr pParm)
{
try
{
string dbPath = string.Empty;
IFeature feature = pParm.DataSource as IFeature;
try
{
//更新界面逻辑
ProjectInfo projectInfo = (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo);
dbPath = System.IO.Path.Combine(projectInfo.ProjDir, "DataCheckrResult.db");
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, $"CREATE TABLE IF NOT exists DataCheckResults (`ID` INTEGER, `ErrorLayer` TEXT,`OBJECTID` TEXT,`ErrorType` TEXT,`ErrorCode` TEXT,`ErrorDesc` TEXT,`ErrorData` TEXT,`ErrorArea` TEXT,`ErrorMJ` NUMERIC,`Synopsis` TEXT,`ErrorCategory` TEXT ,PRIMARY KEY(`ID`))", null);
if (feature != null)
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, $"delete from DataCheckResults WHERE OBJECTID='{feature.OID}' ;", null);//删除当前数据相关的核查结果
else
SQLiteDBOperate.Instance.ExecuteNonQuery(dbPath, $"delete from DataCheckResults where ErrorLayer='{pParm.IDataCheckName}' and ErrorCategory='{pParm.CheckType}' ;", null);
if (pParm.CheckResults == null) return;
if (pParm.CheckResults.Count == 0) return;
List<string> sqlList = new List<string>();
foreach (var item in pParm.CheckResults)
{
sqlList.Add(string.Format("INSERT INTO DataCheckResults (ErrorLayer,OBJECTID,ErrorType,ErrorCode,ErrorDesc,ErrorArea,Synopsis,ErrorCategory) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", item.ErrorLayer, item.ObjectID, item.ErrorType, item.ErrorCode, item.ErrorDesc, item.ErrorArea, item.Synopsis, item.ErrorCategory));
}
InsertSQLiteData(dbPath, sqlList);
}
catch (Exception ex)
{
LogAPI.Debug("批量插入SQLite数据(地址:" + dbPath + ") 执行失败,异常原因: " + ex.Message + " ; ");
throw ex;
}
}
catch (Exception ex)
{
throw ex;
}
}
#region GetUnionResult
/// <summary>
/// GetUnionResult
/// </summary>
/// <param name="firstFeatureClass">变更图斑</param>
/// <param name="secondFeatureClass">基础地类图斑</param>
private List<string> GetUnionResult(IFeatureClass DLTBBGFc, IFeatureLayer JC_DLTBFc, string RuleCode, string TempfilePath)
{
GPParamClass paramClass = null;
IFeatureLayer Temp_Union = null;
//IFeatureLayer SelectFeatureLayer = null;
IFeatureLayer multipartToSingleFeatureLayer = null;
List<string> sqlList = new List<string>();
ProjectInfo ProjInfo = null;
try
{
if (DLTBBGFc == null || DLTBBGFc.FeatureCount(null) == 0 || JC_DLTBFc == null || JC_DLTBFc.FeatureClass.FeatureCount(null) == 0)
{
return sqlList;
}
ProjInfo = MapsManager.Instance.CurrProjectInfo as ProjectInfo;
//paramClass = new GPParamClass()
//{
// Tolerance = "0.0001",
// FirstFeatureLayer = JC_DLTBFc,
// SecondFeatureClass = DLTBBGFc,
// IsGetOutPutFeature = true,
//};
//GeoprocessorHelper.SelectLayerByLocationAnalysis(paramClass, "INTERSECT", ref SelectFeatureLayer);
paramClass = new GPParamClass()
{
FirstFeatureLayer = new FeatureLayerClass() { FeatureClass = DLTBBGFc },
SecondFeatureLayer = JC_DLTBFc,
OutFeatureClassPath = $"{TempfilePath}\\Temp_Union",
IsGetOutPutFeature = true,
PreserveAttributes = "ALL"
};
GeoprocessorHelper.UnionAnalysis(paramClass, ref Temp_Union, ProjInfo.XYResolution.ToString());
paramClass = new GPParamClass();
paramClass.FirstFeatureLayer = Temp_Union;
paramClass.OutFeatureClassPath = $"{TempfilePath}\\Multipart";
paramClass.IsGetOutPutFeature = true;
GeoprocessorHelper.MultipartToSinglePath(paramClass, ref multipartToSingleFeatureLayer);
if (multipartToSingleFeatureLayer.FeatureClass != null)
{
IFeatureCursor pCursor = multipartToSingleFeatureLayer.FeatureClass.Search(new QueryFilterClass() { SubFields = $"OBJECTID,FID_DLTBBG,BSM,SHAPE,SHAPE_Area", WhereClause = "SHAPE_Area<0.1" }, true);
IFeature feature = null;
var iFID_DLTBBG = multipartToSingleFeatureLayer.FeatureClass.FindField("FID_DLTBBG");
var iBSM = multipartToSingleFeatureLayer.FeatureClass.FindField("BSM");
while ((feature = pCursor.NextFeature()) != null)
{
var FID_DLTBBG = feature.Value[iFID_DLTBBG].ToTrim();
var BSM = feature.Value[iBSM].ToTrim();
IGeometry geometry = feature.ShapeCopy;
ITopologicalOperator topo = geometry as ITopologicalOperator;
topo.Simplify();
if (geometry.IsEmpty) continue;
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea,MultipartOID,RepairfilePath) VALUES ('{FID_DLTBBG}', '{BSM}', 'DLTBBG', '{RuleCode}', '变更图斑与基础库图斑不套合,且碎图斑面积小于0.1','图形拓扑','{feature.Shape.ToJson()}',{feature.OID},'{TempfilePath}');");
if (feature != null)
Marshal.ReleaseComObject(feature);
}
}
}
catch (Exception ex)
{
LogAPI.Debug($"GetUnionResult执行错误:{ex.Message}");
LogAPI.Debug(ex);
}
finally
{
if (Temp_Union != null)
Marshal.ReleaseComObject(Temp_Union);
if (multipartToSingleFeatureLayer != null)
Marshal.ReleaseComObject(multipartToSingleFeatureLayer);
}
return sqlList;
}
#region DelectDirect
private static void DelectDirect(string srcPath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
else
{
File.Delete(i.FullName); //删除指定文件
}
}
}
catch (Exception ex)
{
//MessageHelper.ShowWarning("工程目录文件有占用,请退出占用后重试!");
LogAPI.Debug("工程目录文件有占用,请退出占用后重试!" + ex);
}
}
#endregion
#region 创建临时数据
private string CreateTempfile(string gdbName)
{
IWorkspaceFactory pFtWsFct = null;
IDataCatalogService _DataCatalog = null;
try
{
string gdbFolder = (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ProjDir + "\\DataCheck";
if (!Directory.Exists(gdbFolder))
Directory.CreateDirectory(gdbFolder);
PluginServiceInterface.CommonHelper.DelectDir(gdbFolder);
pFtWsFct = new FileGDBWorkspaceFactory();
string gdbFileName = Guid.NewGuid().ToString();
string path = System.IO.Path.Combine(gdbFolder, gdbFileName);
string BGDatabasepath = string.Empty;
string jcfcName = string.Empty;
if (gdbName == "BGDB")
BGDatabasepath = (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).BGDatabase;
else if (gdbName == "ZLDB")
BGDatabasepath = (MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).ZLDatabase;
else
{
if (_DataCatalog == null)
_DataCatalog = BundleRuntime.Instance.GetFirstOrDefaultService<IDataCatalogService>();
if (_DataCatalog.CurrentLayers is LayerCfg)
{
LayerCfg ncsj = (_DataCatalog.CurrentLayers as LayerCfg).Layers.FirstOrDefault(f => f.LayerName == "年初数据" && f.LayerType == EnumLayerType.GroupLayer);
List<LayerCfg> NcList = ncsj.GetAllItem();
LayerCfg _JcTBLayerInfo = NcList.FirstOrDefault(f => f.LayerName == "地类图斑");
if (_JcTBLayerInfo != null)
{
var sp = _JcTBLayerInfo.FcPath.Split('\\');
jcfcName = sp[sp.Length - 1];
BGDatabasepath = _JcTBLayerInfo.FcPath;
}
}
}
if (Directory.Exists(BGDatabasepath))
{
if (!string.IsNullOrEmpty(jcfcName))
TempfilePath = $"{path}\\{jcfcName}";
else
TempfilePath = $"{path}\\{gdbName}.gdb";
CopyDirectory(BGDatabasepath, TempfilePath, true);
}
}
catch (Exception ex)
{
throw ex;
}
(MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo).DataCheckPath = TempfilePath;
Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
return TempfilePath;
}
/// <summary>
/// 拷贝模板gdb文件夹
/// </summary>
/// <param name="SourcePath"></param>
/// <param name="DestinationPath"></param>
/// <param name="overwriteexisting"></param>
public static void CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
{
try
{
SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
if (Directory.Exists(SourcePath))
{
if (Directory.Exists(DestinationPath) == false)
Directory.CreateDirectory(DestinationPath);
foreach (string fls in Directory.GetFiles(SourcePath))
{
FileInfo flinfo = new FileInfo(fls);
flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
}
foreach (string drs in Directory.GetDirectories(SourcePath))
{
DirectoryInfo drinfo = new DirectoryInfo(drs);
CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#endregion
#region GetTopology
private List<string> GetTopology(string TempfilePath, string LayerName, string ErrorCode, string ErrorName)
{
IEnvelope envelope = null;
string topologyName = $"TopologyCheck_{LayerName}";
try
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(TempfilePath, WorkspaceTypeEnum.GDBFile);
var featureClassAPI = workspaceAPI.OpenFeatureClass(LayerName);
TopologyVerification(topologyName, featureClassAPI.FeatureClass, new List<esriTopologyRuleType> { esriTopologyRuleType.esriTRTAreaNoOverlap }, ref envelope);
return FindAllError(topologyName, envelope, featureClassAPI.FeatureClass, LayerName, ErrorCode, ErrorName);
}
catch (Exception ex)
{
throw ex;
}
}
#region checkTopologyError
public List<string> FindAllErrorFeatures(string topologyName, IEnvelope searchExtent, IFeatureClass DLTBBG)
{
List<string> sqlList = new List<string>();
IFeatureDataset featureDataset = DLTBBG.FeatureDataset;
ITopologyContainer topologyContainer = (ITopologyContainer)featureDataset;
ITopology topology = topologyContainer.get_TopologyByName(topologyName);
//获取坐标系
IErrorFeatureContainer errorFeatureContainer = (IErrorFeatureContainer)topology;
IGeoDataset geoDataset = (IGeoDataset)topology;
ISpatialReference spatialReference = geoDataset.SpatialReference;
ITopologyRuleContainer topologyRuleContainer = (ITopologyRuleContainer)topology;
//遍历拓扑规则
IEnumRule enumRule = topologyRuleContainer.Rules;
enumRule.Reset();
ESRI.ArcGIS.Geodatabase.IRule rule = null;
List<string> bsmlist = new List<string>();
while ((rule = enumRule.Next()) != null)
{
//获取当前拓扑规则的拓扑错误并遍历
ITopologyRule topologyRule = (ITopologyRule)rule;
IEnumTopologyErrorFeature enumTopologyErrorFeature = errorFeatureContainer.get_ErrorFeatures(spatialReference, topologyRule, searchExtent, true, true);
ITopologyErrorFeature topologyErrorFeature = null;
while ((topologyErrorFeature = enumTopologyErrorFeature.Next()) != null)
{
IFeature pFeature = topologyErrorFeature as IFeature;
if (pFeature != null && !pFeature.Shape.IsEmpty)
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea,RepairfilePath) VALUES ('{topologyErrorFeature.OriginOID}', '{topologyErrorFeature.OriginOID}-{topologyErrorFeature.DestinationOID}', 'DLTBBG', '32074304000007', '变更图斑要素存在重叠','图形拓扑','{pFeature.Shape.ToJson()}','{TempfilePath}');");
}
}
}
//try
//{
// IDataset pDatasetTemp = (IDataset)topology;
// pDatasetTemp.Delete();
// Marshal.ReleaseComObject(pDatasetTemp);
//}
//catch { }
return sqlList;
}
/// <summary>
/// 检查要素层中存在的拓扑错误
/// </summary>
/// <param name="wsPath">工作空间名称</param>
/// <param name="dsPath">数据集名称</param>
/// <param name="feaPath">要素类名称</param>
/// <param name="topologyName">拓扑要素层名,拓扑检查结果记录在该层中</param>
public void checkTopologyError(string topologyName, IFeatureClass DLTBBG, ref IEnvelope envelope)
{
//1. 打开数据集文件
IWorkspace workspace = (DLTBBG as FeatureClass).Workspace;
//2. 打开数据集文件
IFeatureDataset featureDataset = DLTBBG.FeatureDataset;
//3. 向拓扑集中添加要素层
IFeatureClass LRDLlayer = DLTBBG;
//4. 设置拓扑处理对数据集的独占权限
ISchemaLock schemaLock = (ISchemaLock)featureDataset;
IWorkspaceFactory2 ipWsFactory = new FileGDBWorkspaceFactoryClass();
ITopologyContainer2 topologyContainer = featureDataset as ITopologyContainer2;
//判断拓扑是否存在
bool bTopExists = (featureDataset.Workspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTTopology, topologyName);
if (bTopExists)
{
ITopology topologyTemp = topologyContainer.get_TopologyByName(topologyName);
IDataset pDatasetTemp = (IDataset)topologyTemp;
pDatasetTemp.Delete();//删除拓扑
Marshal.ReleaseComObject(pDatasetTemp);
}
//关闭资源锁定
IWorkspaceFactoryLockControl ipWsFactoryLock;
ipWsFactoryLock = (IWorkspaceFactoryLockControl)ipWsFactory;
if (ipWsFactoryLock.SchemaLockingEnabled)
{
ipWsFactoryLock.DisableSchemaLocking();
}
try
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
//5. 拓扑处理
//5.1 创建拓扑容器
//5.2 向拓扑容器中添加拓扑结果层
ITopology2 topology = topologyContainer.CreateTopology(topologyName, topologyContainer.DefaultClusterTolerance, -1, "") as ITopology2;
//5.3 添加参与拓扑运算的数据层
topology.AddClass(LRDLlayer, 5, 1, 1, false);
//5.4 添加拓扑规则
AddRuleToTopology(topology, esriTopologyRuleType.esriTRTAreaNoOverlap, "图层内部面和面之间不允许重叠", LRDLlayer, null);
//5.5 拓扑验证
IGeoDataset geoDataset = (IGeoDataset)topology;
envelope = geoDataset.Extent;
ValidateTopology(topology, envelope);
}
catch (COMException comExc)
{
throw new Exception(String.Format("Error creating topology: {0} Message: {1}", comExc.ErrorCode, comExc.Message), comExc);
}
finally
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}
}
public void AddRuleToTopology(ITopology topology, esriTopologyRuleType ruleType, String ruleName, IFeatureClass featureClass, IFeatureClass destinationClass)
{
ITopologyRule topologyRule = new TopologyRuleClass();
topologyRule.TopologyRuleType = ruleType;
topologyRule.Name = ruleName;
topologyRule.OriginClassID = featureClass.FeatureClassID;
topologyRule.AllOriginSubtypes = true;
if (destinationClass != null)
{
topologyRule.DestinationClassID = destinationClass.FeatureClassID;
topologyRule.AllDestinationSubtypes = true;
}
ITopologyRuleContainer topologyRuleContainer = (ITopologyRuleContainer)topology;
if (topologyRuleContainer.get_CanAddRule(topologyRule))
{
topologyRuleContainer.AddRule(topologyRule);
}
else
{
throw new ArgumentException(string.Format("不能添加{0}规则到拓扑里面,请检查此规则是否正确。", ruleName));
}
}
public void ValidateTopology(ITopology topology, IEnvelope envelope)
{
try
{
IPolygon locationPolygon = new PolygonClass();
ISegmentCollection segmentCollection = (ISegmentCollection)locationPolygon;
segmentCollection.SetRectangle(envelope);
IPolygon polygon = topology.get_DirtyArea(locationPolygon);
IEnvelope areaToValidate = polygon.Envelope;
IEnvelope areaValidated = topology.ValidateTopology(areaToValidate);
locationPolygon.Close();
polygon.Close();
}
catch (Exception ex)
{
LogAPI.Debug("校验括扑异常:" + ex);
}
}
#endregion
#endregion
#region GetTopology_DLTB
/// <summary>
/// //基础地类图斑重叠,缝隙
/// </summary>
/// <param name="ErrorCode">规则编码</param>
/// <returns></returns>
private List<string> GetTopology_DLTB(string ErrorCode)
{
IEnvelope envelope = null;
string topologyName = "TopologyCheck_DLTB";
try
{
IFeatureLayer JC_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName("DLTB");
TopologyVerification(topologyName, JC_featureLayer.FeatureClass, new List<esriTopologyRuleType> { esriTopologyRuleType.esriTRTAreaNoOverlap, esriTopologyRuleType.esriTRTAreaNoGaps }, ref envelope);
//checkTopologyError_DLTB(topologyName, dltb.FeatureClass, ref envelope);
return FindAllError(topologyName, envelope, JC_featureLayer.FeatureClass, "DLTB", ErrorCode, "基础地类图斑");//FindAllErrorFeatures_DLTB(topologyName, dltb.FeatureClass, envelope);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// //基础地类图斑重叠,缝隙
/// </summary>
/// <param name="ErrorCode">规则编码</param>
/// <returns></returns>
private List<string> GetTopology_DLTBBG(string ErrorCode, string Layername)
{
IEnvelope envelope = null;
string topologyName = $"TopologyCheck_{Layername}";
try
{
IFeatureLayer JC_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(Layername);
TopologyVerification(topologyName, JC_featureLayer.FeatureClass, new List<esriTopologyRuleType> { esriTopologyRuleType.esriTRTAreaNoOverlap }, ref envelope);
//checkTopologyError_DLTB(topologyName, dltb.FeatureClass, ref envelope);
return FindAllError(topologyName, envelope, JC_featureLayer.FeatureClass, Layername, ErrorCode, Layername);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 检查要素层中存在的拓扑错误
/// </summary>
/// <param name="wsPath">工作空间名称</param>
/// <param name="dsPath">数据集名称</param>
/// <param name="feaPath">要素类名称</param>
/// <param name="topologyName">拓扑要素层名,拓扑检查结果记录在该层中</param>
public void checkTopologyError_DLTB(string topologyName, IFeatureClass JCFC, ref IEnvelope envelope)
{
//IFeatureLayer JCFC = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("地类图斑");
//1. 打开数据集文件
IWorkspace workspace = (JCFC as FeatureClass).Workspace;
//2. 打开数据集文件
IFeatureDataset featureDataset = JCFC.FeatureDataset;
//3. 向拓扑集中添加要素层
IFeatureClass LRDLlayer = JCFC;
//4. 设置拓扑处理对数据集的独占权限
ISchemaLock schemaLock = (ISchemaLock)featureDataset;
IWorkspaceFactory2 ipWsFactory = new FileGDBWorkspaceFactoryClass();
ITopologyContainer2 topologyContainer = featureDataset as ITopologyContainer2;
//判断拓扑是否存在
bool bTopExists = (featureDataset.Workspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTTopology, topologyName);
if (bTopExists)
{
ITopology topologyTemp = topologyContainer.get_TopologyByName(topologyName);
IDataset pDatasetTemp = (IDataset)topologyTemp;
pDatasetTemp.Delete();//删除拓扑
Marshal.ReleaseComObject(pDatasetTemp);
}
//关闭资源锁定
IWorkspaceFactoryLockControl ipWsFactoryLock;
ipWsFactoryLock = (IWorkspaceFactoryLockControl)ipWsFactory;
if (ipWsFactoryLock.SchemaLockingEnabled)
{
ipWsFactoryLock.DisableSchemaLocking();
}
try
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
//5. 拓扑处理
//5.1 创建拓扑容器
//5.2 向拓扑容器中添加拓扑结果层
ITopology2 topology = topologyContainer.CreateTopology(topologyName, topologyContainer.DefaultClusterTolerance, -1, "") as ITopology2;
//5.3 添加参与拓扑运算的数据层
topology.AddClass(LRDLlayer, 5, 1, 1, false);
//5.4 添加拓扑规则
AddRuleToTopology(topology, esriTopologyRuleType.esriTRTAreaNoOverlap, "图层内部面和面之间不允许重叠", LRDLlayer, null);
AddRuleToTopology(topology, esriTopologyRuleType.esriTRTAreaNoGaps, "图层内部面和面之间不允许存在缝隙", LRDLlayer, null);
//5.5 拓扑验证
IGeoDataset geoDataset = (IGeoDataset)topology;
envelope = geoDataset.Extent;
ValidateTopology(topology, envelope);
}
catch (COMException comExc)
{
throw new Exception(String.Format("Error creating topology: {0} Message: {1}", comExc.ErrorCode, comExc.Message), comExc);
}
finally
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}
}
public List<string> FindAllErrorFeatures_DLTB(string topologyName, IFeatureClass JCFC, IEnvelope searchExtent)
{
List<string> sqlList = new List<string>();
//IFeatureLayer JCFC = MapsManager.Instance.MapService.GetFeatureLayerByLayerName("地类图斑");
IFeatureDataset featureDataset = JCFC.FeatureDataset;
ITopologyContainer topologyContainer = (ITopologyContainer)featureDataset;
ITopology topology = topologyContainer.get_TopologyByName(topologyName);
//获取坐标系
IErrorFeatureContainer errorFeatureContainer = (IErrorFeatureContainer)topology;
IGeoDataset geoDataset = (IGeoDataset)topology;
ISpatialReference spatialReference = geoDataset.SpatialReference;
ITopologyRuleContainer topologyRuleContainer = (ITopologyRuleContainer)topology;
//遍历拓扑规则
IEnumRule enumRule = topologyRuleContainer.Rules;
enumRule.Reset();
ESRI.ArcGIS.Geodatabase.IRule rule = null;
var count = 0;
while ((rule = enumRule.Next()) != null)
{
//获取当前拓扑规则的拓扑错误并遍历
ITopologyRule topologyRule = (ITopologyRule)rule;
IEnumTopologyErrorFeature enumTopologyErrorFeature = errorFeatureContainer.get_ErrorFeatures(spatialReference, topologyRule, searchExtent, true, true);
ITopologyErrorFeature topologyErrorFeature = null;
while ((topologyErrorFeature = enumTopologyErrorFeature.Next()) != null)
{
IFeature pFeature = topologyErrorFeature as IFeature;
if (pFeature != null)
{
if (topologyRule.Name == "图层内部面和面之间不允许存在缝隙" && count == 0)
{
count++;
continue;
}
if (pFeature != null && !pFeature.Shape.IsEmpty)
{
if (topologyRule.Name == "图层内部面和面之间不允许存在缝隙")
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{topologyErrorFeature.OriginOID}', '{topologyErrorFeature.OriginOID}-{topologyErrorFeature.DestinationOID}', 'DLTB', '32074304000008', '基础地类图斑图层内部面和面之间不允许存在缝隙','图形拓扑','{pFeature.Shape.ToJson()}');");
else
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea,RepairfilePath) VALUES ('{topologyErrorFeature.OriginOID}', '{topologyErrorFeature.OriginOID}-{topologyErrorFeature.DestinationOID}', 'DLTB', '32074304000007', '基础地类图斑图层内部面和面之间不允许重叠','图形拓扑','{pFeature.Shape.ToJson()}','{TempfilePath}');");
}
}
}
}
try
{
//IDataset pDatasetTemp = (IDataset)topology;
//pDatasetTemp.Delete();
//Marshal.ReleaseComObject(pDatasetTemp);
}
catch { }
return sqlList;
}
#endregion
#region 自相交-多部件
private void CheckGraphic(object threadParam)
{
IFeature pfeature = null;
IFeatureCursor pCursor = null;
ThreadParam _Parm = threadParam as ThreadParam;
try
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(_Parm.Temppath, WorkspaceTypeEnum.GDBFile);
var featureClass = workspaceAPI.OpenFeatureClass(_Parm.Check_LayerName);
pCursor = featureClass.FeatureClass.Search(null, true);
int iBSM = featureClass.FeatureClass.FindField("BSM");
string strBSM = string.Empty;
while ((pfeature = pCursor.NextFeature()) != null)
{
IPointCollection polygonVertices = new PolygonClass();
IPointCollection lineVertices = pfeature.ShapeCopy as IPointCollection;
polygonVertices.AddPointCollection(lineVertices);
ITopologicalOperator3 pTopology = polygonVertices as ITopologicalOperator3;
esriNonSimpleReasonEnum reason = esriNonSimpleReasonEnum.esriNonSimpleOK;
pTopology.IsKnownSimple_2 = false;
if (!pTopology.get_IsSimpleEx(out reason))
{
if (iBSM != -1)
strBSM = pfeature.Value[iBSM].ToString();
if (reason == esriNonSimpleReasonEnum.esriNonSimpleSelfIntersections && _Parm.Check_RuleName.Contains("自相交"))//自相交
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{pfeature.OID}', '{strBSM}', '{featureClass.FeatureClass.AliasName}', '{_Parm.Check_RuleCode}', '{_Parm.Check_RuleName}','图形拓扑','{pfeature.Shape.ToJson()}');");
}
if (reason == esriNonSimpleReasonEnum.esriNonSimpleUnclosedRing && _Parm.Check_RuleName.Contains("组合图斑"))//组合图斑
{
IPolygon4 polygon = pfeature.ShapeCopy as IPolygon4;
IGeometryBag bag = polygon.ExteriorRingBag;
if ((bag as IGeometryCollection).GeometryCount > 1)
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{pfeature.OID}', '{strBSM}', '{featureClass.FeatureClass.AliasName}', '{_Parm.Check_RuleCode}', '{_Parm.Check_RuleName}','图形拓扑','{pfeature.Shape.ToJson()}');");
}
}
}
if (pTopology != null)
Marshal.ReleaseComObject(pTopology);
if (lineVertices != null)
Marshal.ReleaseComObject(lineVertices);
if (polygonVertices != null)
Marshal.ReleaseComObject(polygonVertices);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (pfeature != null)
Marshal.ReleaseComObject(pfeature);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
GC.Collect();
}
}
#endregion
#region 拓扑验证
/// <summary>
/// 拓扑验证
/// </summary>
/// <param name="topologyName">拓扑名称</param>
/// <param name="featureClass">featureClass</param>
/// <param name="esriTopologyRuleTypes">验证规则</param>
/// <param name="envelope"></param>
private void TopologyVerification(string topologyName, IFeatureClass featureClass, List<esriTopologyRuleType> esriTopologyRuleTypes, ref IEnvelope envelope)
{
//1. 打开数据集文件
IWorkspace workspace = (featureClass as FeatureClass).Workspace;
//2. 打开数据集文件
IFeatureDataset featureDataset = featureClass.FeatureDataset;
//3. 向拓扑集中添加要素层
IFeatureClass LRDLlayer = featureClass;
//4. 设置拓扑处理对数据集的独占权限
ISchemaLock schemaLock = (ISchemaLock)featureDataset;
IWorkspaceFactory2 ipWsFactory = new FileGDBWorkspaceFactoryClass();
ITopologyContainer2 topologyContainer = featureDataset as ITopologyContainer2;
//判断拓扑是否存在
bool bTopExists = (featureDataset.Workspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTTopology, topologyName);
if (bTopExists)
{
ITopology topologyTemp = topologyContainer.get_TopologyByName(topologyName);
IDataset pDatasetTemp = (IDataset)topologyTemp;
pDatasetTemp.Delete();//删除拓扑
Marshal.ReleaseComObject(pDatasetTemp);
}
//关闭资源锁定
IWorkspaceFactoryLockControl ipWsFactoryLock;
ipWsFactoryLock = (IWorkspaceFactoryLockControl)ipWsFactory;
if (ipWsFactoryLock.SchemaLockingEnabled)
{
ipWsFactoryLock.DisableSchemaLocking();
}
try
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
//5. 拓扑处理
//5.1 创建拓扑容器
//5.2 向拓扑容器中添加拓扑结果层
ITopology2 topology = topologyContainer.CreateTopology(topologyName, topologyContainer.DefaultClusterTolerance, -1, "") as ITopology2;
//5.3 添加参与拓扑运算的数据层
topology.AddClass(LRDLlayer, 5, 1, 1, false);
//5.4 添加拓扑规则
string ruleName = string.Empty;
foreach (var item in esriTopologyRuleTypes)
{
switch (item)
{
case esriTopologyRuleType.esriTRTAreaNoGaps:
ruleName = "图层内部面和面之间不允许存在缝隙";
break;
case esriTopologyRuleType.esriTRTAreaNoOverlap:
ruleName = "图层内部面和面之间不允许重叠";
break;
case esriTopologyRuleType.esriTRTLineNoDangles:
ruleName = "图层内部不允许存在悬挂线";
break;
default:
break;
}
AddRuleToTopology(topology, item, ruleName, LRDLlayer, null);
}
//AddRuleToTopology(topology, esriTopologyRuleType.esriTRTAreaNoOverlap, "图层内部面和面之间不允许重叠", LRDLlayer, null);
//AddRuleToTopology(topology, esriTopologyRuleType.esriTRTAreaNoGaps, "图层内部面和面之间不允许存在缝隙", LRDLlayer, null);
//5.5 拓扑验证
IGeoDataset geoDataset = (IGeoDataset)topology;
envelope = geoDataset.Extent;
ValidateTopology(topology, envelope);
}
catch (COMException comExc)
{
throw new Exception(String.Format("Error creating topology: {0} Message: {1}", comExc.ErrorCode, comExc.Message), comExc);
}
finally
{
schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
}
}
/// <summary>
/// 获取拓扑错误
/// </summary>
/// <param name="topologyName"></param>
/// <param name="searchExtent"></param>
/// <param name="DLTBBG"></param>
/// <returns></returns>
public List<string> FindAllError(string topologyName, IEnvelope searchExtent, IFeatureClass featureClass, string ErrorLayer, string ErrorCode, string ErrorName)
{
ITopology topology = null;
List<string> sqlList = new List<string>();
try
{
IFeatureDataset featureDataset = featureClass.FeatureDataset;
ITopologyContainer topologyContainer = (ITopologyContainer)featureDataset;
topology = topologyContainer.get_TopologyByName(topologyName);
//获取坐标系
IErrorFeatureContainer errorFeatureContainer = (IErrorFeatureContainer)topology;
IGeoDataset geoDataset = (IGeoDataset)topology;
ISpatialReference spatialReference = geoDataset.SpatialReference;
ITopologyRuleContainer topologyRuleContainer = (ITopologyRuleContainer)topology;
//遍历拓扑规则
IEnumRule enumRule = topologyRuleContainer.Rules;
enumRule.Reset();
ESRI.ArcGIS.Geodatabase.IRule rule = null;
List<string> bsmlist = new List<string>();
var count = 0;
LogAPI.Debug("数据检查-获取拓扑错误");
while ((rule = enumRule.Next()) != null)
{
//获取当前拓扑规则的拓扑错误并遍历
ITopologyRule topologyRule = (ITopologyRule)rule;
IEnumTopologyErrorFeature enumTopologyErrorFeature = errorFeatureContainer.get_ErrorFeatures(spatialReference, topologyRule, searchExtent, true, true);
ITopologyErrorFeature topologyErrorFeature = null;
while ((topologyErrorFeature = enumTopologyErrorFeature.Next()) != null)
{
if (topologyErrorFeature is IFeature pFeature)
{
if (topologyRule.Name == "图层内部面和面之间不允许存在缝隙" && count == 0)
{
count++;
continue;
}
if (pFeature != null && !pFeature.Shape.IsEmpty)
{
string FeatureJSON = GeometryConvertHelper.ConvertIGeoemtryToWKT(pFeature.Shape);
//string JSON_F = pFeature.Shape.ToJson();
//IGeometry geometryJSON = GeometryConvertHelper.ConvertWKTToIGeometry(FeatureJSON);
if (topologyRule.Name == "图层内部面和面之间不允许存在缝隙")
{
//ITopologicalOperator topoOperator = pFeature.ShapeCopy as ITopologicalOperator;
//double bufferDistance = 0.001; // 缓冲区距离,根据实际需求设置
//IGeometry bufferGeometry = topoOperator.Buffer(bufferDistance);
//// 确保缓冲区几何体是多边形类型
//IPolygon polygon = bufferGeometry as IPolygon;
//if (polygon != null)
//{
// FeatureJSON = GeometryConvertHelper.ConvertIGeoemtryToWKT(polygon);
// // 在这里处理多边形,比如保存到图层、进行空间分析等
//}
if (pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{topologyErrorFeature.OriginOID}', '{SearchBSM(topologyErrorFeature.OriginOID, pFeature)}-{SearchBSM(topologyErrorFeature.DestinationOID, pFeature)}', '{ErrorLayer}', '{ErrorCode}', '{ErrorName}图层内部面和面之间不允许存在缝隙(线-批量不处理)','图形拓扑','{FeatureJSON}');");
}
else
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{topologyErrorFeature.OriginOID}', '{SearchBSM(topologyErrorFeature.OriginOID, pFeature)}-{SearchBSM(topologyErrorFeature.DestinationOID, pFeature)}', '{ErrorLayer}', '{ErrorCode}', '{ErrorName}图层内部面和面之间不允许存在缝隙(面)','图形拓扑','{FeatureJSON}');");
}
}
else if (topologyRule.Name.Contains("图层内部面和面之间不允许重叠"))
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{topologyErrorFeature.OriginOID}', '{SearchBSM(topologyErrorFeature.OriginOID, pFeature, ErrorLayer)}-{SearchBSM(topologyErrorFeature.DestinationOID, pFeature, ErrorLayer)}', '{ErrorLayer}', '{ErrorCode}', '{ErrorName}图层内部面和面之间不允许重叠','图形拓扑','{FeatureJSON}');");
}
else if (topologyRule.Name.Contains("悬挂线"))
{
string bsm = SearchBSM(topologyErrorFeature.OriginOID, pFeature, ErrorLayer);
if (!JudgeContains(sqlList, bsm))
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{topologyErrorFeature.OriginOID}', '{bsm}', '{ErrorLayer}', '{ErrorCode}', '{ErrorName}图层内部不允许存在悬挂线','图形拓扑','{FeatureJSON}');");
}
else if (pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline)
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{topologyErrorFeature.OriginOID}', '{SearchBSM(topologyErrorFeature.OriginOID, pFeature)}-{SearchBSM(topologyErrorFeature.DestinationOID, pFeature)}', '{ErrorLayer}', '{ErrorCode}', '{ErrorName}图层内部面和面之间不允许重叠(线-批量不处理)','图形拓扑','{FeatureJSON}');");
}
else
{
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{topologyErrorFeature.OriginOID}', '{SearchBSM(topologyErrorFeature.OriginOID, pFeature)}-{SearchBSM(topologyErrorFeature.DestinationOID, pFeature)}', '{ErrorLayer}', '{ErrorCode}', '{ErrorName}图层内部面和面之间不允许重叠(面)','图形拓扑','{FeatureJSON}');");
}
}
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug("获取拓扑错误异常:" + ex.Message + ex.StackTrace);
}
finally
{
try
{
if (topology != null)
{
IDataset pDatasetTemp = (IDataset)topology;
pDatasetTemp.Delete();
Marshal.ReleaseComObject(pDatasetTemp);
}
}
catch { }
}
return sqlList;
}
#endregion
private bool JudgeContains(List<string> list, string containsStr)
{
foreach (string item in list)
{
if (item.Contains(containsStr)) return true;
}
return false;
}
private string SearchBSM(int objectID, IFeature pFeature, string layerName = "DLTB")
{
string BSM = "";
IFeature pfeature = null;
IFeatureCursor pCursor = null;
IFeatureLayer JC_featureLayer = MapsManager.Instance.MapService.GetFeatureLayerByName(layerName);
IQueryFilter queryfilter = new QueryFilterClass();
queryfilter.WhereClause = $" OBJECTID = {objectID}";
try
{
pCursor = JC_featureLayer.FeatureClass.Search(queryfilter, true);
int iBSM = JC_featureLayer.FeatureClass.FindField("BSM");
if (iBSM == -1) return "";
while ((pfeature = pCursor.NextFeature()) != null)
{
BSM = pfeature.Value[iBSM].ToString();
return BSM;
}
if (!string.IsNullOrEmpty(BSM)) return BSM;
IGeometry geometry = null;
try
{ geometry = IPolygonExtension.ToGeometry(pFeature.Shape.ToJson(), true, esriGeometryType.esriGeometryPolygon); }
catch
{
try
{
geometry = IPolygonExtension.ToGeometry(pFeature.Shape.ToJson(), false, esriGeometryType.esriGeometryPolyline);
}
catch { }
}
if (geometry != null && !geometry.IsEmpty)
BSM = GetIdentifyBSM(geometry, JC_featureLayer);
return BSM;
}
catch (Exception ex)
{
return BSM;
}
}
public string GetIdentifyBSM(IGeometry pGeo, IFeatureLayer pLayer)
{
string tempBsm = "";
try
{
if (pGeo != null && !pGeo.IsEmpty && pLayer != null)
{
IIdentify identify = pLayer as IIdentify;
if (identify == null) return tempBsm;
ESRI.ArcGIS.esriSystem.IArray array = identify.Identify(pGeo);
if (array == null || array.Count == 0) return tempBsm;
for (int i = 0; i < array.Count; i++)
{
IRowIdentifyObject row = (IRowIdentifyObject)array.get_Element(i);
if (row == null) continue;
IFeature pFeature = row.Row as IFeature;
int bsmFieldIndex = pFeature.Fields.FindField("BSM");
if (bsmFieldIndex != -1)
tempBsm = pFeature.Value[bsmFieldIndex].ToString();
return tempBsm;
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex);
return tempBsm;
}
return tempBsm;
}
#region 地类图斑更新层平均节点密度大于1米小于70米
private void NodeDensity(object threadParam)
{
IFeature pfeature = null;
List<string> sqlList = new List<string>();
IFeatureCursor pCursor = null;
ThreadParam _Parm = threadParam as ThreadParam;
try
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(_Parm.Temppath, WorkspaceTypeEnum.GDBFile);
var featureClass = workspaceAPI.OpenFeatureClass(_Parm.Check_LayerName);
pCursor = featureClass.FeatureClass.Search(null, true);
int iBSM = featureClass.FeatureClass.FindField("BSM");
string strBSM = string.Empty;
while ((pfeature = pCursor.NextFeature()) != null)
{
List<double> Segmentslength = new List<double>();
IGeometryCollection _GeoColl = pfeature.ShapeCopy as IGeometryCollection;
for (int i = 0; i < _GeoColl.GeometryCount; i++)
{
ISegmentCollection _segmColl = _GeoColl.Geometry[i] as ISegmentCollection;
for (int j = 0; j < _segmColl.SegmentCount; j++)
{
Segmentslength.Add(_segmColl.Segment[j].Length);
}
}
if (Segmentslength.Average() > 70 || Segmentslength.Average() < 1)
{
if (iBSM != -1)
strBSM = pfeature.Value[iBSM].ToString();
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{pfeature.OID}', '{strBSM}', '{featureClass.FeatureClass.AliasName}', '{_Parm.Check_RuleCode}', '{_Parm.Check_RuleName}','图形拓扑','{pfeature.Shape.ToJson()}');");
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (pfeature != null)
Marshal.ReleaseComObject(pfeature);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
GC.Collect();
}
}
#endregion
#region 要素不存在尖锐角和局部狭长图形(即不允许存在一个角度小于10度,或局部图形狭长的情况)
private void Localslenderness(object threadParam)
{
IFeature pfeature = null;
List<string> sqlList = new List<string>();
IFeatureCursor pCursor = null;
ThreadParam _Parm = threadParam as ThreadParam;
IGeometry geo = null;
ITopologicalOperator topo2 = null;
IPolyline line2 = null;
try
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(_Parm.Temppath, WorkspaceTypeEnum.GDBFile);
var featureClass = workspaceAPI.OpenFeatureClass(_Parm.Check_LayerName);
pCursor = featureClass.FeatureClass.Search(null, true);
int iBSM = featureClass.FeatureClass.FindField("BSM");
string strBSM = string.Empty;
while ((pfeature = pCursor.NextFeature()) != null)
{
double angle = GetMinAngle(pfeature.ShapeCopy);//获取图形的最小角度
ITopologicalOperator topo = pfeature.ShapeCopy as ITopologicalOperator;
IPolyline line1 = topo.Boundary as IPolyline;
double length1 = line1.Length;
int pointCount1 = (pfeature.ShapeCopy as IPointCollection).PointCount;
geo = topo.Buffer(-0.05);
topo2 = geo as ITopologicalOperator;
line2 = topo2.Boundary as IPolyline;
double length2 = line2.Length;
int pointCount2 = (geo as IPointCollection).PointCount - 1;
double delta_length = length1 - length2;
double avg_halfangle = 180 * (pointCount1 - 1 - 2) / (pointCount1 - 1) / 2;
double conner_normal_length = 2 * 0.05 / Math.Tan(avg_halfangle * (Math.PI / 180));
if ((delta_length > 8 * conner_normal_length * (pointCount1 - 1)) || angle < 10)
{
if (iBSM != -1)
strBSM = pfeature.Value[iBSM].ToString();
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{pfeature.OID}', '{strBSM}', '{featureClass.FeatureClass.AliasName}', '{_Parm.Check_RuleCode}', '{_Parm.Check_RuleName}','图形拓扑','{pfeature.Shape.ToJson()}');");
}
if (topo != null)
Marshal.ReleaseComObject(topo);
if (line1 != null)
Marshal.ReleaseComObject(line1);
if (topo2 != null)
Marshal.ReleaseComObject(topo2);
if (line2 != null)
Marshal.ReleaseComObject(line2);
if (geo != null)
Marshal.ReleaseComObject(geo);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (pfeature != null)
Marshal.ReleaseComObject(pfeature);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
GC.Collect();
}
}
/// <summary>
/// 获取最小角度
/// </summary>
/// <param name="pGeo"></param>
/// <returns></returns>
private static double GetMinAngle(IGeometry pGeo)
{
double result = -1;
IPolygon4 poly4 = null;
ITopologicalOperator topo = null;
GeometryBag geoBag = null;
IGeometryCollection geoCollection = null;
try
{
if (pGeo == null || pGeo.IsEmpty)
return result;
poly4 = pGeo as IPolygon4;
topo = poly4 as ITopologicalOperator;
if (topo != null)
topo.Simplify();
geoBag = poly4.ExteriorRingBag as GeometryBag;
if (geoBag == null) return result;
geoCollection = geoBag as IGeometryCollection;
List<IGeometry> rings = new List<IGeometry>();
for (int j = 0; j < geoCollection.GeometryCount; j++)
{
IGeometry geo = geoCollection.get_Geometry(j);
rings.Add(geo);
//内环图形
IGeometryBag InteriorBag = (pGeo as IPolygon4).get_InteriorRingBag(geo as IRing);
if (InteriorBag != null)
{
IGeometryCollection InteriorRingGeometryCollection = InteriorBag as IGeometryCollection;
for (int IR = 0; IR < InteriorRingGeometryCollection.GeometryCount; IR++)
{
rings.Add(InteriorRingGeometryCollection.get_Geometry(IR));
}
}
}
foreach (IGeometry ring in rings)
{
if (ring.IsEmpty) continue;
IPointCollection points = ring as IPointCollection;
int num = points.PointCount - 1;
for (int i = 0; i < num; i++)
{
IPoint p1 = null;
IPoint p2 = points.get_Point(i);
IPoint p3 = null;
if (i == 0)
{
p1 = points.get_Point(num - 1);
p3 = points.get_Point(i + 1);
}
else if (i == num - 1)
{
p1 = points.get_Point(i - 1);
p3 = points.get_Point(0);
}
else
{
p1 = points.get_Point(i - 1);
p3 = points.get_Point(i + 1);
}
double angle = GetAngle(p2, p1, p3);
if (result == -1)
{
result = angle;
}
else
{
if (result > angle)
result = angle;
}
Marshal.ReleaseComObject(p1);
Marshal.ReleaseComObject(p2);
Marshal.ReleaseComObject(p3);
}
Marshal.ReleaseComObject(ring);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (poly4 != null)
Marshal.ReleaseComObject(poly4);
if (topo != null)
Marshal.ReleaseComObject(topo);
if (geoBag != null)
Marshal.ReleaseComObject(geoBag);
if (geoCollection != null)
Marshal.ReleaseComObject(geoCollection);
}
return result;
}
/// <summary>
/// 计算角度
/// </summary>
/// <param name="cenPoint"></param>
/// <param name="firstPoint"></param>
/// <param name="secondPoint"></param>
/// <returns></returns>
private static double GetAngle(IPoint cenPoint, IPoint firstPoint, IPoint secondPoint)
{
double ma_x = firstPoint.X - cenPoint.X;
double ma_y = firstPoint.Y - cenPoint.Y;
double mb_x = secondPoint.X - cenPoint.X;
double mb_y = secondPoint.Y - cenPoint.Y;
double v1 = (ma_x * mb_x) + (ma_y * mb_y);
double ma_val = Math.Sqrt(ma_x * ma_x + ma_y * ma_y);
double mb_val = Math.Sqrt(mb_x * mb_x + mb_y * mb_y);
if (ma_val * mb_val == 0)
{
return -1;
}
double cosM = v1 / (ma_val * mb_val);
double angleAMB = Math.Acos(cosM) * 180 / Math.PI;
return angleAMB;
}
/// <summary>
/// 尖锐角/局部狭长图形错误
/// </summary>
/// <param name="geometry"></param>
/// <returns></returns>
private bool LongAndNarrow(IGeometry geometry1)
{
List<string> sqlList = new List<string>();
IGeometry geo = null;
ITopologicalOperator topo = null;
ITopologicalOperator topo2 = null;
IPolyline line2 = null;
IPolyline line1 = null;
bool isLongAndNarrow = false;
IGeometry geometry = null;
try
{
if (geometry1 == null || geometry1.IsEmpty) return isLongAndNarrow;
geometry = geometry1;
double angle = GetMinAngle(geometry);//获取图形的最小角度
topo = geometry as ITopologicalOperator;
line1 = topo.Boundary as IPolyline;
double length1 = line1.Length;
int pointCount1 = (geometry as IPointCollection).PointCount;
geo = topo.Buffer(-0.05);
topo2 = geo as ITopologicalOperator;
line2 = topo2.Boundary as IPolyline;
double length2 = line2.Length;
int pointCount2 = (geo as IPointCollection).PointCount - 1;
double delta_length = length1 - length2;
double avg_halfangle = 180 * (pointCount1 - 1 - 2) / (pointCount1 - 1) / 2;
double conner_normal_length = 2 * 0.05 / Math.Tan(avg_halfangle * (Math.PI / 180));
if ((delta_length > 8 * conner_normal_length * (pointCount1 - 1)) || angle < 10)
{
isLongAndNarrow = true;
}
}
catch (Exception ex)
{
LogAPI.Debug("LongAndNarrow异常:" + ex.Message + ex.StackTrace);
}
finally
{
if (topo != null)
Marshal.ReleaseComObject(topo);
if (line1 != null)
Marshal.ReleaseComObject(line1);
if (topo2 != null)
Marshal.ReleaseComObject(topo2);
if (line2 != null)
Marshal.ReleaseComObject(line2);
if (geo != null)
Marshal.ReleaseComObject(geo);
}
return isLongAndNarrow;
}
#endregion
#region 地类图斑更新层内不存在不规则图斑(除地类1001、1002、1006、1009、1107、1109外,其余地类满足面积/周长<0.2,并且有一个角度小于20)
private void Irregular(object threadParam)
{
IFeature pfeature = null;
IFeatureCursor pCursor = null;
ThreadParam _Parm = threadParam as ThreadParam;
try
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(_Parm.Temppath, WorkspaceTypeEnum.GDBFile);
var featureClass = workspaceAPI.OpenFeatureClass(_Parm.Check_LayerName);
pCursor = featureClass.FeatureClass.Search(null, true);
int iBSM = featureClass.FeatureClass.FindField("BSM");
int iDLBM = featureClass.FeatureClass.FindField("DLBM");
int iSHAPE_Area = featureClass.FeatureClass.FindField("SHAPE_Area");
int iSHAPE_Length = featureClass.FeatureClass.FindField("SHAPE_Length");
string strBSM = string.Empty;
while ((pfeature = pCursor.NextFeature()) != null)
{
if ("1001,1002,1006,1009,1107,1109".Contains(pfeature.Value[iDLBM].ToString())) continue;
double angle = GetMinAngle(pfeature.ShapeCopy);//获取图形的最小角度
var SHAPE_Area = pfeature.Value[iSHAPE_Area].ToDouble();
var SHAPE_Length = pfeature.Value[iSHAPE_Length].ToDouble();
if (SHAPE_Area / SHAPE_Length < 0.2 && angle < 20)
{
if (iBSM != -1)
strBSM = pfeature.Value[iBSM].ToString();
sqlList.Add($"INSERT INTO DataCheckResults(OBJECTID, BSM, ErrorLayer, ErrorCode, ErrorName,RuleType,ErrorArea) VALUES ('{pfeature.OID}', '{strBSM}', '{featureClass.FeatureClass.AliasName}', '{_Parm.Check_RuleCode}', '{_Parm.Check_RuleName}','图形拓扑','{pfeature.Shape.ToJson()}');");
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (pfeature != null)
Marshal.ReleaseComObject(pfeature);
if (pCursor != null)
Marshal.ReleaseComObject(pCursor);
GC.Collect();
}
}
#endregion
#region CreateTempGDBForGP
private List<ThreadParam> CreateTempGDBForGP(IFeatureLayer featureLayer, bool isDLTBBG = false)
{
List<ThreadParam> _threadList = new List<ThreadParam>();
List<string> XzqList = new List<string>();
IFeatureCursor pCursor = null;
IFeature f = null;
try
{
if (featureLayer.FeatureClass.FeatureCount(null) == 0) return _threadList;
int idxZLDW = featureLayer.FeatureClass.FindField("ZLDWDM");
if (idxZLDW == -1) return _threadList;
IQueryFilter filter = new QueryFilterClass();
filter.SubFields = "ZLDWDM";
pCursor = featureLayer.FeatureClass.Search(filter, true);
while ((f = pCursor.NextFeature()) != null)
{
string zl = f.Value[idxZLDW].ToTrim();
if (zl.Length != 19) continue;
string xzqdm = zl.Substring(0, 9);
if (!XzqList.Contains(xzqdm))
{
XzqList.Add(xzqdm);
}
}
ProjectInfo prjInfo = MapsManager.Instance.CurrProjectInfo as ProjectInfo;
ThreadParam para = new ThreadParam();
para.StrBgTbLayer = GeoDBAPI.SerialzedPersist(featureLayer);
int ProNum = Environment.ProcessorCount - 2;
//ProNum = XzqList.Count;
//ProNum = 1;
int ThreadNum = XzqList.Count / ProNum;
for (int i = 0; i < ProNum; i++)
{
List<string> tempBsmList = new List<string>();
if (i < ProNum - 1)
tempBsmList = XzqList.GetRange(i * ThreadNum, ThreadNum);
else
tempBsmList = XzqList.GetRange(i * ThreadNum, XzqList.Count - i * ThreadNum);
string _ThreadName = string.Empty;
List<string> _Codes = new List<string>();
foreach (var xzq in tempBsmList)
{
_ThreadName += xzq.Replace(prjInfo.CODE, "");
_Codes.Add(xzq);
}
_threadList.Add(new ThreadParam()
{
ThreadName = _ThreadName,
Codes = _Codes,
ProjInfo = MapsManager.Instance.CurrProjectInfo as ProjectInfo,
StrJcTbLayer = para.StrJcTbLayer,
StrBgTbLayer = para.StrBgTbLayer,
Layers = para.Layers,
IsDLTBBG = isDLTBBG
});
}
foreach (var itemThread in _threadList)
{
ThreadManager.Instance.QueueUserWorkItem(new System.Threading.WaitCallback(Execute), itemThread);
}
while (ThreadManager.Instance.ActiveCount > 0) { }
}
catch (Exception ex)
{
throw ex;
}
return _threadList;
}
public void Execute(object pThreadParm)
{
try
{
ThreadParam _Parm = pThreadParm as ThreadParam;
IFeatureLayer BgTbLayer = GeoDBAPI.DeSerialzedPersist(_Parm.StrBgTbLayer) as IFeatureLayer;
string TempPath = CreateTempFile(_Parm.ThreadName, (BgTbLayer.FeatureClass as FeatureClass).Name);
FileInfo fInfo = new FileInfo(_Parm.IsDLTBBG == true ? _Parm.ProjInfo.BGDatabase : _Parm.ProjInfo.ZLDatabase);
//_Parm.ProjInfo.ZLDatabase = System.IO.Path.Combine(TempPath, fInfo.Name);
string TempGDbPath = System.IO.Path.Combine(TempPath, _Parm.ThreadName + ".gdb");
_Parm.Temppath = TempGDbPath;
GPParamClass paramClass = new GPParamClass();
string strFilter = string.Empty;
foreach (var xzq in _Parm.Codes)
{
strFilter += string.Format(" ZLDWDM like '{0}%' or", xzq);
}
strFilter = strFilter.TrimEnd('r').TrimEnd('o');
paramClass.FirstFeatureLayer = BgTbLayer;
paramClass.Where_clause = strFilter;
paramClass.TempGDBPath = TempPath;
paramClass.IsGetOutPutFeature = true;
paramClass.GPType = EnumGPType.BGTBYCL;
IFeatureLayer Temp_DLTBGXGC = null;
GPHelper helper = new GPHelper();
helper.ExeGPForProces(paramClass, ref Temp_DLTBGXGC);
}
catch
{ }
}
public virtual string CreateTempFile(string pType, string LayerName)
{
string result = string.Empty;
try
{
string dbPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Temp" + ".db");
string TempFolder = Directory.GetCurrentDirectory() + "\\Temp\\DLTB\\" + LayerName + "\\" + pType;
if (!Directory.Exists(TempFolder))
Directory.CreateDirectory(TempFolder);
PluginServiceInterface.CommonHelper.DelectDir(TempFolder);
if (!Directory.Exists(TempFolder))
{
Directory.CreateDirectory(TempFolder);
}
result = TempFolder;
}
catch (Exception ex)
{
Console.WriteLine("创建临时数据库失败!" + ex.Message);
LogAPI.Debug("创建临时数据库异常:" + ex);
throw ex;
}
return result;
}
public bool DirectoryCopy(string sourceDir, string targetDirPath)
{
try
{
if (!Directory.Exists(sourceDir)) return false;
string targetDir = targetDirPath + "\\" + System.IO.Path.GetFileName(sourceDir);
if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
// 文件及文件夹名称数组
string[] dirColl = Directory.GetDirectories(sourceDir);
string[] fileColl = Directory.GetFiles(sourceDir);
// 便利所有文件
if (fileColl.Length > 0)
{
string fileName;
foreach (string fileDir in fileColl)
{
fileName = System.IO.Path.GetFileName(fileDir);
File.Copy(sourceDir + "\\" + fileName, targetDir + "\\" + fileName, true);
}
}
// 遍历所有文件夹
if (dirColl.Length > 0)
{
string folderName;
foreach (string dir in dirColl)
{
folderName = System.IO.Path.GetFileName(dir);
// 递归调用
Directory.CreateDirectory(targetDir + "\\" + folderName);
DirectoryCopy(dir, targetDir + "\\" + folderName);
}
}
return true;
}
catch (Exception ex)
{
//LogAPI.Debug("新建工程页面中,文件夹复制时失败,异常原因: " + ex + " ; ");
Console.WriteLine("数据拷贝失败!");
return false;
//throw;
}
}
#endregion
private void Dg_PreviewMouseDoubleClick(object sender, DevExpress.Xpf.Grid.RowDoubleClickEventArgs e)
{
try
{
object obj = this.treeList.SelectedItem;
if (obj != null)
{
if (!(obj is DataCheckResult result)) return;
if (!string.IsNullOrEmpty(result.PrimaryKeyValue2))
{
IWorkspaceAPI workspaceAPI = new WorkspaceAPI(result.RepairfilePath, WorkspaceTypeEnum.GDBFile);
IFeatureClassAPI featureClassAPI = workspaceAPI.OpenFeatureClass("DLTBBG_Err");
IGeometry geometry = featureClassAPI.GetFeature(result.PrimaryKeyValue2.ToInt()).ShapeCopy;
if (geometry != null && !geometry.IsEmpty)
{
MapsManager.Instance.MapService.DrawGraph(geometry, true);
MapsManager.Instance.MapService.Zoom(geometry);
return;
}
}
else if (!string.IsNullOrWhiteSpace(result.ErrorArea))
{
IGeometry geometry = null;
try
{
//geometry = IPolygonExtension.ToGeometry(result.ErrorArea, true, esriGeometryType.esriGeometryPolygon);
//图形转化模式 默认大地坐标系4900
geometry = GeometryConvertHelper.ConvertWKTToIGeometry(result.ErrorArea);
}
catch
{
try
{
geometry = IPolygonExtension.ToGeometry(result.ErrorArea, false, esriGeometryType.esriGeometryPolyline);
}
catch
{
SelectFeature(result);
}
}
if (geometry != null && !geometry.IsEmpty)
{
MapsManager.Instance.MapService.DrawGraph(geometry, true);
MapsManager.Instance.MapService.Zoom(geometry);
return;
}
else
SelectFeature(result);
}
else if (string.IsNullOrWhiteSpace(result.ErrorArea) || result.ErrorArea == "0" || Convert.ToDouble(result.ErrorArea) < 0.02)
{
SelectFeature(result);
}
else if (!string.IsNullOrWhiteSpace(result.PrimaryKeyValue))
{
IGeometry geometry = null;
if (_CheckName == "变更图斑")
{
if (!string.IsNullOrWhiteSpace(result.BSM))
{
IFeatureClass featureClass = MapsManager.Instance.MapService.GetFeatureClassByName("DLTBBG");
geometry = featureClass.GetFeature(result.BSM.ToInt()).Shape;
if (geometry != null && !geometry.IsEmpty)
{
MapsManager.Instance.MapService.DrawGraph(geometry, true);
MapsManager.Instance.MapService.Zoom(geometry);
return;
}
}
}
}
MapRefreshView.OnCreate(m_hookHelper.Hook);
MapRefreshView.OnClick();
}
}
catch (Exception ex)
{
LogAPI.Debug("Dg_PreviewMouseDoubleClick错误:" + ex.Message);
}
}
private void SelectFeature(DataCheckResult result)
{
try
{
if (!string.IsNullOrWhiteSpace(result.BSM) && !string.IsNullOrWhiteSpace(result.ErrorLayer))
{
var layer = MapsManager.Instance.MapService.GetFeatureClassByName(result.ErrorLayer);
if (layer != null && layer.FeatureCount(null) > 0)
{
IFeatureCursor pCursor = null;
if (result.BSM.Contains("-"))
{
string[] bsms = result.BSM.Split('-');
for (int i = 0; i < bsms.Length; i++)
{
pCursor = layer.Search(new QueryFilterClass() { WhereClause = $"BSM='{bsms[i]}' " }, true);
IFeature feature = pCursor.NextFeature();
if (feature != null)
{
MapsManager.Instance.MapService.DrawGraph(feature.ShapeCopy, true);
MapsManager.Instance.MapService.Zoom(feature.ShapeCopy);
//MapsManager.Instance.MapService.SelectFeature(result.ErrorLayer, feature.OID.ToString());
}
}
}
else
{
pCursor = layer.Search(new QueryFilterClass() { WhereClause = $"BSM='{result.BSM}' " }, true);
IFeature feature = pCursor.NextFeature();
if (feature != null)
{
MapsManager.Instance.MapService.DrawGraph(feature.ShapeCopy, true);
MapsManager.Instance.MapService.Zoom(feature.ShapeCopy);
//MapsManager.Instance.MapService.SelectFeature(result.ErrorLayer, feature.OID.ToString());
}
}
}
}
else if (string.IsNullOrWhiteSpace(result.ErrorLayer) || string.IsNullOrWhiteSpace(result.PrimaryKey) || string.IsNullOrWhiteSpace(result.PrimaryKeyValue)) return;
else if (result.PrimaryKey.ToUpper() == "OBJECTID")
{
MapsManager.Instance.MapService.SelectFeature(result.ErrorLayer, result.PrimaryKeyValue);
}
}
catch (Exception)
{
return;
}
}
}
#region RepairEntity
public class RepairEntity
{
public string RepairSQL { get; set; }
public string LayerName { get; set; }
public List<string> BSMList { get; set; }
public List<string> IDList { get; set; }
}
#endregion
public class ThreadParam
{
public string ThreadName { get; set; }
public List<string> Codes { get; set; }
public ProjectInfo ProjInfo { get; set; }
public string StrBgTbLayer { get; set; }
public string StrJcTbLayer { get; set; }
public List<LayerCfg> Layers { get; set; }
public string Check_LayerName { get; set; }
public string Check_RuleCode { get; set; }
public string Check_RuleName { get; set; }
public string Temppath { get; set; }
public bool IsDLTBBG { get; set; }
}
public class GPHelper
{
public static GPHelper Instance { get; } = new GPHelper();
public GPHelper() { }
public string ExeGPForProces(string arg)
{
string result = string.Empty;
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(arg);
string strParm = Convert.ToBase64String(toEncryptArray);
var psi = new ProcessStartInfo("GPHelper.exe", strParm);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
var pes = Process.Start(psi);
var sbuffer = new StringBuilder();
var sout = pes.StandardOutput;
while (!sout.EndOfStream)
{
result = sout.ReadLine();
if (String.IsNullOrEmpty(result)) continue;
sbuffer.AppendLine(result);
}
pes.WaitForExit();
pes.Close();
String res = sbuffer.ToString();
sbuffer.Clear();
return result;
}
public void ExeGPForProces(GPParamClass gPParam, ref IFeatureLayer result)
{
string outPath = string.Empty;
try
{
string strParm = SerializeAPI.SerializeToXML<GPParamClass>(gPParam);
outPath = ExeGPForProces(strParm);
lock (this)
{
if (outPath.ToLower() == "error")
{
}
else
{
if (string.IsNullOrWhiteSpace(outPath))
outPath = gPParam.OutFeatureClassPath;
result = new FeatureLayer();
FileInfo file = new FileInfo(outPath.Replace("\r\n", ""));
string dbPath = file.DirectoryName;
string fcName = file.Name;
if (file.Name.ToLower().EndsWith(".gdb") && gPParam.FcName != null)
{
dbPath = file.FullName;
fcName = gPParam.FcName;
}
else if (fcName.ToLower().EndsWith(".shp"))
{
KGIS.Framework.AE.IWorkspaceAPI wsAPI = new KGIS.Framework.AE.WorkspaceAPI(dbPath, KGIS.Framework.AE.Enum.WorkspaceTypeEnum.ShapeFile);
KGIS.Framework.AE.IFeatureClassAPI fcAPI = wsAPI.OpenFeatureClass(fcName.Replace(".shp", ""));
result.FeatureClass = fcAPI.FeatureClass;
}
{
KGIS.Framework.AE.IWorkspaceAPI wsAPI = new KGIS.Framework.AE.WorkspaceAPI(dbPath, KGIS.Framework.AE.Enum.WorkspaceTypeEnum.GDBFile);
KGIS.Framework.AE.IFeatureClassAPI fcAPI = wsAPI.OpenFeatureClass(fcName);
result.FeatureClass = fcAPI.FeatureClass;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(outPath);
Console.WriteLine(ex.Message);
}
}
}
public class ProcesHelper
{
public static ProcesHelper Instance { get; } = new ProcesHelper();
private ProcesHelper() { }
public Action<object> ProgressHandle { get; set; }
public string ExeGPForProces(string arg)
{
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(arg);
string strParm = Convert.ToBase64String(toEncryptArray);
var psi = new ProcessStartInfo("KDataCheck.exe", strParm);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
var pes = Process.Start(psi);
var sbuffer = new StringBuilder();
var sout = pes.StandardOutput;
while (!sout.EndOfStream)
{
var line = sout.ReadLine();
if (String.IsNullOrEmpty(line)) continue;
sbuffer.AppendLine(line);
if (line.StartsWith("Msg:"))
ProgressHandle?.Invoke(line.Replace("Msg:", ""));
else
{
LogAPI.Debug(line);
}
}
pes.WaitForExit();
pes.Close();
String res = sbuffer.ToString();
sbuffer.Clear();
return res;
}
string outPath = string.Empty;
public string ExeGPForProces(IDGParameter gPParam)
{
string result = string.Empty;
try
{
string strParm = SerializeAPI.SerializeToXML(gPParam);
result = ExeGPForProces(strParm);
}
catch (Exception ex)
{
result = ex.Message;
Console.WriteLine(result);
Console.WriteLine(ex.Message);
}
return result;
}
}
public class GDPDJBInfo
{
public string BSM { get; set; }
public string PDJB { get; set; }
public double Area { get; set; }
}
}