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); /// /// 判断本机是否联网 /// /// 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 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; } } /// /// 对象深拷贝 /// /// /// /// public static T DeepCopyByBin(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; } /// /// 复制或剪切文件到剪切板 /// /// 文件路径数组 /// true:剪切;false:复制 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; } } /// /// 文件夹复制 /// /// 原文件夹 /// 目标目录 /// 是否成功复制 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; } } /// /// 清空文件夹(文件占用不处理) /// /// 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) { } } /// /// 清空文件夹且是否发生占用 /// /// /// 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; } } /// /// 设置文件夹以及文件夹下文件为只读或非只读 /// /// public static void SetFolderReadOnly(string folderPath, bool readOnly = true) { try { SetSubFolderReadOnly(folderPath, readOnly); } catch (Exception ex) { LogAPI.Debug("设置文件夹以及文件夹下文件为只读或非只读" + ex); throw ex; } } /// /// 递归设置文件夹及文件夹下所有文件权限 /// /// /// 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; } } /// /// 设置文件只读或非只读 /// /// /// 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); } } /// /// 读取text文件内容 /// /// 文件路径 /// 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; } /// /// 执行压缩SQLite数据库 /// /// 压缩数据库db路径 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(); } } } /// /// 从UserLoginConfig.xml中获取指定key的值 /// /// /// 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 ""; } } /// /// 更新配置文件UserLoginConfig.xml值 /// /// /// /// 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; } } /// /// 执行地图工具 /// /// 执行功能名 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); } /// /// 执行已执行插件的配置功能(无参) /// /// 例如:Kingo.Plugin.MapView.Commands.CmdSaveProject /// 例如:Kingo.Plugin.MapView 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(); 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; } } /// /// DataTable转换成IList /// /// /// public static List ToList(DataTable dt) { if (dt == null || dt.Rows.Count == 0) { return new List(); } PropertyInfo[] properties = typeof(T).GetProperties();//获取实体类型的属性集合 List list = new List(); T model = default(T); foreach (DataRow dr in dt.Rows) { model = Activator.CreateInstance();//创建实体 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 } }