森林草原湿地荒漠调查
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.
 
 
 

1272 lines
56 KiB

using DevExpress.Xpf.Editors;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using KGIS.Framework.AE;
using KGIS.Framework.AE.Enum;
using KGIS.Framework.Core.Services;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.OpenData.Control;
using KGIS.Framework.OpenData.Filter;
using KGIS.Framework.OpenData.InterFace;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Dialog;
using KGIS.Framework.Utils.ExtensionMethod;
using KGIS.Framework.Utils.Helper;
using KGIS.Framework.Utils.Model;
using KGIS.Framework.Utils.Utility;
using Kingo.Core.Authorize;
using Kingo.Plugin.MapView.Model;
using Kingo.PluginServiceInterface;
using KUI.Windows;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using UIShell.OSGi;
namespace Kingo.Plugin.MapView.Views.AppMenuView
{
/// <summary>
/// UCCreateProjectView_WPF.xaml 的交互逻辑
/// </summary>
public partial class UCCreateProjectView_WPF : BaseWindow
{
/// <summary>
/// ViewManager服务接口
/// </summary>
private KGIS.Framework.Views.IViewManager m_ViewManager;
/// <summary>
/// 工作目录服务接口
/// </summary>
IWorkCatalog _workCatalog = null;
private ISystemCfg SystemCfg = null;
/// <summary>
/// 行政区代码集合
/// </summary>
List<DataDicTionary> xzqCoderesult = new List<DataDicTionary>();
private string Setworkapacepath { get; set; }
private string PrjFileStr;
/// <summary>
/// 授权加密-区划代码
/// </summary>
private string getCodes = "";
private List<string> Codes = new List<string>();
private Dictionary<string, string> keyValueCoordinates = new Dictionary<string, string>();
//划入库数据路径集合
private List<HRDataPath> HRDataPaths;
public UCCreateProjectView_WPF()
{
InitializeComponent();
DevExpress.Xpf.Core.ThemeManager.SetTheme(this, DevExpress.Xpf.Core.Theme.Office2013LightGray);
//工作目录接口
_workCatalog = BundleRuntime.Instance.GetFirstOrDefaultService<IWorkCatalog>();
//系统配置接口
SystemCfg = BundleRuntime.Instance.GetFirstOrDefaultService<ISystemCfg>();
Codes = RunIDService2.Instance.Codes;
//从工作目录中选择工程目录
ProjectInfo ProInfo = new ProjectInfo();
Init(ProInfo);
AutoCompluteTxt_Box();
string tempCode = string.Empty;
if (Codes != null && Codes.Count == 1)
{
tempCode = Codes[0];
}
GetXZQDic();
if (!tempCode.EndsWith("00") && !string.IsNullOrWhiteSpace(tempCode))
{
ProInfo.CODE = tempCode;
txt_Box.SelectedValue = tempCode;
txt_Box.IsReadOnly = true;
}
else
{
//给下拉框绑定行政区代码集合
txt_Box.ItemsSource = GetXZQDic();
}
this.Loaded += UCCreateProjectView_WPF_Loaded;
}
/// <summary>
/// 页面预数据加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UCCreateProjectView_WPF_Loaded(object sender, RoutedEventArgs e)
{
try
{
#region 工程类型
//按类型显示默认工程类型 类型判定待修改
SystemTypeEnum systemTypeEnum = Platform.Instance.SystemType;
if (systemTypeEnum == SystemTypeEnum.RCBGJK)
{
projectType.SelectedIndex = -1;
projectType.SelectedIndex = 0;
projType.Opacity = 0;
hideProjType.Visibility = Visibility.Visible;
TbXZQInfo.Visibility = Visibility.Collapsed;
}
else if (systemTypeEnum == SystemTypeEnum.BGFWCG)
{
projType.Content = "变化图斑提取";
projType.Tag = "BHTBTQ";
}
else if (systemTypeEnum == SystemTypeEnum.NDBGJK)
{
projType.Content = "年度变更建库";
projType.Tag = "NDBG";
}
#endregion
#region 坐标代号
//List<string> strings = new List<string>() { "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45" };
string SourcePath = System.IO.Path.Combine(SysAppPath.GetCurrentAppPath(), "CGCS2000");
foreach (string fls in Directory.GetFiles(SourcePath))
{
FileInfo flinfo = new FileInfo(fls);
if (flinfo.Name.Contains("CGCS2000 3 Degree GK Zone"))
keyValueCoordinates[flinfo.Name.Split(' ')[5]] = flinfo.FullName;
}
#endregion
#region 其他区县基础库
if (HRDataPaths == null)
HRDataPaths = new List<HRDataPath>() { new HRDataPath() { ID = 0 } };
gvCtrl.ItemsSource = HRDataPaths;
#endregion
}
catch (Exception ex)
{
PluginServiceInterface.CommonHelper.RecordsErrLog("页面预数据加载异常", ex);
MessageHelper.ShowTips("页面预数据加载异常:" + ex.Message);
}
}
/// <summary>
/// 区划代码自动过滤参数获取getCodes
/// </summary>
public void AutoCompluteTxt_Box()
{
try
{
//获取当前授权类型
Attribute guid_attr = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute));
string guid = ((GuidAttribute)guid_attr).Value;
var type = "";//ConfigurationManager.AppSettings.Get("LicenseType");
//RunIDService2.Instance.Codes
if (type == "F")//加密文件
{
getCodes = RunIDService.GetCode();
}
else if (type == "D")//加密狗EmptyValue
{
AuthorizeHelper authorizeHelper = new AuthorizeHelper(AuthorizeType., "MobileDataMake", "2x", "");
getCodes = authorizeHelper.GetAreaCode(); //GetCode("dlgtz2021", "2x", GetVersion(Assembly.GetExecutingAssembly().Location), TokenLibrary.VendorCode.Code);
if (getCodes == "EmptyValue" || getCodes == null) getCodes = "";
}
if (getCodes != null && getCodes.IndexOf("0000") == 2)
{
getCodes = getCodes.Substring(0, 2);
}
else if (getCodes != null && getCodes.IndexOf("00") == 4)
{
getCodes = getCodes.Substring(0, 4);
}
}
catch (Exception ex)
{
PluginServiceInterface.CommonHelper.RecordsErrLog("执行AutoCompluteTxt_Box发生异常:", ex);
}
}
/// <summary>
/// 区划代码集(330110-余杭区)
/// </summary>
/// <returns></returns>
public List<DataDicTionary> GetXZQDic()
{
KGIS.Framework.DBOperator.IRDBHelper rdbHelper = null;
try
{
string systemPath = SysAppPath.GetDataBasePath() + "System.mdb";
if (File.Exists(systemPath))
{
string connStr = SysConfigsOprator.GetDBConnectionByName("MDBOledbConnection");
connStr = string.Format(connStr, systemPath);
rdbHelper = RDBFactory.CreateDbHelper(connStr, DatabaseType.MSAccess);
string strPrWhere = "1=2";
string strWhere = string.Empty;
if (Codes != null)
{
foreach (var item in Codes)
{
string likeVal = item;
if (item.EndsWith("0000"))
{
likeVal = item.Substring(0, 2);
strWhere += string.Format(" or XZQ LIKE '{0}%'", likeVal);
}
else if (item.EndsWith("00"))
{
likeVal = item.Substring(0, 4);
strWhere += string.Format(" or XZQ LIKE '{0}%'", likeVal);
}
else
{
strWhere += string.Format(" or XZQ LIKE '{0}%'", likeVal);
}
}
}
if (!string.IsNullOrWhiteSpace(strWhere))
strWhere = strPrWhere + strWhere;
else
strWhere = "1=1";
string strSQL = "select OBJECTID AS ID, XZQ AS CODE,XZQMC AS NAME from XZQ Where " + strWhere + "";
DataTable dt = rdbHelper.ExecuteDatatable("Dic", strSQL, true);
if (dt != null)
{
xzqCoderesult = TBToList.ToList<DataDicTionary>(dt);
foreach (var item in xzqCoderesult)
{
item.DisplayName = item.CODE + "-" + item.NAME;
if (dt.Rows.Count == 1) txt_Box.DisplayMemberPath = item.DisplayName;
}
}
}
}
catch (Exception ex)
{
PluginServiceInterface.CommonHelper.RecordsErrLog("获取行政区字典发生异常", ex);
}
finally
{
rdbHelper?.DisConnect();
}
return xzqCoderesult;
}
void Init(ProjectInfo pPrj)
{
try
{
List<ScaleCodeTable> listScale = new List<ScaleCodeTable>
{
new ScaleCodeTable() { Scale = "1:2000", ScaleCode = "I" },
new ScaleCodeTable() { Scale = "1:5000", ScaleCode = "H" },
new ScaleCodeTable() { Scale = "1:10000", ScaleCode = "G" },
new ScaleCodeTable() { Scale = "1:25000", ScaleCode = "F" },
new ScaleCodeTable() { Scale = "1:50000", ScaleCode = "E" },
new ScaleCodeTable() { Scale = "1:100000", ScaleCode = "D" },
new ScaleCodeTable() { Scale = "1:250000", ScaleCode = "C" },
new ScaleCodeTable() { Scale = "1:500000", ScaleCode = "B" }
};
combScale.ItemsSource = listScale;
if (!string.IsNullOrWhiteSpace(pPrj.ScaleCode))
combScale.SelectedItem = listScale.FirstOrDefault(x => x.ScaleCode == pPrj.ScaleCode);
else if (!string.IsNullOrWhiteSpace(pPrj.ScaleCode))
combScale.SelectedItem = listScale.FirstOrDefault(x => x.Scale == pPrj.Scale);
else
combScale.SelectedIndex = 0;
List<ScaleCodeTable> listResolution = new List<ScaleCodeTable>();
listResolution.Add(new ScaleCodeTable() { Scale = "万分之一", ScaleCode = "0.0001" });
listResolution.Add(new ScaleCodeTable() { Scale = "十万分之一", ScaleCode = "0.00001" });
combXYResolution.ItemsSource = listResolution;
if (!string.IsNullOrWhiteSpace(pPrj.XYResolution.ToTrim()) && pPrj.XYResolution != 0)
combXYResolution.SelectedItem = listResolution.FirstOrDefault(x => x.ScaleCode == pPrj.XYResolution.ToTrim());
else
combXYResolution.SelectedIndex = 0;
if (_workCatalog != null && _workCatalog.SaveWorkSapcePath != "")
pPrj.ProjDir = _workCatalog.SaveWorkSapcePath;
if (pPrj.KZMJ == null)
{
pPrj.KZMJ = new KZMJInfo();
}
this.DataContext = pPrj;
}
catch (Exception ex)
{
LogAPI.Debug("加载新建工程页面数据时失败,异常原因: " + ex.Message + " ; ");
MessageHelper.ShowTips("加载新建工程页面数据时异常:" + ex.Message);
}
}
#region TextEdit字段校验
//工程名称 值校验
private void Validate(object sender, ValidationEventArgs e)
{
if (e.Value != null)
{
if (e.Value is string)
{
if (string.IsNullOrWhiteSpace(e.Value as string))
{
e.IsValid = false;
e.ErrorContent = "值不能为空";
}
}
else if (e.Value is float || e.Value is double || e.Value is Int32 || e.Value is decimal)
{
double db = Convert.ToDouble(e.Value);
if (db == 0)
{
e.IsValid = false;
e.ErrorContent = "值不能为0";
}
}
}
else
{
e.IsValid = false;
e.ErrorContent = "值不能为空";
}
}
private bool BtnPrjFile_Validate(string BtnPrjFileValue)
{
try
{
if (BtnPrjFileValue.Length == 2)
{
double db = BtnPrjFileValue.ToInt();
if (db < 25 || db > 45)
{
MessageHelper.ShowTips("该值不在代号(25~45)预期内");
return false;
}
else
{
if (keyValueCoordinates.ContainsKey(BtnPrjFileValue.Trim() + ".prj"))
{
ISpatialReference spatialReference = GetSpatialReference(keyValueCoordinates[BtnPrjFileValue.Trim() + ".prj"]);
SetPRJBySp(spatialReference, true);
return true;
}
else
return false;
}
}
else if (!BtnPrjFileValue.StartsWith("CGCS2000"))
{
MessageHelper.ShowTips("该值不在代号(25~45)预期内");
return false;
}
else
return true;
}
catch (Exception ex)
{
PluginServiceInterface.CommonHelper.RecordsErrLog("验证坐标代号异常:", ex);
return false;
}
}
#endregion
/// <summary>
/// 选择工程目录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelectedPrjDir_Click(object sender, RoutedEventArgs e)
{
try
{
FolderBrowserDialog m_Dialog = new FolderBrowserDialog();
System.Windows.Forms.DialogResult result = m_Dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel) return;
string m_Dir = m_Dialog.SelectedPath.Trim();
this.btnPrjDir.Text = m_Dir;//工程路径
}
catch (Exception ex)
{
LogAPI.Debug("新建工程页面中-选择工程目录时失败,异常原因: " + ex + " ; ");
MessageHelper.ShowTips("操作异常:" + ex.Message);
}
}
/// <summary>
/// 工作目录文件夹复制
/// </summary>
/// <param name="sourceDir">原文件夹</param>
/// <param name="targetDirPath">目标目录</param>
/// <returns>是否成功复制</returns>
private void DirectoryCopys(string targetDirPath, string xzqCode_Name)
{
try
{
string targetDir = targetDirPath + "\\" + xzqCode_Name;
//创建工程目录文件
if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
string folderName = string.Empty;
Directory.CreateDirectory(targetDir + "\\举证成果");
Directory.CreateDirectory(targetDir + "\\参考数据");
Directory.CreateDirectory(targetDir + "\\工程目录");
Directory.CreateDirectory(targetDir + "\\年初数据");
Directory.CreateDirectory(targetDir + "\\变更成果");
}
catch (Exception ex)
{
LogAPI.Debug("创建工程目录页面中,文件夹复制时失败,异常原因: " + ex.Message + " ; ");
throw;
}
}
private void btnPrjFilePath_Click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog openFileDialog = new OpenFileDialog
{
InitialDirectory = System.IO.Path.Combine(SysAppPath.GetCurrentAppPath(), @"CGCS2000"),
Filter = "prj Files(*.prj)|*.prj",
Multiselect = false
};
if (openFileDialog.ShowDialog())
{
ISpatialReference spatialReference = GetSpatialReference(openFileDialog.FileName);
SetPRJBySp(spatialReference);
}
}
catch (Exception ex)
{
LogAPI.Debug("新建工程 页面 中 选择坐标系 时失败,异常原因: " + ex + " ; ");
MessageHelper.ShowTips("选择坐标参考异常:" + ex.Message);
}
}
private void btnPrjFilePath_Click2(object sender, RoutedEventArgs e)
{
try
{
IGeoDataset s = GetGisFileSource();
if (s == null || s.SpatialReference == null) return;
SetPRJBySp(s.SpatialReference);
if (s != null)
Marshal.ReleaseComObject(s);
}
catch (Exception ex)
{
LogAPI.Debug("新建工程 页面 中 导入坐标系 时失败,异常原因: " + ex + " ; ");
MessageHelper.ShowTips("导入坐标参考系异常:" + ex.Message);
}
}
public ISpatialReference GetSpatialReference(string prjFile)
{
//创建一个要素集创建一个投影
ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass();
ISpatialReference spatialReference = pSpatialRefFac.CreateESRISpatialReferenceFromPRJFile(prjFile);
return spatialReference;
}
private void SetPRJBySp(ISpatialReference spatialReference, bool IsCoordinateCode = false)
{
string spatialrefstr = string.Empty;
IESRISpatialReferenceGEN2 prjsr = spatialReference as IESRISpatialReferenceGEN2;
prjsr.ExportToESRISpatialReference2(out spatialrefstr, out int t);
PrjFileStr = spatialrefstr;
string beginstr = "[";
int leftindex = spatialrefstr.IndexOf(beginstr) + beginstr.Length;
string spatialrefrightstr = spatialrefstr.Substring(leftindex);
int length = spatialrefrightstr.IndexOf(",");
string btnPrjFileValue = spatialrefrightstr.Substring(0, length).Replace("\"", "");
if (!IsCoordinateCode)
btnPrjFile.Text = spatialrefrightstr.Substring(0, length).Replace("\"", "");
if (btnPrjFileValue.ToLower().Contains("3_degree"))
{
this.txtFDD.Text = "3";
}
else if (btnPrjFileValue.ToLower().Contains("6_degree"))
{
this.txtFDD.Text = "6";
}
else
{
this.txtFDD.Text = "0";
}
//获取中央经线
try
{
txtZYJD.Text = "0";
beginstr = "Central_Meridian";
leftindex = spatialrefstr.IndexOf(beginstr) + beginstr.Length;
if (leftindex > beginstr.Length)
{
spatialrefrightstr = spatialrefstr.Substring(leftindex);
length = spatialrefrightstr.IndexOf("]");
double p1 = double.Parse(spatialrefrightstr.Substring(0, length).Split(',')[1]);
txtZYJD.Text = p1.ToTrim();
}
}
catch (Exception ex1)
{
LogAPI.Debug("新建工程 页面 中 设置项目坐标系 过程中 获取中央经线 时失败,异常原因: " + ex1 + " ; ");
}
//获取图形带号
try
{
string str_spTXDH = "0";
spTXDH.Text = "0";
beginstr = "False_Easting";
leftindex = spatialrefstr.IndexOf(beginstr) + beginstr.Length;
if (leftindex > beginstr.Length)
{
spatialrefrightstr = spatialrefstr.Substring(leftindex);
length = spatialrefrightstr.IndexOf("]");
string p7 = spatialrefrightstr.Substring(0, length).Split(',')[1];
//原方法强行转化有问题
//spTXDH.Text = int.Parse(p7.Replace("500000.0", "")).ToString();
string sTemp_1 = p7.Replace("500000.0", "");
int iTemp_1;
if (ExtendMethd.JudgeIsCouldConversionInt(sTemp_1) == true)
{
iTemp_1 = int.Parse(sTemp_1);
str_spTXDH = iTemp_1.ToString();
}
else
{
str_spTXDH = "0";
}
}
else
{
str_spTXDH = "0";
}
spTXDH.Text = str_spTXDH;
}
catch (Exception ex2)
{
LogAPI.Debug("新建工程 页面 中 设置项目坐标系 过程中 获取图形带号 时失败,异常原因: " + ex2 + " ; ");
}
}
private IGeoDataset GetGisFileSource()
{
try
{
OpenDataDialog pDialog = new OpenDataDialog();
ISpatialDataObjectFilter pOFilter;
pOFilter = new FilterDatasetsAndLayers();
pDialog.AddFilter(pOFilter, true);
pDialog.Title = "选择矢量图层数据";
pDialog.AllowMultiSelect = false;
pDialog.RestoreLocation = true;
pDialog.StartLocation = pDialog.FinalLocation;
if (pDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && pDialog.Selection.Count != 0)
{
foreach (ISpatialDataObject distObj in pDialog.Selection)
{
if (distObj.DatasetType == esriDatasetType.esriDTFeatureClass)
{
return (distObj.DatasetName as ESRI.ArcGIS.esriSystem.IName).Open() as IGeoDataset;
}
}
}
return null;
}
catch (Exception ex)
{
LogAPI.Debug("新建工程页面中获取GIS文件源时失败,异常原因: " + ex + " ; ");
return null;
}
}
/// <summary>
/// 创建新工程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnOK_Click(object sender, RoutedEventArgs e)
{
btnOK.IsEnabled = false;
btnCanel.IsEnabled = false;
//关闭前关闭所有的未关闭的窗体
m_ViewManager = Platform.Instance.ViewManager;
//m_ViewManager.CloseAllDocument();
//m_ViewManager.CloseAllPanel();
ProjectInfo ProInfo = MapsManager.Instance.MapService.GetProjectInfo() as ProjectInfo;
if (ProInfo != null && ProInfo.ProjType == EnumProjType.BHTBTQ && Platform.Instance.SystemType == SystemTypeEnum.BGFWCG)
{
IUcZYQMagrHelper ucZYQMagrHelper = BundleRuntime.Instance.GetFirstOrDefaultService<IUcZYQMagrHelper>();
ucZYQMagrHelper?.ClearData();
IUcMulitMapControlHelper ucMulitMapControlHelper = BundleRuntime.Instance.GetFirstOrDefaultService<IUcMulitMapControlHelper>();
ucMulitMapControlHelper?.ClearData();
}
MapsManager.Instance.MapService.CloseProject();
try
{
if (BtnPrjFile_Validate(btnPrjFile.Text.ToTrim()) == false) return;
if (string.IsNullOrWhiteSpace(PrjFileStr))
{
MessageHelper.ShowTips("请指定坐标系!");
return;
}
if ((combScale.SelectedItem as ScaleCodeTable) == null)
{
MessageHelper.ShowTips("请选择比例尺!");
return;
}
if (xzqCoderesult.FirstOrDefault(x => x.CODE == txt_Box.SelectedValue.ToTrim()) == null)
{
MessageHelper.ShowTips("请选择正确的区县代码");
return;
}
double LDMJValue = string.IsNullOrEmpty(this.TZH_LDMJ.Text) ? 0 : this.TZH_LDMJ.Text.ToDouble();
double HDMJValue = string.IsNullOrEmpty(this.TZH_HDMJ.Text) ? 0 : this.TZH_HDMJ.Text.ToDouble();
if (LDMJValue + HDMJValue <= 0)
{
MessageHelper.ShowTips("陆地和海岛面积之和不能为零!");
return;
}
this.ShowLoading("工程创建中……", 0, 0);
ProjectInfo pro = this.DataContext as ProjectInfo;
pro.CODE = txt_Box.SelectedValue.ToTrim();
pro.CodeName = txt_Box.Text.Contains("-") ? txt_Box.Text.Split('-')[1] : "";
pro.FDD = txtFDD.Text;
pro.Scale = (combScale.SelectedItem as ScaleCodeTable).Scale;
pro.ScaleCode = (combScale.SelectedItem as ScaleCodeTable).ScaleCode;
pro.XYResolution = (combXYResolution.SelectedItem as ScaleCodeTable).ScaleCode.ToDouble();
pro.ProjSuffix = ".KBG";
pro.PrjFileStr = PrjFileStr;
pro.TXDH = Convert.ToInt16(spTXDH.Text);
pro.ZYJD = Convert.ToInt16(txtZYJD.Text);
//设置工作目录下的工程目录
string dispalyName = xzqCoderesult.FirstOrDefault(x => x.CODE == txt_Box.SelectedValue.ToTrim()).NAME;
string itemType = string.Format("{0}({1})", dispalyName, txt_Box.SelectedValue.ToTrim());//作为工作目录次级目录文件夹
pro.ProWorkDir = itemType;// btnPrjDir.Text.ToString();//工作目录工程文件夹
pro.ProjDir = System.IO.Path.Combine(btnPrjDir.Text.ToString(), itemType + "\\工程目录\\" + pro.ProjName);
//存放年初数据文件夹路径
//pro.JCKPath = System.IO.Path.Combine(btnPrjDir.Text.ToString(), itemType + "\\年初数据");
//设置举证成果的文件夹路径
pro.DBPath = System.IO.Path.Combine(btnPrjDir.Text.ToString(), itemType + "\\举证成果");
pro.BGResultPath = System.IO.Path.Combine(btnPrjDir.Text.ToString(), itemType + "\\变更成果");
#region 工程信息增加
string s = projType.Tag.ToTrim();
pro.ProjType = (EnumProjType)System.Enum.Parse(typeof(EnumProjType), s);
//加载调入本县范围的其他区县基础库
pro.DR_DataKPaths = new List<string>();
if (HRDataPaths != null && HRDataPaths?.Count > 1)
foreach (HRDataPath item in HRDataPaths)
{
if (!string.IsNullOrWhiteSpace(item.HRPath))
pro.DR_DataKPaths.Add(item.HRPath);
}
pro.XZQDMChange = cb_XZQDMChange.IsChecked == true;
//同步全局调查面积
pro.DCMJ = pro.KZMJ.TZH_LDMJ.ToDouble();
pro.DCMJHD = pro.KZMJ.TZH_HDMJ.ToDouble();
#endregion
Setworkapacepath = btnPrjDir.Text.ToString();
DirectoryCopys(Setworkapacepath, itemType);
ClearKCDLSXData();
#region 验证:依据配置记录中的地址遍历去验证发现如果工程文件不在的就把记录删掉
SysConfigsOprator configOp = new SysConfigsOprator();
int iDelFailCount_Temp = 0;
string strRecentOpenProjectRecordXmlPath = Setworkapacepath + "\\RecentWorkCatalogRecord.xml";
if (File.Exists(strRecentOpenProjectRecordXmlPath) == true)
{
List<string> iInvalidPathXMLList = configOp.GetExcludeInvalidRecentOpenProjectRecordXmlMsg(strRecentOpenProjectRecordXmlPath);
if (iInvalidPathXMLList != null && iInvalidPathXMLList.Count() > 0)
{
bool bDelTemp = false;
for (int ut = 0; ut < iInvalidPathXMLList.Count(); ut++)
{
bDelTemp = configOp.DeleteProjectFileOpenTime(strRecentOpenProjectRecordXmlPath, iInvalidPathXMLList[ut]);
if (bDelTemp == false)
{
iDelFailCount_Temp += 1;
}
}
}
if (iDelFailCount_Temp > 0)
LogAPI.Debug("依据配置记录中的地址遍历去验证发现如果KBG文件不在的就把记录删掉 时失败,请排查 ; ");
}
#endregion
//验证同名工程是否存在
if (!Directory.Exists(pro.ProjDir))
{
Directory.CreateDirectory(pro.ProjDir);
}
else
{
this.CloseLoading();
MessageHelper.ShowTips("当前目录下已存在同名工程!");
return;
}
string strMxdPath = string.Empty;
if (pro.ProjSuffix == ".KBG")
{
if (pro.ProjType == EnumProjType.BHTBTQ)
{
DirectoryCopy(SysAppPath.GetCurrentAppPath() + string.Format("工作空间\\模板\\新建变更工程\\{0}\\BHDB.gdb", (int)Math.Floor(Math.Round(10 / pro.XYResolution))), pro.ProjDir);
strMxdPath = SysAppPath.GetCurrentAppPath() + "工作空间\\模板\\新建变更工程\\LatersToXMLForBHTBTQ.xml";
}
else
strMxdPath = SysAppPath.GetCurrentAppPath() + "工作空间\\模板\\新建变更工程\\LatersToXML.xml";
File.Copy(SysAppPath.GetCurrentAppPath() + "工作空间\\模板\\新建变更工程\\ReportData.db", pro.ProjDir + "\\ReportData.db");
File.Copy(SysAppPath.GetCurrentAppPath() + "工作空间\\模板\\新建变更工程\\dic.mdb", pro.ProjDir + "\\dic.mdb");
File.Copy(SysAppPath.GetCurrentAppPath() + "工作空间\\模板\\新建变更工程\\DataCheckrResult.db", pro.ProjDir + "\\DataCheckrResult.db");
File.Copy(SysAppPath.GetCurrentAppPath() + "工作空间\\模板\\新建变更工程\\BGTJ.sqlite", pro.ProjDir + "\\BGTJ.sqlite");
File.Copy(SysAppPath.GetBGGDLXConfigPath(), pro.ProjDir + "\\BG_GDLXConfig.xml");
pro.DataBaseName = "PrjDB.gdb";
}
LayerCfg StrLayerInfo = SerializeAPI.DeserializeToObject2<LayerCfg>(strMxdPath);
StrLayerInfo.LayerName = pro.ProjName;
Byte[] bytearr = System.Text.Encoding.Default.GetBytes(SerializeAPI.SerializeToXML<LayerCfg>(StrLayerInfo));
string strBase64 = Convert.ToBase64String(bytearr);
pro.TempData = strBase64;
Platform.Instance.Progress.SetWorkPath(System.IO.Path.GetDirectoryName(pro.ProjDir));
//设置坐标系
if (pro.ProjType == EnumProjType.BHTBTQ)
{
string BhDatabase = System.IO.Path.Combine(pro.ProjDir, "BHDB.gdb");
IWorkspaceAPI wsAPI = new WorkspaceAPI(BhDatabase, KGIS.Framework.AE.Enum.WorkspaceTypeEnum.GDBFile);
//GeoDBAPI.SetGeoDatasetSpatialReference(wsAPI.CurrentWorkspace, MapsManager.Instance.MapService.getAxMapControl().SpatialReference, pro.XYResolution);
ISpatialReference reference = GetCurentProjectedCoordinate();
GeoDBAPI.SetGeoDatasetSpatialReference(wsAPI.CurrentWorkspace, reference, pro.XYResolution);
wsAPI.CloseWorkspace();
}
if (pro.Save())
{
IMapService mapService = MapsManager.Instance.MapService;
//设置工作目录时同时会加载
mapService.LoadProject(pro.ProjDir + "\\" + pro.ProjName + pro.ProjSuffix);
mapService.SetFolderPath(pro.ProjDir);//获取工程目录路径
Platform.Instance.ViewManager.SetFilePath(pro.ProjDir);
Platform.Instance.AppMenuManager.HideAppMenu();
#region 创建系统配置文件
//if (SystemCfg != null)
//{
// string layerConfigsPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs", "LoadLayersConfig.xml");
// if (File.Exists(layerConfigsPath))
// {
// SystemCfg.BaseLoadCfg = new JCSJLayers();
// XDocument xDoc = XDocument.Load(layerConfigsPath);
// XElement configElement = xDoc.Element("LayersConfig");
// XElement jcsjLayersElment = configElement.Element("JCSJLayers");
// if (jcsjLayersElment != null)
// {
// foreach (XElement item in jcsjLayersElment.Elements("Layer"))
// {
// LayerCfg layer = new LayerCfg();
// layer.LayerName = item.Attribute("Name").Value;
// //layer.LayerAliasName = item.Attribute("AliasName").Value;
// //layer.Order = Convert.ToInt32(item.Attribute("Order").Value);
// layer.Required = item.Attribute("Required").Value.ToLower() == "true" ? true : false;
// SystemCfg.BaseLoadCfg.LayerInfo.Add(layer);
// }
// }
// }
// SystemCfg.Save();
//}
#endregion
this.Close();
}
//if (pro.ProjType == EnumProjType.BHTBTQ)
// CreateBHTBTQ();
Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "SaveProject" });
}
catch (Exception ex)
{
MessageHelper.ShowError("新建工程失败:" + ex.Message);
LogAPI.Debug("新建工程时发生异常,异常信息如下:");
LogAPI.Debug(ex);
LogAPI.Debug("异常信息结束。");
}
finally
{
btnOK.IsEnabled = true;
btnCanel.IsEnabled = true;
this.CloseLoading();
_workCatalog.IsLoadProject = false;
//重新加载工作目录列表
_workCatalog.SetWorksapce(Setworkapacepath);
_workCatalog.IsLoadProject = true;
}
}
/// <summary>
/// 创建投影坐标系
/// </summary>
/// <param name="pcType">esriSRProjCS4Type</param>
/// <returns></returns>
public ISpatialReference GetCurentProjectedCoordinate()
{
try
{
if (!string.IsNullOrWhiteSpace(PrjFileStr))
{
//创建一个要素集创建一个投影
ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass();
ISpatialReference pSpatialReference;
PrjFileStr = PrjFileStr.Replace("'", "\"");
pSpatialRefFac.CreateESRISpatialReference(PrjFileStr, out pSpatialReference, out int s);
return pSpatialReference;
}
return null;
}
catch (Exception ex)
{
LogAPI.Debug("创建投影坐标系失败:" + ex.Message);
return null;
}
}
/// <summary>
/// 文件夹复制
/// </summary>
/// <param name="sourceDir">原文件夹</param>
/// <param name="targetDirPath">目标目录</param>
/// <returns>是否成功复制</returns>
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 + " ; ");
return false;
throw;
}
}
/// <summary>
/// 文件夹复制
/// </summary>
/// <param name="sourceDir">原文件夹</param>
/// <param name="targetDirPath">目标目录</param>
/// <returns>是否成功复制</returns>
public bool DirectoryCopy(string sourceDir, string targetDirPath, bool Isfa)
{
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, true);
}
}
return true;
}
catch (Exception ex)
{
LogAPI.Debug("新建工程页面中,文件夹复制时失败,异常原因: " + ex + " ; ");
return false;
throw;
}
}
private void BtnCanel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void IsBG_Checked(object sender, RoutedEventArgs e)
{
if (IsBG.IsChecked == true)
{
TZQLDKZMJ.Visibility = Visibility.Visible;
BGLDMJ.Visibility = Visibility.Visible;
LDDCMJ.Visibility = Visibility.Collapsed;
BGHDMJ.Visibility = Visibility.Visible;
HDDCMJ.Visibility = Visibility.Collapsed;
}
else
{
TZQLDKZMJ.Visibility = Visibility.Collapsed;
BGLDMJ.Visibility = Visibility.Collapsed;
LDDCMJ.Visibility = Visibility.Visible;
BGHDMJ.Visibility = Visibility.Collapsed;
HDDCMJ.Visibility = Visibility.Visible;
}
}
#region 行政区
private void BtnSelectedXZQPath_Click(object sender, RoutedEventArgs e)
{
string FcPath = string.Empty;
GetSelectionFc(ref FcPath);
btnXZQPath.Text = FcPath;
}
#endregion
#region 调入村级调查区
private void BtnSelectedCJDCQPath_Click(object sender, RoutedEventArgs e)
{
string FcPath = string.Empty;
GetSelectionFc(ref FcPath);
btnCJDCQPath.Text = FcPath;
}
#endregion
private IFeatureClass GetSelectionFc(ref string strFcPath)
{
IFeatureClass result = null;
try
{
// 获取源数据
OpenDataDialog pDialog = new OpenDataDialog();
ISpatialDataObjectFilter pOFilter;
pOFilter = new FilterFeatureDatasetsAndFeatureClasses();
pDialog.AddFilter(pOFilter, true);
pDialog.Title = "选择划调整范围数据";
pDialog.AllowMultiSelect = false;
pDialog.RestoreLocation = true;
pDialog.StartLocation = pDialog.FinalLocation;
if (pDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && pDialog.Selection.Count > 0)
{
List<ISpatialDataObject> distObj = pDialog.Selection;
foreach (var obj in distObj)
{
if (obj.DatasetType == esriDatasetType.esriDTFeatureClass)
{
result = (obj.DatasetName as IName).Open() as IFeatureClass;
strFcPath = obj.FullName;
}
}
}
else
{
return result;
}
}
catch (Exception ex)
{
LogAPI.Debug("选择数据失败:" + ex.Message.ToString());
}
return result;
}
/// <summary>
/// 清空扣除地类系数
/// </summary>
private void ClearKCDLSXData()
{
string strPath = SysAppPath.GetBGGDLXConfigPath();
XDocument xDoc = XDocument.Load(strPath);
foreach (XElement xElement in xDoc.Descendants("Item"))
{
xElement.Attributes("KCDLXS").Single().Value = "0";
}
xDoc.Save(strPath);
}
private void btnSelectedCZCPath_Click(object sender, RoutedEventArgs e)
{
string FcPath = string.Empty;
GetSelectionFc(ref FcPath);
btnczcPath.Text = FcPath;
}
private void projectType_SelectedIndexChanged(object sender, RoutedEventArgs e)
{
if ((sender as ComboBoxEdit).Items.Count <= 0) return;
if (DRCJDCQ == null) return;
if (((sender as ComboBoxEdit).Items[0] as ComboBoxEditItem).Content.ToString() == "变化图斑提取类型")
{
DRCJDCQ.Visibility = Visibility.Collapsed;
DRXZQ.Visibility = Visibility.Collapsed;
DRCZC.Visibility = Visibility.Collapsed;
ZLBHXX.Visibility = Visibility.Collapsed;
this.Height = 350;
}
else
{
DRCJDCQ.Visibility = Visibility.Visible;
DRXZQ.Visibility = Visibility.Visible;
DRCZC.Visibility = Visibility.Visible;
ZLBHXX.Visibility = Visibility.Visible;
this.Height = 660;
}
projType.Content = ((sender as ComboBoxEdit).Items[0] as ComboBoxEditItem).Content;
projType.Tag = (projectType.SelectedItem as ComboBoxEditItem).Tag;
}
//加载调入本县范围的其他区县基础库
private void Txt_Add_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
IWorkspaceAPI workApi = null;
try
{
string FinalLocation = "";
PluginServiceInterface.Helper.OpenDataDialogHelper.OpenDataDialog("选择调入本县范围的其他区县基础库", ref FinalLocation);
if (!string.IsNullOrWhiteSpace(FinalLocation))
{
string ImportDataType = System.IO.Path.GetExtension(FinalLocation).ToUpper().Replace('.', ' ').TrimStart();
WorkspaceTypeEnum workspaceType = ImportDataType == "GDB" ? WorkspaceTypeEnum.GDBFile : WorkspaceTypeEnum.MDBFile;
workApi = new WorkspaceAPI(FinalLocation, workspaceType, true);
if (!workApi.ExistFeatureClass("CJDCQ"))
{
MessageHelper.ShowError("缺失CJDCQ图层数据!");
return;
}
else if (!workApi.ExistFeatureClass("CZCDYD"))
{
MessageHelper.ShowError("缺失CZCDYD图层数据!");
return;
}
else if (!workApi.ExistFeatureClass("XZQ"))
{
MessageHelper.ShowError("缺失XZQ图层数据!");
return;
}
else if (!workApi.ExistFeatureClass("DLTB"))
{
MessageHelper.ShowError("缺失DLTB图层数据!");
return;
}
string ExceptionMessage = string.Empty;
IFeatureClassAPI TempFL = null;
foreach (var item in "DLTB,CZCDYD,CJDCQ,XZQ".Split(','))
{
TempFL = workApi.OpenFeatureClass2(item);
CheackJCGDB(new FeatureLayer() { FeatureClass = TempFL.FeatureClass }, ref ExceptionMessage);
TempFL.CloseFeatureClass();
}
if (!string.IsNullOrWhiteSpace(ExceptionMessage))
{
LogAPI.Debug("基础数据加载数据异常提示:" + ExceptionMessage);
MessageHelper.ShowTips(ExceptionMessage);
return;
}
if (HRDataPaths?.Count > 0)
if (HRDataPaths.FirstOrDefault(x => x.HRPath.Trim().Equals(FinalLocation.Trim())) != null)
{
MessageHelper.ShowError("划入数据路径重复!");
return;
}
HRDataPaths.Add(new HRDataPath()
{
ID = HRDataPaths.OrderByDescending(x => x.ID).FirstOrDefault().ID + 1,
HRPath = FinalLocation
});
}
if (HRDataPaths?.Count >= 2)
gvCtrl.ItemsSource = HRDataPaths.FindAll(x => !string.IsNullOrWhiteSpace(x.HRPath)).ToList();
gvCtrl.RefreshData();
}
catch (Exception ex)
{
MessageHelper.ShowError("添加路径报错:" + ex.Message);
}
}
private void Txt_Del_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try
{
if (sender is TextBlock TextBlock)
{
var Info = HRDataPaths.FirstOrDefault(f => f.ID == TextBlock.Tag.ToInt());
HRDataPaths.Remove(Info);
if (HRDataPaths.Count == 0)
HRDataPaths.Add(new HRDataPath() { ID = 0, HRPath = "", HRCode = "000000" });
if (HRDataPaths?.Count >= 2)
gvCtrl.ItemsSource = HRDataPaths.FindAll(x => !string.IsNullOrWhiteSpace(x.HRPath)).ToList();
else
{
gvCtrl.ItemsSource = HRDataPaths;
}
gvCtrl.RefreshData();
}
}
catch (Exception ex)
{
LogAPI.Debug("删除信息失败:" + ex.Message);
}
}
public void CheackJCGDB(IFeatureLayer JClayer, ref string ExceptionMessage)
{
try
{
if (!"DLTB,CZCDYD,CJDCQ,XZQ".Contains(((IDataset)JClayer.FeatureClass).Name.ToUpper()))
ExceptionMessage += $"Err:{JClayer.FeatureClass.AliasName}要素类名称非国家标准名称,需使用国家下发的原始基础库;\n";
if (JClayer.FeatureClass.OIDFieldName != "OBJECTID")
ExceptionMessage += $"Err:{JClayer.FeatureClass.AliasName}数据主键字段非“OBJECTID”,需使用国家下发的原始基础库;\n";
if (JClayer.FeatureClass.Fields.FieldCount == 0)
ExceptionMessage += $"Err:{JClayer.FeatureClass.AliasName}数据字段结构与国家下发模板存在差异,需使用国家下发的原始基础库;\n";
string FieldsJH = string.Empty;
if (((IDataset)JClayer.FeatureClass).Name.ToUpper() == "DLTB")
FieldsJH = "OBJECTID,BSM,TBYBH,YSDM,TBBH,DLBM,DLMC,QSXZ,QSDWDM,QSDWMC,ZLDWDM,ZLDWMC,TBMJ,KCDLBM,KCXS,KCMJ,TBDLMJ,GDLX,GDPDJB,XZDWKD,TBXHDM,TBXHMC,ZZSXDM,ZZSXMC,GDDB,FRDBS,CZCSXM,SJNF,MSSM,HDMC,BZ";
else if (((IDataset)JClayer.FeatureClass).Name.ToUpper() == "CZCDYD")
FieldsJH = "OBJECTID,CZCDM,CZCMC,CZCLX,YSDM,BSM,CZCMJ,BZ";
else if (((IDataset)JClayer.FeatureClass).Name.ToUpper() == "CJDCQ")
FieldsJH = "OBJECTID,BSM,YSDM,ZLDWDM,ZLDWMC,DCMJ,JSMJ,MSSM,HDMC,BZ";
else if (((IDataset)JClayer.FeatureClass).Name.ToUpper() == "XZQ")
FieldsJH = "OBJECTID,BSM,YSDM,XZQDM,XZQMC,DCMJ,JSMJ,MSSM,HDMC,BZ";
foreach (var item in FieldsJH.Split(','))
{
int fieldIndex = JClayer.FeatureClass.Fields.FindField(item);
if (fieldIndex == -1)
ExceptionMessage += $"Err:{JClayer.FeatureClass.AliasName}数据缺失字段“{item}”,需使用国家下发的原始基础库;\n";
}
for (int i = 0; i < JClayer.FeatureClass.Fields.FieldCount; i++)
{
IField field = JClayer.FeatureClass.Fields.get_Field(i);
if (!field.Editable || field.Name.ToUpper().Contains("SHAPE") || field.Name.ToUpper().Contains("XZQTZLX") || field.Name.ToUpper().Contains("GXSJ"))
continue;//字段 “SHAPE” “XZQTZLX” “GXSJ” 作为系统例外字段
if (!FieldsJH.Contains(field.Name))
ExceptionMessage += $"Err:{JClayer.FeatureClass.AliasName}数据出现非国家下发模板字段“{field.Name}”,需使用国家下发的原始基础库;\n";
}
}
catch (Exception ex)
{
throw new Exception($"{ex.Message}");
}
}
private void BtnPrjFile_LostFocus(object sender, RoutedEventArgs e)
{
try
{
if (!string.IsNullOrEmpty(btnPrjFile.Text))
{
string path = System.IO.Path.Combine(SysAppPath.GetCurrentAppPath(), @"CGCS2000");
string[] files = Directory.GetFiles(path, "*.prj");
for (int i = 0; i < files.Length; i++)
{
string name = System.IO.Path.GetFileNameWithoutExtension(files[i]);
if (name.EndsWith(btnPrjFile.Text.TrimEnd()))
{
ISpatialReference spatialReference = GetSpatialReference(files[i]);
SetPRJBySp(spatialReference);
break;
}
}
}
}
catch (Exception ex)
{
LogAPI.Debug(ex);
}
}
private void Txt_Box_SelectionChanged(object sender, RoutedEventArgs e)
{
#if DEBUG
if (!string.IsNullOrWhiteSpace(txt_Box.Text))
{
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
{
{ "350426-尤溪县", "34" },
{ "610303-金台区", "36" },
{ "350703-建阳区", "39" },
{ "350421-明溪县", "39" },
{ "624001-甘肃中农发山丹马场", "39" },
{ "350429-泰宁县", "39" },
{ "350206-湖里区", "39" },
{ "330703-金东区", "40" },
{ "330502-吴兴区", "40" },
{ "330213-奉化区", "40" },
{ "330282-慈溪区", "40" },
{ "350128-平潭县", "40" },
{ "330281-余姚市", "40" },
{ "331123-遂昌县", "40" },
{ "330292-前湾新区", "40" },
{ "330225-象山县", "41" },
{ "220802-洮北区", "41" },
{ "220183-德惠市", "42" },
{ "220284-磐石市", "42" },
{ "220104-朝阳区", "42" },
{ "220203-龙潭区", "42" },
{ "220403-西安区", "42" }
};
if (keyValuePairs.TryGetValue(txt_Box.Text, out string CodeValue))
{
btnPrjFile.Text = CodeValue;
BtnPrjFile_LostFocus(null, null);
}
}
#else
#endif
}
}
}