ComsStatic.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. using Sunny.UI;
  2. using SuperMap.Data;
  3. using SuperMap.Layout;
  4. using SuperMap.Mapping;
  5. using SuperMap.UI;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Configuration;
  9. using System.Data;
  10. using System.Drawing;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Windows.Forms;
  18. using WeifenLuo.WinFormsUI.Docking;
  19. using WWPipeLine.Commons;
  20. namespace WWPipeLine.MapBasic
  21. {
  22. public class ComsStatic
  23. {
  24. #region Instance
  25. private static ComsStatic m_Instance;
  26. public static ComsStatic Instance
  27. {
  28. get
  29. {
  30. if (m_Instance == null)
  31. m_Instance = new ComsStatic();
  32. return m_Instance;
  33. }
  34. }
  35. private static Workspace m_Workspace;
  36. public void SetWorkspace(Workspace ws) { m_Workspace = ws; }
  37. private static MapControl m_MapControl;
  38. public void SetMapControl(MapControl mp) { m_MapControl = mp; }
  39. private static DockPanel m_DockPanel;
  40. public void SetDockPanel(DockPanel dp) { m_DockPanel = dp; }
  41. private static Datasource m_MemoryDatasource;
  42. public void SetMemoryDatasource(Datasource ds) { m_MemoryDatasource = ds; }
  43. private static IMessageInterface m_IMessageInterface;
  44. public void SetIMessageInterface(IMessageInterface mi) { m_IMessageInterface = mi; }
  45. public static IMessageInterface MessageInterface { get => m_IMessageInterface; }
  46. #endregion
  47. #region 配置文件信息
  48. public static readonly string ConfigsNpgsql = ComsStatic.DesDecrypt(ConfigurationManager.AppSettings["ConfigsNpgsql"], "wwwwwwwwww");
  49. public static string ConfigsNpgsqlServer { get => ConfigsNpgsql.Split('=')[1].Split(';')[0]; }
  50. public static readonly string MenusPath = ConfigurationManager.AppSettings["MenusPath"];
  51. public static readonly string WorkspaceName = ConfigurationManager.AppSettings["WorkspaceName"];
  52. public static readonly int WorkspaceMapIndex = StringToInt(ConfigurationManager.AppSettings["WorkspaceMapIndex"]);
  53. public static readonly double MapCenterX = StringToDouble(ConfigurationManager.AppSettings["MapCenterX"]);
  54. public static readonly double MapCenterY = StringToDouble(ConfigurationManager.AppSettings["MapCenterY"]);
  55. public static readonly double MapScale = StringToDouble(ConfigurationManager.AppSettings["MapScale"]);
  56. public static readonly int WorkspaceDatasourceIndex = StringToInt(ConfigurationManager.AppSettings["WorkspaceDatasourceIndex"]);
  57. public static readonly string bsURL = ConfigurationManager.AppSettings["bsURL"];
  58. public static readonly string webTool = ConfigurationManager.AppSettings["webTool"];
  59. public static readonly string GISversion = ConfigurationManager.AppSettings["GISversion"];
  60. #endregion
  61. #region 用户信息
  62. //public void SetUserID(int uid) { m_UserID = uid; }
  63. //private static int m_UserID;
  64. //public static int UserID { get => m_UserID; }
  65. //public void SetUserNick(string uNick) { m_UserNick = uNick; }
  66. //private static string m_UserNick;
  67. //public static string UserNick { get => m_UserNick; }
  68. public void SetLoginID(int uid) { m_LoginID = uid; }
  69. private static int m_LoginID;
  70. public static int LoginID { get => m_LoginID; }
  71. #endregion
  72. #region Workspace MapControl DatasetVector
  73. public static Datasource Datasource { get => m_Workspace.Datasources[WorkspaceDatasourceIndex]; }
  74. public static Datasource DatasourceMemory { get => m_MemoryDatasource; }
  75. public static Workspace Workspace { get => m_Workspace; }
  76. public static MapControl MapControl { get => m_MapControl; }
  77. public static DockPanel DockPanel { get => m_DockPanel; }
  78. public static DatasetVector dvConfig { get => Datasource.Datasets["wwconfig"] as DatasetVector; }
  79. public static DatasetVector gsGuanXian { get => Datasource.Datasets[dvGXDatasetName] as DatasetVector; }
  80. public static DatasetVector gsGuanDian { get => Datasource.Datasets["gsGD"] as DatasetVector; }
  81. /// <summary>
  82. /// B/S端用到的网络数据集名称
  83. /// </summary>
  84. public static readonly string NetworkDatasetName = "DaAnPostgrsSQL_Network";
  85. /// <summary>
  86. /// 供水管线的数据集 Name=gsGX
  87. /// </summary>
  88. public static readonly string dvGXDatasetName = "gsGX";
  89. /// <summary>
  90. /// 供水管线的图层名称 Caption=供水管线
  91. /// </summary>
  92. public static readonly string dvGXCaption = "供水管线";
  93. #region 软件打开时 动态加载图层 这种情况需要确定工作空间内只有管线和其他图层,不能包含管点图层
  94. public static List<LayerEx> layerExList
  95. {
  96. get
  97. {
  98. //备注:1、节点图层的DatasetName必须带有dv,系统中会通过该字母判断是否选择的是节点图层
  99. List<LayerEx> list = new List<LayerEx>();
  100. list.Add(new LayerEx { Index = 0, Caption = "供水节点", Dataset = "dvJD", MarkerSymbolID = 14, MarkerSize = 2 });
  101. list.Add(new LayerEx { Index = 0, Caption = "供水阀门", Dataset = "dvFM", MarkerSymbolID = 13, MarkerSize = 3 });
  102. list.Add(new LayerEx { Index = 0, Caption = "消防栓", Dataset = "dvXFS", MarkerSymbolID = 19, MarkerSize = 3 });
  103. list.Add(new LayerEx { Index = 0, Caption = "压力监测点", Dataset = "dvYL", MarkerSymbolID = 20, MarkerSize = 3 });
  104. list.Add(new LayerEx { Index = 0, Caption = "流量监测点", Dataset = "dvLL", MarkerSymbolID = 15, MarkerSize = 3 });
  105. list.Add(new LayerEx { Index = 0, Caption = "水质监测点", Dataset = "dvSZ", MarkerSymbolID = 18, MarkerSize = 3 });
  106. list.Add(new LayerEx { Index = 0, Caption = "水表", Dataset = "dvSB", MarkerSymbolID = 17, MarkerSize = 3 });
  107. list.Add(new LayerEx { Index = 0, Caption = "供水水厂", Dataset = "dvSC", MarkerSymbolID = 21, MarkerSize = 3 });
  108. list.Add(new LayerEx { Index = 0, Caption = "排气阀", Dataset = "dvPQF", MarkerSymbolID = 16, MarkerSize = 3 });
  109. list.Add(new LayerEx { Index = 0, Caption = "调压站", Dataset = "dvJY", MarkerSymbolID = 20, MarkerSize = 3 });
  110. return list;
  111. }
  112. }
  113. public static void SetDatasetVectorAddLayer()
  114. {
  115. DatasetVector dv = null;
  116. LayerSettingVector layerSettingVector;
  117. string[] strField = GetFieldInfos(gsGuanDian);
  118. foreach (LayerEx lyrEx in layerExList.ToArray())
  119. {
  120. if (!Datasource.Datasets.Contains(lyrEx.Dataset))
  121. {
  122. dv = Datasource.Datasets.Create(new DatasetVectorInfo() { Name = lyrEx.Dataset, Type = DatasetType.Point });
  123. bool result = dv.AppendFields(gsGuanDian, "smid", "smuserid", strField);
  124. }
  125. else
  126. {
  127. dv = Datasource.Datasets[lyrEx.Dataset] as DatasetVector;
  128. dv.Truncate();
  129. }
  130. dv.Append(gsGuanDian.Query("FLDM='" + lyrEx.Caption + "'", CursorType.Static));
  131. LayerGroup lg = m_MapControl.Map.Layers.FindLayer("LayerGroup") as LayerGroup;
  132. if (lg == null) continue;
  133. layerSettingVector = new LayerSettingVector();
  134. //默认GeoStyle
  135. //{ FillBackColor=Color [A=255, R=255, G=255, B=255],FillForeColor=Color [A=255, R=189, G=235, B=255],
  136. // FillGradientAngle=0,FillGradientMode=None,FillGradientOffsetRatioX=0,FillGradientOffsetRatioY=0,
  137. // FillOpaqueRate=100,FillSymbolID=0,LineColor=Color [A=255, R=0, G=0, B=0],LineSymbolID=0,LineWidth=1,
  138. // MarkerAngle=0,MarkerSize={Width=2,Height=-0.1},MarkerSymbolID=0}
  139. GeoStyle geoStyle = new GeoStyle();
  140. geoStyle.MarkerSize = new Size2D(lyrEx.MarkerSize, lyrEx.MarkerSize);
  141. geoStyle.LineColor = lyrEx.LineColor;
  142. geoStyle.MarkerSymbolID = lyrEx.MarkerSymbolID;
  143. layerSettingVector.Style = geoStyle;
  144. Layer layer = Layer.CreateLayer(dv, layerSettingVector);
  145. layer.Caption = lyrEx.Caption;
  146. layer.Selection.IsDefaultStyleEnabled = false;
  147. layer.Selection.Style = geoStyle_Selection;
  148. layer.Selection.SetStyleOptions(StyleOptions.MarkerSymbolID, true);
  149. layer.Selection.SetStyleOptions(StyleOptions.LineColor, true);
  150. layer.Selection.SetStyleOptions(StyleOptions.MarkerSize, true);
  151. lg.Insert(0, layer);
  152. }
  153. }
  154. public static bool SetDatasetVector()
  155. {
  156. try
  157. {
  158. DatasetVector dv = null;
  159. string[] strField = GetFieldInfos(gsGuanDian);
  160. foreach (LayerEx lyrEx in layerExList.ToArray())
  161. {
  162. if (!Datasource.Datasets.Contains(lyrEx.Dataset))
  163. {
  164. dv = Datasource.Datasets.Create(new DatasetVectorInfo() { Name = lyrEx.Dataset, Type = DatasetType.Point });
  165. bool result = dv.AppendFields(gsGuanDian, "smid", "smuserid", strField);
  166. }
  167. else
  168. {
  169. dv = Datasource.Datasets[lyrEx.Dataset] as DatasetVector;
  170. dv.Truncate();
  171. }
  172. dv.Append(gsGuanDian.Query("FLDM='" + lyrEx.Caption + "'", CursorType.Static));
  173. }
  174. return true;
  175. }
  176. catch (Exception ex) { LogHelper.Fatal(ex); return false; }
  177. }
  178. public static GeoStyle geoStyle_Selection = new GeoStyle { MarkerSymbolID = 0, LineColor = Color.Red, MarkerSize = new Size2D(4, 4) };
  179. #endregion
  180. public static Layer LayerGuanXian
  181. {
  182. get
  183. {
  184. LayerGroup lg = m_MapControl.Map.Layers.FindLayer("LayerGroup") as LayerGroup;
  185. if (lg.Count == 0) return null;
  186. Layer lyr = null;
  187. foreach (Layer lyrr in lg)
  188. {
  189. if (lyrr.Dataset == gsGuanXian) { lyr = lyrr; break; }
  190. }
  191. return lyr;
  192. }
  193. }
  194. //public static Layers MapLayers { get => m_MapControl.Map.Layers; }
  195. /// <summary>
  196. /// 管点管线图层
  197. /// </summary>
  198. public static List<Layer> MapLayers
  199. {
  200. get
  201. {
  202. List<Layer> layerList = new List<Layer>();
  203. LayerGroup lg = m_MapControl.Map.Layers.FindLayer("LayerGroup") as LayerGroup;
  204. if (lg.Count == 0) return null;
  205. foreach (Layer lyrr in lg)
  206. {
  207. if (lyrr.Dataset == null || lyrr.Dataset.Datasource.Alias != Datasource.Alias) continue;
  208. layerList.Add(lyrr);
  209. }
  210. return layerList;
  211. }
  212. }
  213. /// <summary>
  214. /// 管点管线图层 + 用水单位图层
  215. /// </summary>
  216. public static List<Layer> MapLayersUsed
  217. {
  218. get
  219. {
  220. List<Layer> layerList = MapLayers;
  221. LayerGroup lg = m_MapControl.Map.Layers.FindLayer("LayerGroup#1") as LayerGroup;
  222. if (lg.Count == 0) return layerList;
  223. foreach (Layer lyrr in lg)
  224. {
  225. if (lyrr.Dataset == null || lyrr.Dataset.Datasource.Alias != Datasource.Alias) continue;
  226. if (!",pyunit,".ToLower().Contains(lyrr.Dataset.Name.ToLower())) continue;
  227. layerList.Add(lyrr);
  228. }
  229. return layerList;
  230. }
  231. }
  232. /// <summary>
  233. /// 当前数据集的所有图层
  234. /// </summary>
  235. public static List<Layer> MapLayersAll
  236. {
  237. get
  238. {
  239. List<Layer> layerList = new List<Layer>();
  240. foreach (Layer lyr in m_MapControl.Map.Layers)
  241. {
  242. if (lyr.Name.ToLower().Contains("layergroup"))
  243. {
  244. LayerGroup lyrG = lyr as LayerGroup;
  245. foreach (Layer lyrr in lyrG.Layers)
  246. {
  247. if (lyrr.Dataset.Datasource.Alias == Datasource.Alias)
  248. layerList.Add(lyrr);
  249. }
  250. }
  251. else if (lyr.Dataset.Datasource.Alias == Datasource.Alias)
  252. {
  253. layerList.Add(lyr);
  254. }
  255. }
  256. return layerList;
  257. }
  258. }
  259. public static void SetLayersIsSelectableFalse(string layerName, bool isSelect)
  260. {
  261. foreach (Layer r in MapLayers)
  262. {
  263. if (r.Name == layerName || r.Caption == layerName || r.Dataset.Name == layerName)
  264. r.IsSelectable = isSelect;
  265. else
  266. r.IsSelectable = !isSelect;
  267. }
  268. }
  269. public static void SetLayersIsVisibleFalse(string layerName, bool isSelect)
  270. {
  271. foreach (Layer r in MapLayers)
  272. {
  273. if (r.Name == layerName || r.Caption == layerName || r.Dataset.Name == layerName)
  274. r.IsVisible = isSelect;
  275. else
  276. r.IsVisible = !isSelect;
  277. }
  278. }
  279. /// <summary>
  280. /// 依据TrackingLayer的Name清空
  281. /// </summary>
  282. /// <param name="tag"></param>
  283. public static void TrackingLayerRemove(string tag)
  284. {
  285. int index = MapControl.Map.TrackingLayer.IndexOf(tag);
  286. while (index != -1)
  287. {
  288. MapControl.Map.TrackingLayer.Remove(index);
  289. index = MapControl.Map.TrackingLayer.IndexOf(tag);
  290. }
  291. }
  292. public static readonly string ControlToolsTrackingName = "ControlToolAddGeoRegion";
  293. public static void MapControl_Tracked_TrackingName(object sender, SuperMap.UI.TrackedEventArgs e)
  294. {
  295. m_MapControl.Tracked -= MapControl_Tracked_TrackingName;
  296. m_MapControl.Action = SuperMap.UI.Action.Select;
  297. m_MapControl.Action = SuperMap.UI.Action.Pan;
  298. if (e.Geometry is null) { Sunny.UI.UIMessageTip.ShowError("区域绘制失败"); return; }
  299. GeoRegion m_geo = e.Geometry.Clone() as GeoRegion;
  300. if (m_geo is null) { Sunny.UI.UIMessageTip.ShowError("区域绘制失败"); return; }
  301. m_geo.Style = ComsStatic.geoStyle_Red_1mm_OpaqueRate;
  302. m_MapControl.Map.TrackingLayer.Clear();
  303. m_MapControl.Map.TrackingLayer.Add(m_geo, ComsStatic.ControlToolsTrackingName);
  304. m_MapControl.Map.RefreshTrackingLayer();
  305. }
  306. /// <summary>
  307. /// 关闭当前主程序中除了Tag=MainControls的其他所有窗体
  308. /// <para>默认4个主要窗体: 主窗体 工具栏 鹰眼 图层</para>
  309. /// </summary>
  310. public static void closeFormTagMainControls()
  311. {
  312. try
  313. {
  314. foreach (Form form in Application.OpenForms)
  315. {
  316. if (form.Tag?.ToString() != "MainControls" && form.Text?.ToString() != "工具栏")
  317. {
  318. form.Close(); break;
  319. }
  320. }
  321. if (Application.OpenForms.Count > 6)
  322. {
  323. closeFormTagMainControls();
  324. }
  325. }
  326. catch (Exception ex)
  327. {
  328. ComsStatic.ShowErrorLog(ex);
  329. }
  330. }
  331. #endregion
  332. #region SuperMap.Data相关操作
  333. public static readonly string[] resultFieldsGX = new string[] { "fldm", "cz", "gj", "cd", "yl", "msfs", "dzms", "qsdw", "tcdw" };
  334. public static readonly string[] resultFieldsGD = new string[] { "fldm", "fsw", "xh", "gg", "cz", "kj", "gj", "yl", "dmgc", "ms", "msfs", "dzms", "qsdw", "tcdw" };
  335. public static Recordset QueryRecordset(DatasetVector dv, string sqlWhere, string[] resultFields = null, string[] groupBy = null, string[] orderBy = null)
  336. {
  337. QueryParameter para = new QueryParameter();
  338. if (sqlWhere != null) para.AttributeFilter = sqlWhere;
  339. if (resultFields != null) para.ResultFields = Commons.StringEx.setToLower(resultFields);
  340. if (groupBy != null) para.GroupBy = Commons.StringEx.setToLower(groupBy);
  341. if (orderBy != null) para.OrderBy = Commons.StringEx.setToLower(orderBy);
  342. para.CursorType = CursorType.Static;
  343. return dv.Query(para);
  344. }
  345. public static Recordset QueryRecordsetDynamic(DatasetVector dv, string sqlWhere, string[] resultFields = null, string[] groupBy = null, string[] orderBy = null)
  346. {
  347. QueryParameter para = new QueryParameter();
  348. if (sqlWhere != null) para.AttributeFilter = sqlWhere;
  349. if (resultFields != null) para.ResultFields = Commons.StringEx.setToLower(resultFields);
  350. if (groupBy != null) para.GroupBy = Commons.StringEx.setToLower(groupBy);
  351. if (orderBy != null) para.OrderBy = Commons.StringEx.setToLower(orderBy);
  352. para.CursorType = CursorType.Dynamic;
  353. return dv.Query(para);
  354. }
  355. public static DataTable QueryDataTable(DatasetVector dv, string sqlWhere, string[] resultFields = null, string[] groupBy = null, string[] orderBy = null)
  356. {
  357. QueryParameter para = new QueryParameter();
  358. if (sqlWhere != null) para.AttributeFilter = sqlWhere;
  359. if (resultFields != null) para.ResultFields = Commons.StringEx.setToLower(resultFields);
  360. if (groupBy != null) para.GroupBy = Commons.StringEx.setToLower(groupBy);
  361. if (orderBy != null) para.OrderBy = Commons.StringEx.setToLower(orderBy);
  362. para.CursorType = CursorType.Static;
  363. return RecordsetToDataTable(dv.Query(para), true, dv.Name);
  364. }
  365. public static List<object> QueryFieldsValueList(DatasetVector dv, string sqlWhere, string resultFields, string[] groupBy = null, string[] orderBy = null)
  366. {
  367. Recordset rd = QueryRecordset(dv, sqlWhere, new string[] { resultFields }, groupBy, orderBy);
  368. List<object> result = new List<object>();
  369. rd.MoveFirst();
  370. if (!rd.IsEOF)
  371. {
  372. result.Add(rd.GetFieldValue(resultFields));
  373. rd.MoveNext();
  374. }
  375. return result;
  376. }
  377. public static DataTable RecordsetToDataTable(Recordset recordset, bool isDispose = true, string tableName = null)
  378. {
  379. if (string.IsNullOrEmpty(tableName)) tableName = recordset.Dataset.Name;
  380. DataTable dt = new DataTable { TableName = tableName };
  381. foreach (FieldInfo info in recordset.GetFieldInfos())
  382. {
  383. dt.Columns.Add(new DataColumn { ColumnName = info.Name, Caption = info.Caption });
  384. }
  385. DataRow dr;
  386. recordset.MoveFirst();
  387. while (!recordset.IsEOF)
  388. {
  389. dr = dt.NewRow();
  390. foreach (DataColumn dc in dt.Columns)
  391. {
  392. dr[dc] = recordset.GetFieldValue(dc.ColumnName)?.ToString();
  393. }
  394. dt.Rows.Add(dr);
  395. recordset.MoveNext();
  396. }
  397. if (isDispose) RecordsetDispose(recordset);
  398. return dt;
  399. }
  400. //public static DataTable RecordsetToDataTable(Recordset recordset, bool isDispose = true, string tableName = null)
  401. //{
  402. // if (string.IsNullOrEmpty(tableName)) tableName = recordset.Dataset.Name;
  403. // DataTable dt = new DataTable { TableName = tableName };
  404. // FieldInfos fieldInfos = recordset.GetFieldInfos();
  405. // Int32 count = fieldInfos.Count;
  406. // DataColumn dataColumn;
  407. // for (Int32 i = 0; i < count; i++)
  408. // {
  409. // dataColumn = new DataColumn { ColumnName = fieldInfos[i].Name, Caption = fieldInfos[i].Caption };
  410. // dt.Columns.Add(dataColumn);
  411. // }
  412. // recordset.MoveFirst();
  413. // Int32 length = recordset.RecordCount;
  414. // DataRow dr;
  415. // for (int i = 0; i < length; i++)
  416. // {
  417. // dr = dt.NewRow();
  418. // var actIndex = 0;
  419. // for (Int32 j = 0; j < count; j++)
  420. // {
  421. // var objValue = recordset.GetFieldValue(j);
  422. // string value = objValue?.ToString();
  423. // dr[actIndex++] = value;
  424. // }
  425. // dt.Rows.Add(dr);
  426. // recordset.MoveNext();
  427. // }
  428. // if (isDispose) RecordsetDispose(recordset);
  429. // return dt;
  430. //}
  431. public static List<DataTable> TongJiFieldGroupCount(DatasetVector dv, string[] strField)
  432. {
  433. Recordset rd = null;
  434. List<DataTable> dts = new List<DataTable>();
  435. DataTable dt;
  436. DataRow dr;
  437. string fieldValue = string.Empty;
  438. foreach (string field in strField)
  439. {
  440. string[] ck = new string[] { field };
  441. rd = ComsStatic.QueryRecordset(dv, null, ck, ck, ck);
  442. dt = new DataTable(); dt.Columns.Add("类别"); dt.Columns.Add("数量");
  443. if (!HasField(dv, field)) continue;
  444. dt.TableName = rd.GetFieldInfos()[field].Caption;
  445. if (rd.RecordCount == 0)//该字段所有值均为null 不能GroupBy
  446. {
  447. dr = dt.NewRow();
  448. dr["类别"] = "未知"; dr["数量"] = dv.RecordCount;
  449. dt.Rows.Add(dr);
  450. }
  451. else
  452. {
  453. rd.MoveFirst();
  454. while (!rd.IsEOF)
  455. {
  456. dr = dt.NewRow();
  457. fieldValue = rd.GetFieldValue(field)?.ToString();
  458. if (string.IsNullOrEmpty(fieldValue))
  459. {
  460. dr["类别"] = "未知";
  461. dr["数量"] = dv.Query(string.Format("{0} is null", field), CursorType.Static).RecordCount;
  462. }
  463. else
  464. {
  465. dr["类别"] = fieldValue;
  466. dr["数量"] = dv.Query(string.Format("{0}='{1}'", field, fieldValue), CursorType.Static).RecordCount;
  467. }
  468. dt.Rows.Add(dr);
  469. rd.MoveNext();
  470. }
  471. }
  472. dr = dt.NewRow();
  473. dr["类别"] = dt.TableName + "总量"; dr["数量"] = dv.RecordCount;
  474. dt.Rows.Add(dr);
  475. dts.Add(dt);
  476. }
  477. ComsStatic.RecordsetDispose(rd);
  478. return dts;
  479. }
  480. public static string getSqlCheckListBox(Dictionary<string, CheckedListBox> dic, string otherWhere = null)
  481. {
  482. if (string.IsNullOrEmpty(otherWhere))
  483. otherWhere = " 1=1 ";
  484. StringBuilder sb = new StringBuilder(otherWhere);
  485. foreach (string key in dic.Keys)
  486. {
  487. if (dic[key].CheckedItems.Count > 0)
  488. {
  489. sb.Append(" AND (1=2 ");
  490. foreach (string clbItem in dic[key].CheckedItems)
  491. {
  492. if (clbItem == "未知")
  493. sb.AppendFormat(" OR {0} is null ", key);
  494. else
  495. sb.AppendFormat(" OR {0}='{1}' ", key, clbItem);
  496. }
  497. sb.Append(" ) ");
  498. }
  499. }
  500. return sb.ToString();
  501. }
  502. /// <summary>
  503. /// 获取DatasetVector的FieldInfos数组 不包含系统字段
  504. /// </summary>
  505. /// <param name="dv"></param>
  506. /// <returns></returns>
  507. public static string[] GetFieldInfos(DatasetVector dv)
  508. {
  509. List<string> listStr = new List<string>();
  510. foreach (FieldInfo f in dv.FieldInfos)
  511. {
  512. if (f.IsSystemField || f.Name.ToLower() == "smuserid") continue;
  513. listStr.Add(f.Name);
  514. }
  515. return listStr.ToArray();
  516. }
  517. public static bool HasField(DatasetVector m_DatasetVector, string _field)
  518. {
  519. bool hasField = false;
  520. FieldInfos fieldInfos = m_DatasetVector.FieldInfos;
  521. for (int i = 0; i < fieldInfos.Count; i++)
  522. {
  523. if (fieldInfos[i].Name.ToLower() == _field.ToLower())
  524. {
  525. hasField = true; break;
  526. }
  527. }
  528. return hasField;
  529. }
  530. public static bool HasField(Recordset m_Recordset, string _field)
  531. {
  532. bool hasField = false;
  533. FieldInfos fieldInfos = m_Recordset.GetFieldInfos();
  534. for (int i = 0; i < fieldInfos.Count; i++)
  535. {
  536. if (fieldInfos[i].Name.ToLower() == _field.ToLower())
  537. {
  538. hasField = true; break;
  539. }
  540. }
  541. return hasField;
  542. }
  543. public static void RecordsetDispose(Recordset rd)
  544. {
  545. if (rd != null) { rd.Close(); rd.Dispose(); }
  546. }
  547. public static void EditHistoryUndo(EditHistory eh)
  548. {
  549. while (eh.CanUndo)
  550. {
  551. bool isSuccess = eh.Undo();
  552. }
  553. eh.Clear(); eh.Dispose();
  554. }
  555. public static DataTable GetJSLKbyJSJDPT(DataTable dt)
  556. {
  557. #region 构造 管线的起始管点和终点管点 信息
  558. dt.Columns.Add(new DataColumn { ColumnName = "qdsmid", Caption = "起点SmID" });
  559. dt.Columns.Add(new DataColumn { ColumnName = "qdsmx", Caption = "起点X坐标" });
  560. dt.Columns.Add(new DataColumn { ColumnName = "qdsmy", Caption = "起点Y坐标" });
  561. dt.Columns.Add(new DataColumn { ColumnName = "qddmgc", Caption = "起点地面高程" });
  562. dt.Columns.Add(new DataColumn { ColumnName = "qdgdms", Caption = "起点埋深" });
  563. dt.Columns.Add(new DataColumn { ColumnName = "qdgc", Caption = "起点高程" });
  564. dt.Columns.Add(new DataColumn { ColumnName = "zdsmid", Caption = "终点SmID" });
  565. dt.Columns.Add(new DataColumn { ColumnName = "zdsmx", Caption = "终点X坐标" });
  566. dt.Columns.Add(new DataColumn { ColumnName = "zdsmy", Caption = "终点Y坐标" });
  567. dt.Columns.Add(new DataColumn { ColumnName = "zddmgc", Caption = "终点地面高程" });
  568. dt.Columns.Add(new DataColumn { ColumnName = "zdgdms", Caption = "终点埋深" });
  569. dt.Columns.Add(new DataColumn { ColumnName = "zdgc", Caption = "终点高程" });
  570. #endregion
  571. DataTable dtJSJDPT;
  572. foreach (DataRow dr in dt.Rows)
  573. {
  574. dtJSJDPT = QueryDataTable(gsGuanDian, string.Format(" bsm='{0}' ", dr["qsdh"]));
  575. if (dtJSJDPT.Rows.Count == 1)
  576. {
  577. dr["qdsmid"] = dtJSJDPT.Rows[0]["smid"]; dr["qdsmx"] = dtJSJDPT.Rows[0]["x"]; dr["qdsmy"] = dtJSJDPT.Rows[0]["y"];
  578. dr["qddmgc"] = dtJSJDPT.Rows[0]["dmgc"]; dr["qdgdms"] = dtJSJDPT.Rows[0]["ms"];
  579. dr["qdgc"] = StringToDouble(dtJSJDPT.Rows[0]["dmgc"], 2) - StringToDouble(dtJSJDPT.Rows[0]["ms"], 2);
  580. }
  581. dtJSJDPT = QueryDataTable(gsGuanDian, string.Format(" bsm='{0}' ", dr["zddh"]));
  582. if (dtJSJDPT.Rows.Count == 1)
  583. {
  584. dr["zdsmid"] = dtJSJDPT.Rows[0]["smid"]; dr["zdsmx"] = dtJSJDPT.Rows[0]["x"]; dr["zdsmy"] = dtJSJDPT.Rows[0]["y"];
  585. dr["zddmgc"] = dtJSJDPT.Rows[0]["dmgc"]; dr["zdgdms"] = dtJSJDPT.Rows[0]["ms"];
  586. dr["zdgc"] = StringToDouble(dtJSJDPT.Rows[0]["dmgc"], 2) - StringToDouble(dtJSJDPT.Rows[0]["ms"], 2);
  587. }
  588. }
  589. return dt;
  590. }
  591. public static Dictionary<string, object> getGuanXianPeiZhi(string pzlx)
  592. {
  593. Dictionary<string, object> dic = new Dictionary<string, object>();
  594. Recordset _rd = dvConfig.Query(string.Format(" pzlx='{0}' ", pzlx), CursorType.Static);
  595. if (_rd.RecordCount == 0) return dic;
  596. _rd.MoveFirst();
  597. while (!_rd.IsEOF)
  598. {
  599. string gxcz = _rd.GetString("gxcz");
  600. dic.Add(gxcz + "_gxyjnx", _rd.GetFieldValue("gxyjnx"));
  601. dic.Add(gxcz + "_gxbznx", _rd.GetFieldValue("gxbznx"));
  602. dic.Add(gxcz + "_gxms", _rd.GetFieldValue("gxms"));
  603. _rd.MoveNext();
  604. }
  605. ComsStatic.RecordsetDispose(_rd);
  606. return dic;
  607. }
  608. public static double GetMaxValue(DatasetVector dv, string fieldName)
  609. {
  610. return dv.Statistic(fieldName, StatisticMode.Max);
  611. }
  612. public static int GetMaxValueInt(DatasetVector dv, string fieldName)
  613. {
  614. return StringToInt(dv.Statistic(fieldName, StatisticMode.Max));
  615. }
  616. public static object GetOnlyValueByField(DatasetVector dv, string sqlWhere, string field)
  617. {
  618. Recordset rd = dv.Query(sqlWhere, CursorType.Static);
  619. if (rd is null || rd.RecordCount != 1) return null;
  620. return rd.GetFieldValue(field);
  621. }
  622. /// <summary>
  623. /// 在当前的DatasetVector中,获取指定列名的最小值
  624. /// </summary>
  625. /// <param name="fieldName"></param>
  626. /// <returns></returns>
  627. public static double GetMinValue(DatasetVector dv, string fieldName)
  628. {
  629. return dv.Statistic(fieldName, StatisticMode.Min);
  630. }
  631. #endregion
  632. #region ShowUIMessageTip界面提示信息
  633. public static void ShowUIMessageTipOKorError(bool _result, string msg, string logMsg = "")
  634. {
  635. if (_result)
  636. {
  637. ShowOKLog(msg + "操作成功", logMsg);
  638. }
  639. else
  640. {
  641. ShowErrorLog(msg + "操作失败", logMsg);
  642. }
  643. }
  644. public static void ShowErrorLog(object msg, string logMsg = "")
  645. {
  646. LogHelper.Error(string.Format("{0} {1}", msg, logMsg));
  647. UIMessageTip.ShowError(msg.ToString(), 2000, false);
  648. //UIMessageTip.ShowError(msg.ToString(), 2000, false, new Point(800, 400), true);
  649. }
  650. public static void ShowOK(string msg)
  651. {
  652. UIMessageTip.ShowOk(msg.ToString(), 2000, false);
  653. //UIMessageTip.ShowOk(msg, 2000, false, new Point(800, 400), true);
  654. }
  655. public static void ShowOKLog(object msg, string logMsg = "")
  656. {
  657. //pgAddLoginm(string.Format("{0} {1}", msg, logMsg));
  658. LogHelper.Info(string.Format("{0} {1}", msg, logMsg));
  659. UIMessageTip.ShowOk(msg.ToString(), 2000, false);
  660. //UIMessageTip.ShowOk(msg.ToString(), 2000, false, new Point(800, 400), true);
  661. }
  662. #endregion
  663. #region String操作
  664. public static double StringToDouble(object str, int dleng = -1)
  665. {
  666. if (str is null) return 0;
  667. double result = 0.0D;
  668. double.TryParse(str.ToString(), out result);
  669. if (dleng != -1)
  670. {
  671. result = Math.Round(result, dleng);
  672. }
  673. return result;
  674. }
  675. /// <summary>
  676. /// Object转Int Ojbect=null或者转换失败时返回0;
  677. /// </summary>
  678. /// <param name="str"></param>
  679. /// <returns></returns>
  680. public static int StringToInt(object str)
  681. {
  682. if (str is null) return 0;
  683. Int32 result = 0;
  684. Int32.TryParse(str.ToString(), out result);
  685. return result;
  686. }
  687. public static Int16 StringToInt16(object str)
  688. {
  689. if (str is null) return 0;
  690. Int16 result = 0;
  691. Int16.TryParse(str.ToString(), out result);
  692. return result;
  693. }
  694. public static float StringToFloat(object str)
  695. {
  696. if (str is null) return 0.0F;
  697. float result = 0.0F;
  698. float.TryParse(str.ToString(), out result);
  699. return result;
  700. }
  701. public static string getMd5Hash(string input, string key)
  702. {
  703. MD5 md5Hasher = MD5.Create();
  704. string str = input + key;
  705. byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(str));
  706. StringBuilder sBuilder = new StringBuilder();
  707. for (int i = 0; i < data.Length; i++)
  708. {
  709. sBuilder.Append(data[i].ToString("x2"));
  710. }
  711. return sBuilder.ToString();
  712. }
  713. /// <summary>
  714. /// DES加密
  715. /// </summary>
  716. /// <param name="encryptString"></param>
  717. /// <returns></returns>
  718. public static string DesEncrypt(string encryptString, string key)
  719. {
  720. byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
  721. byte[] keyIV = keyBytes;
  722. byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
  723. DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
  724. MemoryStream mStream = new MemoryStream();
  725. CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
  726. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  727. cStream.FlushFinalBlock();
  728. return Convert.ToBase64String(mStream.ToArray());
  729. }
  730. /// <summary>
  731. /// DES解密
  732. /// </summary>
  733. /// <param name="decryptString"></param>
  734. /// <returns></returns>
  735. public static string DesDecrypt(string decryptString, string key)
  736. {
  737. byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
  738. byte[] keyIV = keyBytes;
  739. byte[] inputByteArray = Convert.FromBase64String(decryptString);
  740. DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
  741. MemoryStream mStream = new MemoryStream();
  742. CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
  743. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  744. cStream.FlushFinalBlock();
  745. return Encoding.UTF8.GetString(mStream.ToArray());
  746. }
  747. #endregion
  748. #region SummyUI的控件设置和数据绑定
  749. public static readonly UIStyle uiStyleCom = UIStyle.Blue; //R 80 G 160 B 255
  750. /// <summary>
  751. /// HideEnableTag ,smid
  752. /// </summary>
  753. public static readonly string HideEnableTag = ",smx,smy,smkey,smsdriw,smsdrin,smsdrie,smsdris,smgranule,SmGeometry,smlength,smtopoerror,smlibtileid,smperimeter,smarea,smnodeid,smuserid,smgeometrysize,smgeoposition,objectid,bsm,wth,tfh,dmt,x,y,dinggc,digc,cqbh,tsdh,ssbh,ROTATEANGLE,lrrq,enabled,zcbh,qdms,zdms,shape_length,shape_area,lx,qsdh,zddh,fmlx,sblx,sbsl,sbdz,qdsmid,qdsmx,qdsmy,zdsmid,zdsmx,zdsmy,".ToLower();
  754. public static void setUIDataGridView(UIDataGridView dgv, DataTable dt = null, string showTag = null, string hideTag = null)
  755. {
  756. dgv.Dock = DockStyle.Fill;
  757. dgv.ShowEditingIcon = false;
  758. dgv.ShowCellToolTips = false;
  759. dgv.AllowUserToAddRows = false;
  760. dgv.AllowUserToResizeRows = false;
  761. dgv.AllowUserToDeleteRows = false;
  762. dgv.AllowUserToOrderColumns = false;
  763. dgv.ReadOnly = true;
  764. dgv.MultiSelect = false;
  765. dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
  766. dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
  767. dgv.Style = UIStyle.Gray;// ComsStatic.uiStyleCom;
  768. dgv.RowPostPaint += Dgv_RowPostPaint;
  769. if (dt != null)
  770. {
  771. dgv.DataSource = dt;
  772. if (showTag != null)
  773. {
  774. string[] strShow = showTag.ToLower().Split(',');
  775. int indexStr = 0;
  776. for (int i = 0; i < dgv.Columns.Count; i++)
  777. {
  778. dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  779. dgv.Columns[i].HeaderText = dt.Columns[i].Caption;
  780. indexStr = strShow.ToList().IndexOf(dgv.Columns[i].Name.ToLower());
  781. if (indexStr > -1)
  782. dgv.Columns[i].DisplayIndex = indexStr;
  783. else
  784. dgv.Columns[i].Visible = false;
  785. }
  786. return;
  787. }
  788. if (string.IsNullOrEmpty(hideTag))
  789. {
  790. for (int i = 0; i < dgv.Columns.Count; i++)
  791. {
  792. dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  793. dgv.Columns[i].HeaderText = dt.Columns[i].Caption;
  794. if (HideEnableTag.Contains("," + dgv.Columns[i].Name.ToLower() + ","))
  795. {
  796. dgv.Columns[i].Visible = false;
  797. }
  798. }
  799. }
  800. else
  801. {
  802. for (int i = 0; i < dgv.Columns.Count; i++)
  803. {
  804. dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  805. dgv.Columns[i].HeaderText = dt.Columns[i].Caption;
  806. if (HideEnableTag.Contains("," + dgv.Columns[i].Name.ToLower() + ",") || hideTag.ToLower().Contains("," + dgv.Columns[i].Name.ToLower() + ","))
  807. {
  808. dgv.Columns[i].Visible = false;
  809. }
  810. }
  811. }
  812. }
  813. }
  814. private static void Dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
  815. {
  816. DataGridView dgv = sender as DataGridView;
  817. Rectangle rect = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
  818. TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rect, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
  819. }
  820. public static void BindUICombox(UIComboBox cbx, bool hasGX = true)
  821. {
  822. foreach (Layer lyr in ComsStatic.MapLayers)
  823. {
  824. if (!hasGX && lyr.Dataset.Name == ComsStatic.gsGuanXian.Name) continue;
  825. cbx.Items.Add(new DoListItem(lyr.Dataset.Name, lyr.Caption));
  826. }
  827. cbx.SelectedIndex = 0;
  828. }
  829. public static void BindDataTableOnCheckedListBox(DatasetVector _dv, CheckedListBox _cbg, string _ziduan)
  830. {
  831. Recordset rd = QueryRecordset(_dv, null, new string[] { _ziduan }, new string[] { _ziduan }, new string[] { _ziduan });
  832. rd.MoveFirst();
  833. string fieldValue = string.Empty;
  834. _cbg.Items.Clear();
  835. while (!rd.IsEOF)
  836. {
  837. fieldValue = rd.GetString(_ziduan);// rd.GetFieldValue(_ziduan)?.ToString();
  838. if (string.IsNullOrEmpty(fieldValue))
  839. _cbg.Items.Add("未知");
  840. else
  841. _cbg.Items.Add(fieldValue);
  842. rd.MoveNext();
  843. }
  844. ComsStatic.RecordsetDispose(rd);
  845. }
  846. public static void BindDataTableOnCheckedListBox(string gdFLDM, CheckedListBox _cbg, string _ziduan)
  847. {
  848. Recordset rd = QueryRecordset(ComsStatic.gsGuanDian, string.Format("FLDM='{0}'", gdFLDM), new string[] { _ziduan }, new string[] { _ziduan }, new string[] { _ziduan });
  849. rd.MoveFirst();
  850. string fieldValue = string.Empty;
  851. _cbg.Items.Clear();
  852. while (!rd.IsEOF)
  853. {
  854. fieldValue = rd.GetString(_ziduan);
  855. if (string.IsNullOrEmpty(fieldValue))
  856. _cbg.Items.Add("未知");
  857. else
  858. _cbg.Items.Add(fieldValue);
  859. rd.MoveNext();
  860. }
  861. ComsStatic.RecordsetDispose(rd);
  862. }
  863. public static void BindDataTableOnComboBox(DatasetVector _dv, UIComboBox _cbg, string _ziduan)
  864. {
  865. Recordset rd = QueryRecordset(_dv, null, new string[] { _ziduan }, new string[] { _ziduan }, new string[] { _ziduan });
  866. rd.MoveFirst();
  867. _cbg.Items.Clear();
  868. string fieldValue = string.Empty;
  869. while (!rd.IsEOF)
  870. {
  871. fieldValue = rd.GetString(_ziduan);
  872. if (string.IsNullOrEmpty(fieldValue))
  873. _cbg.Items.Add("未知");
  874. else
  875. _cbg.Items.Add(fieldValue);
  876. rd.MoveNext();
  877. }
  878. _cbg.SelectedIndex = 0;
  879. ComsStatic.RecordsetDispose(rd);
  880. }
  881. public static DataTable getPaperSize()
  882. {
  883. DataTable dt = new DataTable { TableName = "PaperSizeTable" };
  884. dt.Columns.Add("sizekey"); dt.Columns.Add("sizedesc");
  885. dt.Rows.Add("A4", "A4 210x297mm");
  886. dt.Rows.Add("A3", "A3 297x420mm");
  887. dt.Rows.Add("ISOA2", "标准纸面大小(A2)");
  888. dt.Rows.Add("ISOA1", "标准纸面大小(A1)");
  889. dt.Rows.Add("ISOA0", "标准纸面大小(A0)");
  890. return dt;
  891. }
  892. public static PaperSize getPaperSize(string size)
  893. {
  894. PaperSize ps = PaperSize.A4;
  895. switch (size)
  896. {
  897. case "A4": ps = PaperSize.A4; break;
  898. case "A3": ps = PaperSize.A3; break;
  899. case "ISOA2": ps = PaperSize.ISOA2; break;
  900. case "ISOA1": ps = PaperSize.ISOA1; break;
  901. case "ISOA0": ps = PaperSize.ISOA0; break;
  902. default: break;
  903. }
  904. return ps;
  905. }
  906. /// <summary>
  907. /// 设置CheckedListBox的选择状态 1全选 2反选 3全不选
  908. /// </summary>
  909. /// <param name="clb"></param>
  910. /// <param name="doState">1全选 2反选 3全不选</param>
  911. public static void CheckListBoxDo(CheckedListBox clb, int doState)
  912. {
  913. switch (doState)
  914. {
  915. case 1://全选
  916. for (int i = 0; i < clb.Items.Count; i++)
  917. {
  918. clb.SetItemChecked(i, true);
  919. }
  920. break;
  921. case 2://反选
  922. for (int i = 0; i < clb.Items.Count; i++)
  923. {
  924. bool ck = clb.GetItemChecked(i);
  925. clb.SetItemChecked(i, !ck);
  926. }
  927. break;
  928. case 3://全不选
  929. for (int i = 0; i < clb.Items.Count; i++)
  930. {
  931. clb.SetItemChecked(i, false);
  932. }
  933. break;
  934. default:
  935. break;
  936. }
  937. }
  938. private static ToolTip toolTips = new ToolTip();
  939. public static void CheckedListBox_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
  940. {
  941. CheckedListBox clb = sender as CheckedListBox;
  942. int index = clb.IndexFromPoint(e.Location);
  943. if (index != -1 && toolTips.GetToolTip(clb) != clb.Items[index].ToString())
  944. {
  945. toolTips.SetToolTip(clb, clb.Items[index].ToString());
  946. }
  947. }
  948. //2021年12月27日 15:22:36 18个引用
  949. public static void uiTextBox_num_KeyPress(object sender, KeyPressEventArgs e)
  950. {
  951. // 横向数字键的1-9 小键盘数字键的1-9 BackSpace 小键盘 . Del 字母按键 .>
  952. if ((e.KeyChar >= 48 || e.KeyChar <= 57) || (e.KeyChar >= 96 || e.KeyChar <= 105) || (e.KeyChar == 8) || (e.KeyChar == 110) || (e.KeyChar == 190))
  953. e.Handled = false;//可以输入
  954. else
  955. e.Handled = true;
  956. }
  957. public static void UIListBox_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
  958. {
  959. UIListBox clb = sender as UIListBox;
  960. int index = clb.IndexFromPoint(e.Location);
  961. if (index != -1 && toolTips.GetToolTip(clb) != clb.Items[index].ToString())
  962. {
  963. toolTips.SetToolTip(clb, clb.Items[index].ToString());
  964. }
  965. }
  966. #endregion
  967. #region 其他计算操作
  968. /// <summary>
  969. /// 通过起点的坐标和数值、终点的坐标和数值,计算线上交点的数值
  970. /// </summary>
  971. /// <param name="gx_start">起点坐标</param>
  972. /// <param name="gx_start_gc">起点数值</param>
  973. /// <param name="gx_end">终点坐标</param>
  974. /// <param name="gx_end_gc">终点数值</param>
  975. /// <param name="JiaoDian">线上的交点坐标</param>
  976. /// <returns>交点数值</returns>
  977. public static double getPointHeight(Point2D start, double startValue, Point2D end, double endValue, Point2D JiaoDian)
  978. {
  979. if (!Geometrist.IsPointOnLine(JiaoDian, start, end, false)) return 0.0;
  980. if (startValue == endValue) return Math.Round(startValue, 2);
  981. double JiaoDianValue = 0.0D;
  982. if (startValue < endValue)//确保起点数据 大于 终点数据
  983. {
  984. double temp = startValue;
  985. startValue = endValue;
  986. endValue = temp;
  987. Point2D temPoint = start;
  988. start = end;
  989. end = temPoint;
  990. }
  991. // 参考链接 https://zhuanlan.zhihu.com/p/43660758 下面的公式可以用,是正式的,这里备份一下
  992. //JiaoDian_gc = gx_end_gc + (gx_start_gc - gx_end_gc) * (Math.Sqrt(Math.Pow((JiaoDian.X - gx_end.X), 2.0) + Math.Pow((JiaoDian.Y - gx_end.Y), 2.0))) / (Math.Sqrt(Math.Pow((gx_start.X - gx_end.X), 2.0) + Math.Pow((gx_start.Y - gx_end.Y), 2.0)));
  993. JiaoDianValue = endValue + (startValue - endValue) * (Math.Sqrt(Math.Pow((JiaoDian.X - end.X), 2.0) + Math.Pow((JiaoDian.Y - end.Y), 2.0))) / (Math.Sqrt(Math.Pow((start.X - end.X), 2.0) + Math.Pow((start.Y - end.Y), 2.0)));
  994. if (JiaoDianValue == double.PositiveInfinity || JiaoDianValue == double.NegativeInfinity)
  995. {
  996. JiaoDianValue = endValue;
  997. }
  998. return Math.Round(JiaoDianValue, 2);
  999. }
  1000. /// <summary>
  1001. /// 返回Double数组的最大值或者最小值
  1002. /// </summary>
  1003. /// <param name="dblist"></param>
  1004. /// <param name="isMax">True表示最大值,false表示最小值</param>
  1005. /// <returns></returns>
  1006. public static double getMaxMin(double[] dblist, bool isMax)
  1007. {
  1008. double finalValue = dblist[0];
  1009. if (isMax)//最大值
  1010. {
  1011. for (int i = 0; i < dblist.Length; i++)
  1012. {
  1013. if (finalValue < dblist[i])
  1014. finalValue = dblist[i];
  1015. }
  1016. }
  1017. else
  1018. {
  1019. for (int i = 0; i < dblist.Length; i++)
  1020. {
  1021. if (finalValue > dblist[i])
  1022. finalValue = dblist[i];
  1023. }
  1024. }
  1025. return finalValue;
  1026. }
  1027. /// <summary>
  1028. /// 将逗号分隔的csv格式文件,转换为DataTable
  1029. /// </summary>
  1030. /// <param name="filePath">csv文件路径</param>
  1031. /// <param name="FirstField">首行是否是标题行</param>
  1032. /// <returns></returns>
  1033. public static DataTable CSVToDataTable(string filePath, bool FirstField)
  1034. {
  1035. DataTable table = new DataTable();
  1036. bool isField = true;
  1037. using (StreamReader reader = new StreamReader(filePath, Encoding.GetEncoding("gb2312"), false))
  1038. {
  1039. string line = string.Empty;
  1040. while (reader.Peek() > 0)
  1041. {
  1042. line = reader.ReadLine();
  1043. if (string.IsNullOrEmpty(line) || line.Split(',').Length == 0) continue;
  1044. string[] split = line.Split(',');
  1045. if (isField)
  1046. {
  1047. isField = false;
  1048. if (FirstField)//首行是标题
  1049. {
  1050. foreach (string str in split) table.Columns.Add(str);
  1051. continue;
  1052. }
  1053. else
  1054. {
  1055. for (int i = 0; i < split.Length; i++) table.Columns.Add("列" + i.ToString());
  1056. }
  1057. }
  1058. DataRow newRow = table.NewRow();
  1059. for (int j = 0; j < split.Length; j++)
  1060. {
  1061. newRow[j] = split[j].Trim('"');
  1062. }
  1063. table.Rows.Add(newRow);
  1064. }
  1065. return table;
  1066. }
  1067. }
  1068. #endregion
  1069. #region postgresSql
  1070. ///// <summary>
  1071. ///// 获取本机所有IPV4地址列表
  1072. ///// </summary>
  1073. ///// <returns>本机所有IPV4地址列表,以分号分隔</returns>
  1074. //public static string GetSelfIpv4List()
  1075. //{
  1076. // StringBuilder ips = new StringBuilder();
  1077. // try
  1078. // {
  1079. // IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  1080. // foreach (IPAddress ipa in IpEntry.AddressList)
  1081. // {
  1082. // if (ipa.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  1083. // { ips.AppendFormat("{0};", ipa.ToString()); break; }
  1084. // }
  1085. // }
  1086. // catch { }
  1087. // finally { ips.AppendFormat("未知"); }
  1088. // return ips.ToString();
  1089. //}
  1090. public static string AppConfigGetvalue(string strKey)
  1091. {
  1092. foreach (string key in ConfigurationManager.AppSettings)
  1093. {
  1094. if (key == strKey)
  1095. {
  1096. return ConfigurationManager.AppSettings[strKey];
  1097. }
  1098. }
  1099. return null;
  1100. }
  1101. public static void AppConfigUpdate(string newKey, string newValue)
  1102. {
  1103. bool isModified = false;
  1104. foreach (string key in ConfigurationManager.AppSettings)
  1105. {
  1106. if (key == newKey)
  1107. {
  1108. isModified = true;
  1109. }
  1110. }
  1111. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  1112. if (isModified)
  1113. {
  1114. config.AppSettings.Settings.Remove(newKey);
  1115. }
  1116. config.AppSettings.Settings.Add(newKey, newValue);
  1117. config.Save(ConfigurationSaveMode.Modified);
  1118. ConfigurationManager.RefreshSection("appSettings");
  1119. }
  1120. public static string GetInterNetworkIp { get; } = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString();
  1121. public static string GetSql(string select, List<string> wheres, string orderby = null, string groupby = null)
  1122. {
  1123. StringBuilder sb = new StringBuilder(select);
  1124. if (wheres.Count > 0)
  1125. {
  1126. sb.Append(" where " + string.Join(" and ", wheres.ToArray()));
  1127. }
  1128. if (!string.IsNullOrEmpty(orderby)) sb.Append(orderby);
  1129. if (!string.IsNullOrEmpty(groupby)) sb.Append(groupby);
  1130. return sb.ToString();
  1131. }
  1132. public static void pgAddLogin(string n, string p, string c)
  1133. {
  1134. string sql = string.Format(" INSERT INTO userlogin(lgName,lgtime,lgIP,lgCup)VALUES('{0}','{1}','{2}','{3}') returning id;", n, DateTime.Now.ToLocalTime(), p, c);
  1135. object obj = new NpgsqlHelper().ExecuteScalar(sql);
  1136. ComsStatic.Instance.SetLoginID(StringToInt(obj));
  1137. }
  1138. public static void pgAddLoginm(string n)
  1139. {
  1140. if (ComsStatic.LoginID == 0) return;
  1141. string sql = string.Format(" INSERT INTO userloginm(lgid,czms,cztime)VALUES('{0}','{1}','{2}') returning id;", ComsStatic.LoginID, n, DateTime.Now.ToLocalTime());
  1142. new NpgsqlHelper().ExecuteScalar(sql);
  1143. }
  1144. //public static bool pgDeleteGuanDian(string bsm)
  1145. //{
  1146. // string sql = string.Format(" DELETE FROM {0} WHERE bsm='{1}' RETURNING bsm ", gsGuanDian.TableName, bsm);
  1147. // object obj = new NpgsqlHelper().ExecuteScalar(sql);
  1148. // if (obj == null) return false;
  1149. // return true;
  1150. //}
  1151. //public static bool pgDeleteGuanDian(string dvTableName, string bsm)
  1152. //{
  1153. // string sql = string.Format(" DELETE FROM {0} WHERE bsm='{1}' RETURNING bsm ", dvTableName, bsm);
  1154. // object obj = new NpgsqlHelper().ExecuteScalar(sql);
  1155. // if (obj == null) return false;
  1156. // return true;
  1157. //}
  1158. #endregion
  1159. #region 管网标注的配置
  1160. /// <summary>
  1161. ///线样式 LineColor = Color.Brown, LineWidth = 0.5
  1162. /// </summary>
  1163. public static GeoStyle geoStyle_Brown_05mm = new GeoStyle() { LineColor = Color.Brown, LineWidth = 0.5 };
  1164. /// <summary>
  1165. ///点样式 LineColor = Color.Red, MarkerSize = new Size2D(5, 5)
  1166. /// </summary>
  1167. public static GeoStyle geoStyle_Red_Mark5mm = new GeoStyle { LineColor = Color.Red, MarkerSize = new Size2D(5, 5) };
  1168. /// <summary>
  1169. /// 标注样式 ForeColor = Color.Brown, IsSizeFixed = true, FontHeight = 6, Alignment = TextAlignment.BottomLeft
  1170. /// </summary>
  1171. public static TextStyle textStyle_Brown_6mm_BottomLeft = new TextStyle { ForeColor = Color.Brown, IsSizeFixed = true, FontHeight = 6, Alignment = TextAlignment.BottomLeft };
  1172. /// <summary>
  1173. ///边框线样式 LineColor = Color.Red, LineWidth = 1, FillOpaqueRate = 10
  1174. /// </summary>
  1175. public static GeoStyle geoStyle_Red_1mm_OpaqueRate = new GeoStyle { LineColor = Color.Red, LineWidth = 1, FillOpaqueRate = 10 };
  1176. public static Point2D GetPoint2D(object x, object y)
  1177. {
  1178. return new Point2D(StringToDouble(x), StringToDouble(y));
  1179. }
  1180. /// <summary>
  1181. /// 获取标注风格配置的TextStyle
  1182. /// </summary>
  1183. /// <returns></returns>
  1184. public static TextStyle BiaoZhuFengGe()
  1185. {
  1186. QueryParameter queryParameter = new QueryParameter
  1187. {
  1188. AttributeFilter = " pzlx='标注风格配置' and pzKey='TextStyleKey' ",
  1189. ResultFields = new string[] { "pzValue" },
  1190. CursorType = CursorType.Static
  1191. };
  1192. Recordset _rd = ComsStatic.dvConfig.Query(queryParameter);
  1193. if (_rd.RecordCount != 1) return textStyle_Brown_6mm_BottomLeft;
  1194. TextStyle ts = new TextStyle();
  1195. bool fromResult = ts.FromXML(_rd.GetFieldValue("pzValue").ToString());
  1196. ComsStatic.RecordsetDispose(_rd);
  1197. if (!fromResult) return textStyle_Brown_6mm_BottomLeft;
  1198. return ts;
  1199. }
  1200. #endregion
  1201. #region 与bs的相关操作
  1202. public static string webGISVersion { get; } = ComsStatic.GetUrlString(webTool + "Tools/PictureUpload.ashx?action=getGISversion");
  1203. public static string GetUrlString(string Url)
  1204. {
  1205. string retString = string.Empty;
  1206. try
  1207. {
  1208. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  1209. request.Proxy = null;
  1210. request.KeepAlive = false;
  1211. request.Method = "GET";
  1212. request.ContentType = "text/plain; charset=UTF-8";
  1213. request.AutomaticDecompression = DecompressionMethods.GZip;
  1214. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  1215. Stream myResponseStream = response.GetResponseStream();
  1216. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
  1217. retString = myStreamReader.ReadToEnd();
  1218. myStreamReader.Close();
  1219. myResponseStream.Close();
  1220. if (response != null) response.Close();
  1221. if (request != null) request.Abort();
  1222. }
  1223. catch { }
  1224. return retString;
  1225. }
  1226. #endregion
  1227. }
  1228. public class DoListItem
  1229. {
  1230. private string _key = string.Empty;
  1231. private string _value = string.Empty;
  1232. public DoListItem(string pKey, string pValue) { _key = pKey; _value = pValue; }
  1233. public override string ToString() { return _value; }
  1234. public string Key { get => _key; set => _key = value; }
  1235. public string Value { get => _value; set => _value = value; }
  1236. }
  1237. public class DoTrackingPoint
  1238. {
  1239. private Timer timer = new Timer() { Enabled = false, Interval = 300 };
  1240. private int Timertag = 1;
  1241. private GeoPoint markPoint = null;
  1242. public void Doing(double x, double y)
  1243. {
  1244. timer.Tick += Timer_Tick;
  1245. Point2D p2d = new Point2D(x, y);
  1246. ComsStatic.MapControl.Map.Center = p2d;
  1247. ComsStatic.MapControl.Map.Refresh();
  1248. markPoint = new GeoPoint(p2d);
  1249. markPoint.Style = new GeoStyle() { MarkerSize = new Size2D(5, 5), LineColor = Color.Red };
  1250. timer.Enabled = true; timer.Start();
  1251. }
  1252. private void Timer_Tick(object sender, EventArgs e)
  1253. {
  1254. if (Timertag == 6)
  1255. {
  1256. timer.Stop();
  1257. timer.Enabled = false;
  1258. Timertag = 1;
  1259. int index = ComsStatic.MapControl.Map.TrackingLayer.IndexOf("DoInterestPoint");
  1260. if (index > -1) ComsStatic.MapControl.Map.TrackingLayer.Remove(index);
  1261. ComsStatic.MapControl.Map.RefreshTrackingLayer();
  1262. return;
  1263. }
  1264. else if (Timertag % 2 == 1 && markPoint != null)
  1265. {
  1266. ComsStatic.MapControl.Map.TrackingLayer.Add(markPoint, "DoInterestPoint");
  1267. }
  1268. else //if (Timertag % 2 == 0)
  1269. {
  1270. int index = ComsStatic.MapControl.Map.TrackingLayer.IndexOf("DoInterestPoint");
  1271. if (index > -1) ComsStatic.MapControl.Map.TrackingLayer.Remove(index);
  1272. }
  1273. Timertag++;
  1274. ComsStatic.MapControl.Map.RefreshTrackingLayer();
  1275. }
  1276. }
  1277. public class LayerEx
  1278. {
  1279. //public LayerEx() { }
  1280. private string caption;
  1281. private string fldm;
  1282. private string dataset;
  1283. private DatasetVector datasetVector;
  1284. private int markerSymbolID = 0;
  1285. private double markerSize = 0;
  1286. private double maxVisibleScale = 0;
  1287. private double minVisibleScale = 0;
  1288. private bool isEditable = false;
  1289. private bool isVisible = true;
  1290. private int index;
  1291. private Color lineColor = Color.Blue;
  1292. private double lineWidth;
  1293. public string Caption { get => caption; set => caption = value; }
  1294. public string FLDM { get => fldm; set => fldm = value; }
  1295. public string Dataset { get => dataset; set => dataset = value; }
  1296. public DatasetVector DatasetVector { get => datasetVector; set => datasetVector = value; }
  1297. public int MarkerSymbolID { get => markerSymbolID; set => markerSymbolID = value; }
  1298. public double MarkerSize { get => markerSize; set => markerSize = value; }
  1299. public double MaxVisibleScale { get => maxVisibleScale; set => maxVisibleScale = value; }
  1300. public double MinVisibleScale { get => minVisibleScale; set => minVisibleScale = value; }
  1301. public bool IsEditable { get => isEditable; set => isEditable = value; }
  1302. public bool IsVisible { get => isVisible; set => isVisible = value; }
  1303. public int Index { get => index; set => index = value; }
  1304. public double LineWidth { get => lineWidth; set => lineWidth = value; }
  1305. public Color LineColor { get => lineColor; set => lineColor = value; }
  1306. }
  1307. }