using ExportMap.db; using ExportMap.Models; using Npgsql; using System; using System.Collections.Generic; using System.Configuration; using System.Data.Common; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security.AccessControl; using System.Security.Principal; using System.Web; namespace ExportMap.cs { public class Tools { /// /// 基础目录 /// public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory; private static string tempDir; /// /// 临时目录 /// public static string TempDir { get { if (string.IsNullOrWhiteSpace(tempDir)) { tempDir = Path.Combine(BaseDir, "temp"); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } } return tempDir; } } private static PostgreHelper _dbHelper; /// /// DB帮助类 /// public static PostgreHelper DBHelper { get { if (null == _dbHelper) { _dbHelper = new PostgreHelper(); } return _dbHelper; } } /// /// 字节格式化 /// public static string FormatBytes(long bytes) { string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" }; int i = 0; double dblSByte = bytes; if (bytes > 1024) for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024) dblSByte = bytes / 1024.0; return String.Format("{0:0.##}{1}", dblSByte, Suffix[i]); } /// /// 获取设置 /// public static string GetSetting(string key) { return ConfigurationManager.AppSettings[key]; } /// /// 获取Db参数 /// public static List GetParams(string sql, T t) { List list = new List(); Type tType = typeof(T); BindingFlags flags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance; int start = sql.IndexOf("@"); while (start != -1) { int end = sql.IndexOf(",", start); if (end == -1) end = sql.IndexOf(")", start); if (end == -1) end = sql.IndexOf(" ", start); if (end == -1) end = sql.Length; string name = sql.Substring(start + 1, end - start - 1); PropertyInfo pi = tType.GetProperty(name, flags); if (pi != null) { object value = pi.GetValue(t, null); DbParameter dp = new NpgsqlParameter("@" + name, value); list.Add(dp); } start = sql.IndexOf("@", end); } return list; } /// /// 创建目录 /// public static void CreateDirectory(string dir) { WindowsIdentity wi = WindowsIdentity.GetCurrent(); FileSystemAccessRule rule = new FileSystemAccessRule(wi.User, FileSystemRights.FullControl, AccessControlType.Allow); DirectorySecurity ds = new DirectorySecurity(); ds.AddAccessRule(rule); Directory.CreateDirectory(dir, ds); } /// /// 克隆对象 /// public static T Clone(T source) where T : new() { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } using (Stream stream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } /// /// 执行CMD /// /// 任务 /// 命令行 /// 是否为QGIS Py脚本 /// 是否输出错误 /// 执行结果或出错信息 public static string ExecCmd(SysTask task, string cmd, bool isPy = false, bool isOut = false) { List list = new List(); if (isPy) { list.Add("cd \"C:\\Program Files\\QGIS 3.16\\apps\\Python37\""); list.Add("\"C:\\Program Files\\QGIS 3.16\\bin\\qgis_process-qgis-ltr.bat\""); //list.Add("\"C:\\Program Files\\QGIS 3.16\\bin\\python-qgis-ltr.bat\""); //list.Add("exit()"); } list.Add(cmd); string str = ExecCmd(task, list, isOut); return str; } /// /// 执行CMD /// /// 任务 /// 命令集合 /// 是否输出错误 /// 执行结果或出错信息 public static string ExecCmd(SysTask task, List list, bool isOut = false) { string str = null; try { Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; //p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = isOut; p.StartInfo.RedirectStandardError = true; p.Start(); task.pid = p.Id; task.id = TaskDBHelper.Insert(task); StreamWriter si = p.StandardInput; // 标准输入流 StreamReader so = isOut ? p.StandardOutput : null; // 标准输出流 StreamReader se = p.StandardError; // 标准错误流 LogOut.Info("cmd = " + string.Join(",", list)); si.AutoFlush = true; foreach (string cmd in list) { si.WriteLine(cmd); } si.WriteLine("exit"); string info = null == so ? null : so.ReadToEnd(); str = se.ReadToEnd(); //if (!string.IsNullOrEmpty(info)) LogOut.Debug(info); if (!string.IsNullOrEmpty(str) && !str.Contains("@jit(cache=True, nogil=True)")) LogOut.Error(str); if (p.HasExited == false) p.Kill(); task = TaskDBHelper.SelectById(task.id); if (null != task && task.status < 2) { task.status = 2; TaskDBHelper.Update(task); } if (null != so) so.Close(); se.Close(); si.Close(); p.Close(); } catch (Exception ex) { LogOut.Error(ex.Message + "\r\n" + ex.StackTrace); str = ex.Message; task = TaskDBHelper.SelectById(task.id); if (null != task && task.status < 2) { task.err = ex.Message; task.status = 4; TaskDBHelper.Update(task); } } return str; } /// /// 执行命令 /// /// 命令集合 public static string ExecCmd(List list) { string str = null; Process p = null; try { p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.Start(); StreamWriter si = p.StandardInput; StreamReader se = p.StandardError; LogOut.Info("cmd = " + string.Join(",", list)); si.AutoFlush = true; foreach (string cmd in list) { si.WriteLine(cmd); } si.WriteLine("exit"); str = se.ReadToEnd(); se.Close(); si.Close(); } catch (Exception ex) { LogOut.Error(ex.Message + "\r\n" + ex.StackTrace); str = ex.Message; } finally { if (p != null) { p.Close(); p = null; } } return str; } /// /// 创建数据发布类 /// public static SysPublish NewPublish(SysMeta meta, XYZArgs args, string url, string path) { SysPublish sys = new SysPublish(); sys.name = meta.name; sys.url = url; // GetReleaseUrl(meta) sys.type = meta.type; sys.status = 3; sys.dirid = meta.dircode; sys.depid = args.depcode; sys.min = args.min; sys.max = args.max; sys.json = null; sys.create_user = args.userId; sys.geom = null; sys.bak = null; sys.path = path; return sys; } /// /// 删除路径 /// public static string DelPath(string path) { List list = new List(); list.Add(string.Format("rd \"{0}\" /s /q", path)); return ExecCmd(list); } /// /// 设置单体模型参数 /// public static void SetIsModel(XYZArgs args, List list) { if (null == args.models || args.models.Count != args.ids.Count) { foreach (SysMeta meta in list) meta.ismeta = 1; return; } foreach (SysMeta meta in list) { int idx = args.ids.IndexOf(meta.id); meta.ismeta = idx == -1 ? 1 : args.models[idx]; } } /// /// 获取本机IP /// /// public static string GetLocalIP() { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); } } return GetSetting("localIP"); } [DllImport("ReadLas.dll")] public extern static int get_las_cs(string file_name); } }