管道基础大数据平台系统开发-【CS】-ExportMap
13693261870
2023-12-26 2cf980484c713dfcecce72302b8a757a0c5aedb2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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.Drawing;
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.WebSockets;
 
namespace ExportMap.cs
{
    public class Tools
    {
        /// <summary>
        /// 基础目录
        /// </summary>
        public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory;
 
        /// <summary>
        /// 获取令牌
        /// </summary>
        public static string Token
        {
            get
            {
                return "c36e4f94-dfde-401e-9967-2c4a449f1300";
            }
        }
 
        private static string tempDir;
 
        /// <summary>
        /// 临时目录
        /// </summary>
        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;
 
        /// <summary>
        /// DB帮助类
        /// </summary>
        public static PostgreHelper DBHelper
        {
            get
            {
                if (null == _dbHelper)
                {
                    _dbHelper = new PostgreHelper();
                }
 
                return _dbHelper;
            }
        }
 
        /// <summary>
        /// 获取Py初始化参数
        /// </summary>
        public static string[] PyInitArgs
        {
            get
            {
                string args = GetSetting("pyInitArgs");
 
                return args.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            }
        }
 
        /// <summary>
        /// 字节格式化
        /// </summary>
        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]);
        }
 
        /// <summary>
        /// 获取设置
        /// </summary>
        public static string GetSetting(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
 
        /// <summary>
        /// 获取Db参数
        /// </summary>
        public static List<DbParameter> GetParams<T>(string sql, T t)
        {
            List<DbParameter> list = new List<DbParameter>();
            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;
        }
 
        /// <summary>
        /// 创建目录 *
        /// </summary>
        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);
        }
 
        /// <summary>
        /// 克隆对象 *
        /// </summary>
        public static T Clone<T>(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);
            }
        }
 
        /// <summary>
        /// 执行CMD
        /// </summary>
        /// <param name="task">任务</param>
        /// <param name="cmd">命令行</param>
        /// <param name="isPy">是否为QGIS Py脚本</param>
        /// <param name="isOut">是否输出错误</param>
        /// <returns>执行结果或出错信息</returns>
        public static string ExecCmd(SysTask task, string cmd, bool isPy = false, bool isOut = false)
        {
            List<string> list = new List<string>();
            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.AddRange(PyInitArgs);
                //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;
        }
 
        /// <summary>
        /// 执行CMD
        /// </summary>
        /// <param name="task">任务</param>
        /// <param name="list">命令集合</param>
        /// <param name="isOut">是否输出错误</param>
        /// <returns>执行结果或出错信息</returns>
        public static string ExecCmd(SysTask task, List<string> list, bool isOut = false)
        {
            string str;
            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;
        }
 
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="list">命令集合</param>
        public static string ExecCmd(List<string> 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();
                }
            }
            return str;
        }
 
        /// <summary>
        /// 执行命令
        /// </summary>
        public static string ExecCmd(List<string> list, ref string rs)
        {
            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 so = p.StandardOutput;
                StreamReader se = p.StandardError;
 
                LogOut.Info("cmd = " + string.Join(",", list));
                si.AutoFlush = true;
                foreach (string cmd in list)
                {
                    si.WriteLine(cmd);
                }
                si.WriteLine("exit");
 
                rs = so.ReadToEnd();
                str = se.ReadToEnd();
 
                se.Close();
                so.Close();
                si.Close();
            }
            catch (Exception ex)
            {
                LogOut.Error(ex.Message + "\r\n" + ex.StackTrace);
                str = ex.Message;
            }
            finally
            {
                if (p != null)
                {
                    p.Close();
                }
            }
            return str;
        }
 
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="list">命令集合</param>
        public static string ExecExe(string exe, string args, bool noWin = true)
        {
            string str = null;
            Process p = null;
            try
            {
                p = new Process();
                p.StartInfo.FileName = exe;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = noWin;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                if (!string.IsNullOrEmpty(args)) p.StartInfo.Arguments = args;
 
                p.Start();
                p.WaitForExit();
            }
            catch (Exception ex)
            {
                LogOut.Error(ex.Message + "\r\n" + ex.StackTrace);
                str = ex.Message;
            }
            finally
            {
                if (p != null)
                {
                    p.Close();
                }
            }
            return str;
        }
 
        /// <summary>
        /// 创建数据发布类
        /// </summary>
        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;
        }
 
        /// <summary>
        /// 删除路径
        /// </summary>
        public static string DelPath(string path)
        {
            List<string> list = new List<string>();
            list.Add(string.Format("rd \"{0}\" /s /q", path));
 
            return ExecCmd(list);
        }
 
        /// <summary>
        /// 获取EPSG代码
        /// </summary>
        public static string GetEPSG(string file)
        {
            string gdalPath = GetSetting("gdalPath");
            string cmd = string.Format("{0}\\gdalsrsinfo.exe \"{1}\" -o epsg", gdalPath, file);
 
            string rs = null;
            string ostr = ExecCmd(new List<string> { cmd }, ref rs);
            if (string.IsNullOrEmpty(rs)) return null;
 
            string[] strs = rs.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string str in strs)
            {
                if (str.Contains("EPSG:"))
                {
                    return str;
                }
            }
 
            return null;
        }
 
        /// <summary>
        /// 设置单体模型参数
        /// </summary>
        public static void SetIsModel(XYZArgs args, List<SysMeta> 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];
            }
        }
 
        /// <summary>
        /// 获取本机IP
        /// </summary>
        /// <returns></returns>
        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);
    }
}