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

771 lines
31 KiB

6 months ago
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using KGIS.Framework.AE.ExtensionMethod;
using KGIS.Framework.Core.Services;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.ExtensionMethod;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
namespace Kingo.PluginServiceInterface
{
public static class CommonHelper
{
[System.Runtime.InteropServices.DllImport("winInet.dll")]
private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);
/// <summary>
/// 判断本机是否联网
/// </summary>
/// <returns></returns>
public static bool IsConnectNetwork()
{
try
{
//return false;
int dwFlag = 0;
//false表示没有连接到任何网络,true表示已连接到网络上
if (!InternetGetConnectedState(ref dwFlag, 0))
{
//if (!InternetGetConnectedState(ref dwFlag, 0))
// Console.WriteLine("未连网!");
//else if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
// Console.WriteLine("采用调治解调器上网。");
//else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
// Console.WriteLine("采用网卡上网。");
return false;
}
Task<bool> task = new System.Threading.Tasks.TaskFactory().StartNew(() =>
{
//判断当前网络是否可用
IPAddress[] addresslist = Dns.GetHostAddresses("www.baidu.com");
if (addresslist[0].ToString().Length <= 6)//未联网
{
return false;
}
else//联网
{
return true;
}
//ping方法判断是否联网
//System.Net.NetworkInformation.Ping a = new System.Net.NetworkInformation.Ping();
//System.Net.NetworkInformation.PingReply re = a.Send("www.baidu.com", 10);
//return (re.Status == System.Net.NetworkInformation.IPStatus.Success);
});
/*
* 100广ping百度网站时一直不返回
* 100
* 线
*/
if (task.Wait(100))//在分配的时间(100毫秒)内完成执行
{
return task.Result;
}
else//超过100毫秒未返回,则当做是未联网状态
{
return false;
}
}
catch //(Exception ex)
{
//LogAPI.Debug("判断本机器是否联网异常:" + ex.Message);
return false;
}
}
/// <summary>
/// 对象深拷贝
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T DeepCopyByBin<T>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
//序列化成流
bf.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
//反序列化成对象
retval = bf.Deserialize(ms);
ms.Close();
}
return (T)retval;
}
/// <summary>
/// 复制或剪切文件到剪切板
/// </summary>
/// <param name="files">文件路径数组</param>
/// <param name="cut">true:剪切;false:复制</param>
public static void CopyToClipboard(object obj, bool cut = false, EnumCopyType enumCopyType = EnumCopyType.enumText)
{
try
{
if (obj == null || string.IsNullOrWhiteSpace(obj.ToString()))
{
return;
}
IDataObject data = null;
switch (enumCopyType)
{
case EnumCopyType.enumText:
data = new DataObject(DataFormats.Text, obj.ToString()) as IDataObject;
break;
case EnumCopyType.enumFiles:
data = new DataObject(DataFormats.FileDrop, obj) as IDataObject;
break;
}
System.IO.MemoryStream memo = new System.IO.MemoryStream(4);
byte[] bytes = new byte[] { (byte)(cut ? 2 : 5), 0, 0, 0 };
memo.Write(bytes, 0, bytes.Length);
data.SetData("PreferredDropEffect", memo);
Clipboard.SetDataObject(data, false);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 文件夹复制
/// </summary>
/// <param name="sourceDir">原文件夹</param>
/// <param name="targetDirPath">目标目录</param>
/// <returns>是否成功复制</returns>
public static bool DirectoryCopy(string sourceDir, string targetDirPath)
{
try
{
if (!System.IO.Directory.Exists(sourceDir))
{
return false;
}
string targetDir = targetDirPath + "\\" + System.IO.Path.GetFileName(sourceDir);
if (!System.IO.Directory.Exists(targetDir))
{
System.IO.Directory.CreateDirectory(targetDir);
}
// 文件及文件夹名称数组
string[] dirColl = System.IO.Directory.GetDirectories(sourceDir);
string[] fileColl = System.IO.Directory.GetFiles(sourceDir);
// 便利所有文件
if (fileColl.Length > 0)
{
string fileName;
foreach (string fileDir in fileColl)
{
fileName = System.IO.Path.GetFileName(fileDir);
System.IO.File.Copy(sourceDir + "\\" + fileName, targetDir + "\\" + fileName, true);
}
}
// 遍历所有文件夹
if (dirColl.Length > 0)
{
string folderName;
foreach (string dir in dirColl)
{
folderName = System.IO.Path.GetFileName(dir);
// 递归调用
System.IO.Directory.CreateDirectory(targetDir + "\\" + folderName);
DirectoryCopy(dir, targetDir + "\\" + folderName);
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 清空文件夹(文件占用不处理)
/// </summary>
/// <param name="srcPath"></param>
public static void DelectDir(string srcPath)
{
try
{
if (!Directory.Exists(srcPath)) return;
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)
{ }
}
/// <summary>
/// 清空文件夹且是否发生占用
/// </summary>
/// <param name="srcPath"></param>
/// <returns></returns>
private static bool 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); //删除指定文件
}
}
return true;
}
catch (Exception e)
{
LogAPI.Debug("工程目录文件有占用,请退出占用后重试!" + e);
return false;
}
}
/// <summary>
/// 设置文件夹以及文件夹下文件为只读或非只读
/// </summary>
/// <param name="folderPath"></param>
public static void SetFolderReadOnly(string folderPath, bool readOnly = true)
{
try
{
SetSubFolderReadOnly(folderPath, readOnly);
}
catch (Exception ex)
{
LogAPI.Debug("设置文件夹以及文件夹下文件为只读或非只读" + ex);
throw ex;
}
}
/// <summary>
/// 递归设置文件夹及文件夹下所有文件权限
/// </summary>
/// <param name="folderPath"></param>
/// <param name="readOnly"></param>
private static void SetSubFolderReadOnly(string folderPath, bool readOnly = true)
{
try
{
System.IO.DirectoryInfo DirInfo = new DirectoryInfo(folderPath);
System.IO.DirectoryInfo[] directoryInfos = DirInfo.GetDirectories();
if (directoryInfos != null && directoryInfos.Length > 0)
{
foreach (var item in directoryInfos)
{
SetSubFolderReadOnly(item.FullName, readOnly);
}
}
FileInfo[] fileInfos = DirInfo.GetFiles();
if (fileInfos != null && fileInfos.Length > 0)
{
foreach (var item in fileInfos)
{
SetFileReadAccess(item.FullName, readOnly);
}
}
if (readOnly)
{
DirInfo.Attributes = FileAttributes.ReadOnly & FileAttributes.Directory;
}
else
{
DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 设置文件只读或非只读
/// </summary>
/// <param name="FileName"></param>
/// <param name="SetReadOnly"></param>
public static void SetFileReadAccess(string FileName, bool SetReadOnly = true) //注意这个函数
{
try
{
FileInfo fInfo = new FileInfo(FileName);
if (fInfo.IsReadOnly != SetReadOnly)
{
fInfo.IsReadOnly = SetReadOnly;
}
}
catch (Exception ex)
{
throw new Exception("设置文件只读异常:" + ex.Message);
}
}
/// <summary>
/// 读取text文件内容
/// </summary>
/// <param name="FilePath">文件路径</param>
/// <returns></returns>
public static string ReadTextFileConten(string FilePath)
{
string content = string.Empty;
try
{
// 创建一个 StreamReader 的实例来读取文件
// using 语句也能关闭 StreamReader
using (StreamReader sr = new StreamReader(FilePath))
{
string line;
// 从文件读取并显示行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
content += line;
}
}
}
catch (Exception ex)
{
throw ex;
}
return content;
}
/// <summary>
/// 执行压缩SQLite数据库
/// </summary>
/// <returns>压缩数据库db路径</returns>
public static void ExecuteZip(string dbPath)
{
IRDBHelper rdbHelper = null;
try
{
rdbHelper = RDBFactory.CreateDbHelper($"{dbPath}{(MapsManager.Instance.CurrProjectInfo as ProjectInfo).Pathpassword}", DatabaseType.SQLite);
rdbHelper.ExecuteNonQueryWithException("VACUUM", System.Data.CommandType.Text);
}
catch (Exception ex)
{
throw new Exception("输出成果压缩db异常:" + ex.Message);
}
finally
{
if (rdbHelper != null)
{
rdbHelper.DisConnect();
}
}
}
/// <summary>
/// 从UserLoginConfig.xml中获取指定key的值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetAppsetingValueByKey(string key)
{
try
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
string strPath = SysAppPath.GetConfigPath() + "UserLoginConfig.xml";
doc.Load(strPath);
System.Xml.XmlNode xmlSysNode = doc.SelectSingleNode("configuration/AppSettings");
if (xmlSysNode.ChildNodes != null && xmlSysNode.ChildNodes.Count > 0)
{
foreach (System.Xml.XmlNode node in xmlSysNode.ChildNodes)
{
if (node.Attributes["Key"].Value == key)
{
return node.Attributes["Value"].Value;
}
}
}
return "";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
}
/// <summary>
/// 更新配置文件UserLoginConfig.xml值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static void UpdateAppsettingValueByKey(string key, string value, string XMLName)
{
try
{
XmlDocument doc = new XmlDocument();
string strPath = SysAppPath.GetConfigPath() + $"{XMLName.Trim()}.xml";
doc.Load(strPath);
XmlNode xmlSysNode = doc.SelectSingleNode("configuration/AppSettings");
if (xmlSysNode.ChildNodes != null && xmlSysNode.ChildNodes.Count > 0)
{
foreach (XmlNode node in xmlSysNode.ChildNodes)
{
if (node.Attributes["Key"].Value == key)
{
node.Attributes["Value"].Value = value;
doc.Save(strPath);
break;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 执行地图工具
/// </summary>
/// <param name="HandleName">执行功能名</param>
public static void ExeCommandOperation(string HandleName)
{
string CommandID = string.Empty;
string BundleSymbolicName = string.Empty;
switch (HandleName)
{
case "执行结束编辑":
CommandID = "Kingo.Plugin.EngineEditor.Commands.Commands.ControlsStopEditToolCommand";
BundleSymbolicName = "Kingo.Plugin.EngineEditor";
break;
case "执行全图":
CommandID = "Kingo.Plugin.MapView.Commands.ControlsMapFullExtent";
BundleSymbolicName = "Kingo.Plugin.MapView";
break;
case "执行数据解压":
CommandID = "Kingo.Plugin.DTBJK.Commands.CmdDecompressionDB";
BundleSymbolicName = "Kingo.Plugin.DTBJK";
break;
default:
break;
}
ExeCommandIDByBundle(CommandID, BundleSymbolicName);
}
/// <summary>
/// 执行已执行插件的配置功能(无参)
/// </summary>
/// <param name="CommandID">例如:Kingo.Plugin.MapView.Commands.CmdSaveProject</param>
/// <param name="BundleSymbolicName">例如:Kingo.Plugin.MapView</param>
private static void ExeCommandIDByBundle(string CommandID, string BundleSymbolicName)
{
try
{
if (string.IsNullOrWhiteSpace(CommandID) || string.IsNullOrWhiteSpace(BundleSymbolicName) || UIShell.OSGi.BundleRuntime.Instance == null)
return;
var bundle = UIShell.OSGi.BundleRuntime.Instance.Framework.Bundles.Find(x => x.SymbolicName.Equals(BundleSymbolicName));
if (bundle == null) return;
KGIS.Framework.Commands.ICommandManager _CmdManager = UIShell.OSGi.BundleRuntime.Instance.GetFirstOrDefaultService<KGIS.Framework.Commands.ICommandManager>();
if (_CmdManager != null)
{
var pCmd = _CmdManager.AddCmd(CommandID, bundle, null);
if (pCmd is BaseMapMenuCommand)
KGIS.Framework.Menus.ServicesInvokes.CommandManagerInvoke.ExeCommand(pCmd, null);
if (pCmd is ESRI.ArcGIS.SystemUI.ICommand)
(pCmd as ESRI.ArcGIS.SystemUI.ICommand).OnClick();
}
}
catch (Exception ex)
{
LogAPI.Debug("执行已执行插件的配置功能失败:" + ex);
throw ex;
}
}
/// <summary>
/// DataTable转换成IList
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToList<T>(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
{
return new List<T>();
}
PropertyInfo[] properties = typeof(T).GetProperties();//获取实体类型的属性集合
List<T> list = new List<T>();
T model = default(T);
foreach (DataRow dr in dt.Rows)
{
model = Activator.CreateInstance<T>();//创建实体
foreach (PropertyInfo p in properties)
{
foreach (DataColumn col in dt.Columns)
{
try
{
if (col.ColumnName.ToLower().Equals(p.Name.ToLower()))
{
object obj = dr[col.ColumnName];
if (obj == null || obj is DBNull)
break;
if (obj.ToString().Replace(" ", "").Length == 0)
break;
if (p.PropertyType == typeof(string))
{
p.SetValue(model, obj.ToString(), null);
}
else if (p.PropertyType == typeof(int) || p.PropertyType == typeof(int?))
{
p.SetValue(model, int.Parse(obj.ToString()), null);
}
else if (p.PropertyType == typeof(DateTime) || p.PropertyType == typeof(DateTime?))
{
p.SetValue(model, DateTime.Parse(obj.ToString()), null);
}
else if (p.PropertyType == typeof(float) || p.PropertyType == typeof(float?))
{
p.SetValue(model, float.Parse(obj.ToString()), null);
}
else if (p.PropertyType == typeof(double) || p.PropertyType == typeof(double?))
{
p.SetValue(model, double.Parse(obj.ToString()), null);
}
else if (p.PropertyType == typeof(decimal) || p.PropertyType == typeof(decimal?))
{
p.SetValue(model, decimal.Parse(obj.ToString()), null);
}
else if (p.PropertyType == typeof(bool) || p.PropertyType == typeof(bool?))
{
bool b = false;
if (Boolean.TryParse(obj.ToString(), out b))
{
p.SetValue(model, b, null);
}
else
{
if (obj.ToString().Equals("0"))
{
p.SetValue(model, false, null);
}
else
{
p.SetValue(model, true, null);
}
}
}
break;
}
}
catch (Exception ex)
{
LogAPI.Debug("DataTable转换成IList" + ex);
throw ex;
}
}
}
list.Add(model);
}
return list;
}
#region 授权验证
public static bool VerifyMandate(IFeatureClass FeatureClass)
{
bool VerifyMandate = false;
try
{
if ((FeatureClass as FeatureClass).Workspace.Type != esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
IFeatureClassManage fcManage = FeatureClass as IFeatureClassManage;
fcManage.UpdateExtent();
}
IEnvelope envelope = (FeatureClass as IGeoDataset).Extent;
if (string.IsNullOrWhiteSpace(RunIDService2.Instance.Area) || envelope.IsEmpty)
{
#if DEBUG
return true;
#else
LogAPI.Debug("未能获取有效的授权信息,数据导出失败!");
return VerifyMandate;
#endif
}
if (!string.IsNullOrWhiteSpace(RunIDService2.Instance.Area))
{
IGeometry geo = GetPolygonFromWkt(RunIDService2.Instance.Area);
IArea area = geo as IArea;
if (area.Area < 0)
{
(geo as IPolygon).ReverseOrientation();
}
ISpatialReferenceFactory NewSpatialReference = new SpatialReferenceEnvironmentClass();
geo.SpatialReference = NewSpatialReference.CreateGeographicCoordinateSystem(4490);
geo.Project(MapsManager.Instance.MapService.getAxMapControl().SpatialReference);
IPointCollection poly = new PolygonClass();
poly.AddPoint(new PointClass() { X = envelope.XMin, Y = envelope.YMax });
poly.AddPoint(new PointClass() { X = envelope.XMax, Y = envelope.YMax });
poly.AddPoint(new PointClass() { X = envelope.XMax, Y = envelope.YMin });
poly.AddPoint(new PointClass() { X = envelope.XMin, Y = envelope.YMin });
poly.AddPoint(new PointClass() { X = envelope.XMin, Y = envelope.YMax });
IGeometry geo2 = poly as IGeometry;
IPointCollection poly2 = new PolygonClass();
poly2.AddPoint(new PointClass() { X = geo.Envelope.XMin, Y = geo.Envelope.YMax });
poly2.AddPoint(new PointClass() { X = geo.Envelope.XMax, Y = geo.Envelope.YMax });
poly2.AddPoint(new PointClass() { X = geo.Envelope.XMax, Y = geo.Envelope.YMin });
poly2.AddPoint(new PointClass() { X = geo.Envelope.XMin, Y = geo.Envelope.YMin });
poly2.AddPoint(new PointClass() { X = geo.Envelope.XMin, Y = geo.Envelope.YMax });
geo = poly2 as IGeometry;
geo.SpatialReference = MapsManager.Instance.MapService.getAxMapControl().SpatialReference;
geo2.SpatialReference = MapsManager.Instance.MapService.getAxMapControl().SpatialReference;
ITopologicalOperator topo = geo as ITopologicalOperator;
IGeometry newGeo = topo.Intersect(geo2, geo2.Dimension);
double d = geo.GetEllipseArea();
double d1 = geo2.GetEllipseArea();
double newD = newGeo.GetEllipseArea();
if (newD / d1 < 0.8)
return VerifyMandate;
else
VerifyMandate = true;
}
}
catch (Exception ex)
{
VerifyMandate = false;
}
return VerifyMandate;
}
#endregion
#region GetPolygonFromWkt
public static IGeometry GetPolygonFromWkt(string pointsStr)
{
try
{
if (string.IsNullOrWhiteSpace(pointsStr))
return null;
pointsStr = DispalySQ_Click(pointsStr);
//OSGeo.OGR.Ogr.RegisterAll();
IGeometry geometry = new PolygonClass();
OSGeo.OGR.Geometry rstGeometry = OSGeo.OGR.Geometry.CreateFromWkt(pointsStr);
byte[] geometryBytes = new byte[rstGeometry.WkbSize()];
rstGeometry.ExportToWkb(geometryBytes);
IGeometryFactory3 factory = new GeometryEnvironment() as IGeometryFactory3;
int bytesLen = geometryBytes.Length;
factory.CreateGeometryFromWkbVariant(geometryBytes, out geometry, out bytesLen);
IPolygon polygon = geometry as IPolygon;
polygon.Close();
ITopologicalOperator pBoundaryTop = polygon as ITopologicalOperator;
pBoundaryTop.Simplify();
return geometry;
}
catch (Exception ex)
{
return null;
}
}
private static string DispalySQ_Click(string Coord)
{
string SQstring = Coord.Replace('\r', ' ').ToTrim();
if (!string.IsNullOrWhiteSpace(SQstring))
{
string[] rings = SQstring.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
string coord = string.Empty;
if (rings.Length == 1)
{
foreach (var geoRing in rings)
{
string strGeo = geoRing.Replace('\r', ' ').ToTrim();
if (strGeo.Split(new char[] { ';' }).Length < 10)
strGeo = geoRing.Replace(";", ",");
if (strGeo.Contains(";"))
{
coord = string.Format("POLYGON((");
string[] ps = strGeo.TrimEnd(';').Split(';');
foreach (var item in ps)
{
coord += item.Replace('\r', ' ').Replace(',', ' ') + ",";
}
}
else
{
coord = string.Format("POLYGON((");
coord += strGeo;
}
coord = coord.TrimEnd(',');
coord += "))";
}
return coord;
}
else if (rings.Length > 1)
{
coord = "MULTIPOLYGON(";
foreach (var ring in rings)
{
string Temp_Coordinate = string.Empty;
string[] points = ring.TrimEnd(';').Split(';');
string strRing = "((";
if (points.Length == 1)
{
strRing += points[0];
}
else
{
foreach (var item in points)
{
strRing += item.Replace(',', ' ') + ",";
}
}
char[] charsToTrim = { ',' };
strRing = strRing.TrimEnd(charsToTrim);
strRing = strRing.ToTrim();
strRing = strRing.TrimEnd(charsToTrim);
strRing += ")),";
coord += strRing;
}
coord = coord.TrimEnd(',');
coord += ")";
}
return coord;
//AreaEnvOfeat(ConvertWKTToIGeometry(SQstring));
}
return string.Empty;
}
#endregion
}
public enum EnumCopyType
{
enumText = 1,
enumFiles = 2
}
}