IcsFromERPJob
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

618 lines
23 KiB

4 months ago
4 months ago
4 months ago
2 months ago
4 months ago
2 months ago
4 months ago
2 months ago
4 months ago
2 months ago
4 months ago
4 months ago
4 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Configuration;
  6. using System.Reflection;
  7. using System.IO;
  8. using System.Diagnostics;
  9. using System.Data.SqlClient;
  10. using System.Data;
  11. using System.Data.Common;
  12. using System.Threading.Tasks;
  13. using System.Security.Cryptography;
  14. //using NFine.Data.Extensions;
  15. namespace ICSSoft.FromERP
  16. {
  17. public class ICSHelper
  18. {
  19. private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  20. public static string GetConnectString()
  21. {
  22. try
  23. {
  24. string connectionString = GetConfigString("SysConnectionString");
  25. return connectionString;
  26. }
  27. catch (Exception)
  28. {
  29. throw;
  30. }
  31. }
  32. public static string GetPLMConnectString()
  33. {
  34. try
  35. {
  36. string connectionString = GetConfigString("SysPlmConnectionString");
  37. return connectionString;
  38. }
  39. catch (Exception)
  40. {
  41. throw;
  42. }
  43. }
  44. public static string GetERPConnectString()
  45. {
  46. try
  47. {
  48. string connectionString = GetConfigString("SysErpConnectionString");
  49. return connectionString;
  50. }
  51. catch (Exception)
  52. {
  53. throw;
  54. }
  55. }
  56. public static string GetConfigString(string name)
  57. {
  58. try
  59. {
  60. Configuration config = GetConfig();
  61. string configString = config.ConnectionStrings.ConnectionStrings[name].ConnectionString.ToString();
  62. return configString;
  63. }
  64. catch (Exception)
  65. {
  66. throw;
  67. }
  68. }
  69. public static Dictionary<string, string> GetConfigString()
  70. {
  71. try
  72. {
  73. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  74. Configuration config = GetConfig();
  75. var settings = config.AppSettings.Settings;
  76. foreach (var key in settings.AllKeys)
  77. {
  78. string value = settings[key].Value.ToString();
  79. dictionary.Add(key.ToString(), value);
  80. }
  81. return dictionary;
  82. }
  83. catch (Exception)
  84. {
  85. throw;
  86. }
  87. }
  88. public static Configuration GetConfig()
  89. {
  90. Assembly assembly = Assembly.GetCallingAssembly();
  91. string path = string.Format("{0}.config", assembly.Location);
  92. if (!File.Exists(path))
  93. {
  94. throw new FileNotFoundException(path + "路径下的文件未找到!");
  95. }
  96. try
  97. {
  98. ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
  99. configFile.ExeConfigFilename = path;
  100. Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
  101. return config;
  102. }
  103. catch (Exception)
  104. {
  105. throw;
  106. }
  107. }
  108. public static void Log(string name)
  109. {
  110. string procName = Process.GetCurrentProcess().ProcessName;
  111. using (PerformanceCounter pc = new PerformanceCounter("Process", "Private Bytes", procName))
  112. {
  113. log.Warn(name + "-当前程序内存占用:" + pc.NextValue());
  114. }
  115. long memoryUsed = GC.GetTotalMemory(true);
  116. log.Warn(name + "-内存占用:" + memoryUsed);
  117. }
  118. /// <summary>
  119. /// BS MES
  120. /// </summary>
  121. /// <param name="Namespace"></param>
  122. /// <param name="ClassName"></param>
  123. /// <param name="TenantId"></param>
  124. /// <param name="sql"></param>
  125. /// <param name="TempTableName"></param>
  126. /// <returns></returns>
  127. public static string Time(string Namespace, string ClassName, string TenantId, string sql, string TempTableName)
  128. {
  129. try
  130. {
  131. string value = @"DECLARE @LastTime datetime='2000-01-01'
  132. --
  133. IF NOT EXISTS(SELECT ID FROM ICSERPTime WHERE Namespace='{0}' AND ClassName='{1}' AND TenantId='{2}')
  134. BEGIN
  135. INSERT INTO ICSERPTime VALUES('{0}','{1}',@LastTime
  136. ,'','','{2}'
  137. ,@LastTime,'job',@LastTime,'job','job','job')
  138. END
  139. --
  140. SELECT @LastTime=ModifyDate FROM ICSERPTime WHERE Namespace='{0}' AND ClassName='{1}' AND TenantId='{2}'
  141. --MTIME字段
  142. {3}
  143. --
  144. SELECT @LastTime=MAX(MTIME) FROM {4}
  145. --
  146. UPDATE ICSERPTime SET ModifyDate=@LastTime,LastModificationTime=GETDATE(),LastModifierUserName='job' ,LastModifierUserId='job'
  147. WHERE Namespace='{0}' AND ClassName='{1}' AND TenantId='{2}'
  148. ";
  149. return string.Format(value, Namespace, ClassName, TenantId, sql, TempTableName);
  150. }
  151. catch (Exception ex)
  152. {
  153. log.Error(ex.ToString());
  154. throw;
  155. }
  156. }
  157. /// <summary>
  158. /// CS MES
  159. /// </summary>
  160. /// <param name="Namespace"></param>
  161. /// <param name="Class"></param>
  162. /// <param name="WorkPoint"></param>
  163. /// <param name="sql"></param>
  164. /// <param name="TempTableName"></param>
  165. /// <returns></returns>
  166. public static string Time4Old(string Namespace, string Class, string WorkPoint, string sql, string TempTableName)
  167. {
  168. try
  169. {
  170. string value = @"DECLARE @LastTime datetime='2000-01-01'
  171. --
  172. IF NOT EXISTS(SELECT ID FROM ICSERPTime WHERE Namespace='{0}' AND Class='{1}' AND WorkPoint='{2}')
  173. BEGIN
  174. INSERT INTO ICSERPTime VALUES('{0}','{1}',CONVERT(VARCHAR(10),@LastTime,23),CONVERT(VARCHAR(10),@LastTime,24),GETDATE(),'{2}',@LastTime)
  175. END
  176. --
  177. SELECT @LastTime=DateTime FROM ICSERPTime WHERE Namespace='{0}' AND Class='{1}' AND WorkPoint='{2}'
  178. --MTIME字段
  179. {3}
  180. --
  181. SELECT @LastTime=MAX(MTIME) FROM {4}
  182. --
  183. UPDATE ICSERPTime SET Date=CONVERT(VARCHAR(10),@LastTime,23),Time=CONVERT(VARCHAR(10),@LastTime,24),DateTime=@LastTime,MTIME=GETDATE() WHERE Namespace='{0}' AND Class='{1}' AND WorkPoint='{2}'
  184. ";
  185. return string.Format(value, Namespace, Class, WorkPoint, sql, TempTableName);
  186. }
  187. catch (Exception ex)
  188. {
  189. log.Error(ex.ToString());
  190. throw;
  191. }
  192. }
  193. public static string InsertSQL(string TableName, Dictionary<string, string> values)
  194. {
  195. try
  196. {
  197. string col = string.Empty;
  198. string value = string.Empty;
  199. foreach (var item in values)
  200. {
  201. col += item.Key + ",";
  202. value += item.Value + ",";
  203. }
  204. if (!string.IsNullOrWhiteSpace(value))
  205. {
  206. return string.Format("INSERT INTO {0} ({1}) SELECT {2} FROM ", TableName, col.TrimEnd(','), value.TrimEnd(','));
  207. }
  208. return value;
  209. }
  210. catch (Exception ex)
  211. {
  212. log.Error(ex.ToString());
  213. throw;
  214. }
  215. }
  216. public static string UpdateSQL(string TableName, Dictionary<string, string> values)
  217. {
  218. try
  219. {
  220. string value = string.Empty;
  221. foreach (var item in values)
  222. {
  223. value += item.Key +"="+ item.Value + ",";
  224. }
  225. if (!string.IsNullOrWhiteSpace(value))
  226. {
  227. return string.Format("UPDATE {0} SET {1} FROM ", TableName, value.TrimEnd(','));
  228. }
  229. return "";
  230. }
  231. catch (Exception ex)
  232. {
  233. log.Error(ex.ToString());
  234. throw;
  235. }
  236. }
  237. public static void ExecuteDate(string conStr, string sql)
  238. {
  239. try
  240. {
  241. using (SqlConnection con = new SqlConnection(conStr))
  242. {
  243. con.Open();
  244. try
  245. {
  246. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  247. using (SqlTransaction tran = con.BeginTransaction())
  248. {
  249. using (SqlCommand command = new SqlCommand())
  250. {
  251. command.Connection = con;
  252. command.Transaction = tran;
  253. command.CommandTimeout = 100;
  254. command.CommandText = sql;
  255. try
  256. {
  257. int result = command.ExecuteNonQuery();
  258. tran.Commit();
  259. }
  260. catch (Exception ex)
  261. {
  262. tran.Rollback();
  263. log.Error( ex.ToString() + Environment.NewLine + "异常SQL:" + Environment.NewLine + sql);
  264. }
  265. }
  266. }
  267. }
  268. catch (Exception ex)
  269. {
  270. log.Error(ex.ToString());
  271. throw ex;
  272. }
  273. finally
  274. {
  275. if (con.State == ConnectionState.Open)
  276. con.Close();
  277. con.Dispose();
  278. }
  279. }
  280. }
  281. catch (Exception ex)
  282. {
  283. log.Error(ex.ToString());
  284. throw ex;
  285. }
  286. }
  287. /// <summary>
  288. /// 获取拼音
  289. /// </summary>
  290. /// <param name="str"></param>
  291. /// <returns></returns>
  292. public static string GetPYString(string str)
  293. {
  294. string tempStr = "";
  295. foreach (char c in str)
  296. {
  297. if ((int)c >= 33 && (int)c <= 126)
  298. {//字母和符号原样保留
  299. tempStr += c.ToString();
  300. }
  301. else
  302. {//累加拼音声母
  303. tempStr += GetPYChar(c.ToString());
  304. }
  305. }
  306. return tempStr;
  307. }
  308. ///
  309. /// 取单个字符的拼音声母
  310. ///
  311. /// 要转换的单个汉字
  312. /// 拼音声母
  313. public static string GetPYChar(string c)
  314. {
  315. byte[] array = new byte[2];
  316. array = System.Text.Encoding.Default.GetBytes(c);
  317. int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
  318. if (i < 0xB0A1) return "*";
  319. if (i < 0xB0C5) return "a";
  320. if (i < 0xB2C1) return "b";
  321. if (i < 0xB4EE) return "c";
  322. if (i < 0xB6EA) return "d";
  323. if (i < 0xB7A2) return "e";
  324. if (i < 0xB8C1) return "f";
  325. if (i < 0xB9FE) return "g";
  326. if (i < 0xBBF7) return "h";
  327. if (i < 0xBFA6) return "j";
  328. if (i < 0xC0AC) return "k";
  329. if (i < 0xC2E8) return "l";
  330. if (i < 0xC4C3) return "m";
  331. if (i < 0xC5B6) return "n";
  332. if (i < 0xC5BE) return "o";
  333. if (i < 0xC6DA) return "p";
  334. if (i < 0xC8BB) return "q";
  335. if (i < 0xC8F6) return "r";
  336. if (i < 0xCBFA) return "s";
  337. if (i < 0xCDDA) return "t";
  338. if (i < 0xCEF4) return "w";
  339. if (i < 0xD1B9) return "x";
  340. if (i < 0xD4D1) return "y";
  341. if (i < 0xD7FA) return "z";
  342. return "*";
  343. }
  344. /// <summary>
  345. /// 返回一个数据表
  346. /// </summary>
  347. /// <param name="connectionString">数据库连接字符串</param>
  348. /// <param name="cmdType">命令类型</param>
  349. /// <param name="cmdText">SQL语句</param>
  350. /// <param name="commandParameters">参数</param>
  351. /// <param name="strTableName">数据表名</param>
  352. /// <param name="bIsLoadStru">是否加载数据表结构</param>
  353. /// <returns></returns>
  354. public static DataTable ExecuteTable(string connection, string cmdText)
  355. {
  356. try
  357. {
  358. using (SqlConnection con = new SqlConnection(connection))
  359. {
  360. con.Open();
  361. try
  362. {
  363. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  364. using (SqlCommand command = new SqlCommand())
  365. {
  366. command.CommandText = cmdText;
  367. DataSet ds = new DataSet();
  368. SqlDataAdapter da = new SqlDataAdapter(command);
  369. da.SelectCommand.Connection = con; //加上这个
  370. //da.FillSchema(ds, SchemaType.Source);
  371. da.Fill(ds);
  372. return ds.Tables[0];
  373. }
  374. }
  375. catch (Exception ex)
  376. {
  377. log.Error(ex.ToString());
  378. throw ex;
  379. }
  380. finally
  381. {
  382. if (con.State == ConnectionState.Open)
  383. con.Close();
  384. con.Dispose();
  385. }
  386. }
  387. }
  388. catch (Exception ex)
  389. {
  390. log.Error(ex.ToString());
  391. throw ex;
  392. }
  393. }
  394. /// <summary>
  395. /// BS MES
  396. /// </summary>
  397. /// <param name="conStr"></param>
  398. /// <returns></returns>
  399. public static DataTable GetERPDB(string conStr)
  400. {
  401. try
  402. {
  403. string value = @"SELECT * FROM SysWorkPoint";
  404. return ExecuteTable(conStr, value);
  405. }
  406. catch (Exception ex)
  407. {
  408. log.Error(ex.ToString());
  409. throw;
  410. }
  411. }
  412. /// <summary>
  413. /// CS MES
  414. /// </summary>
  415. /// <param name="conStr"></param>
  416. /// <returns></returns>
  417. public static DataTable GetOldERPDB(string conStr)
  418. {
  419. try
  420. {
  421. string value = @"
  422. SELECT * FROM Sys_WorkPoint";
  423. return ExecuteTable(conStr, value);
  424. }
  425. catch (Exception ex)
  426. {
  427. log.Error(ex.ToString());
  428. throw;
  429. }
  430. }
  431. public static object ExecuteScalar(string connString, string sql)
  432. {
  433. using (SqlConnection conn = new SqlConnection(connString))
  434. {
  435. conn.Open();
  436. object obj = null;
  437. try
  438. {
  439. SqlCommand cmd = new SqlCommand(sql, conn);
  440. //if (spArr.Length > 0)
  441. // cmd.Parameters.AddRange(spArr.SetDBNull());
  442. obj = cmd.ExecuteScalar();
  443. }
  444. catch (Exception ex)
  445. {
  446. log.Error(ex.ToString());
  447. throw ex;
  448. }
  449. finally
  450. {
  451. if (conn.State == ConnectionState.Open)
  452. conn.Close();
  453. //conn.Dispose();
  454. }
  455. return obj;
  456. }
  457. }
  458. public static DateTime GetTime(string Conn, string Namespace, string ClassName, string TenantId)
  459. {
  460. try
  461. {
  462. string value = @"DECLARE @LastTime datetime='2000-01-01'
  463. --
  464. IF NOT EXISTS(SELECT ID FROM ICSERPTime WHERE Namespace='{0}' AND ClassName='{1}' AND TenantId='{2}')
  465. BEGIN
  466. INSERT INTO ICSERPTime VALUES('{0}','{1}',@LastTime
  467. ,'','','{2}'
  468. ,@LastTime,'job',@LastTime,'job','job','job')
  469. END
  470. --
  471. SELECT @LastTime=ModifyDate FROM ICSERPTime WHERE Namespace='{0}' AND ClassName='{1}' AND TenantId='{2}'
  472. --MTIME字段
  473. Select @LastTime
  474. ";
  475. return ExecuteScalar(Conn, string.Format(value, Namespace, ClassName, TenantId)).ToDateTime();
  476. }
  477. catch (Exception ex)
  478. {
  479. log.Error(ex.ToString());
  480. throw;
  481. }
  482. }
  483. public static void UpdateTime(string Conn, string Namespace, string ClassName, string TenantId, DateTime time)
  484. {
  485. try
  486. {
  487. string value = @"DECLARE @LastTime datetime='2000-01-01'
  488. --
  489. IF NOT EXISTS(SELECT ID FROM ICSERPTime WHERE Namespace='{0}' AND ClassName='{1}' AND TenantId='{2}')
  490. BEGIN
  491. INSERT INTO ICSERPTime VALUES('{0}','{1}',@LastTime
  492. ,'','','{2}'
  493. ,@LastTime,'job',@LastTime,'job','job','job')
  494. END
  495. select @LastTime='{3}'
  496. --
  497. UPDATE ICSERPTime SET ModifyDate=@LastTime,LastModificationTime=GETDATE(),LastModifierUserName='job' ,LastModifierUserId='job'
  498. WHERE Namespace='{0}' AND ClassName='{1}' AND TenantId='{2}'
  499. ";
  500. ExecuteScalar(Conn, string.Format(value, Namespace, ClassName, TenantId, time.ToStringBz()));
  501. }
  502. catch (Exception ex)
  503. {
  504. log.Error(ex.ToString());
  505. throw;
  506. }
  507. }
  508. public static void ExecuteDateNew(string conStr, string sql)
  509. {
  510. using (SqlConnection con = new SqlConnection(conStr))
  511. {
  512. con.Open();
  513. try
  514. {
  515. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  516. using (SqlTransaction tran = con.BeginTransaction())
  517. {
  518. using (SqlCommand command = new SqlCommand())
  519. {
  520. command.Connection = con;
  521. command.Transaction = tran;
  522. command.CommandTimeout = 100;
  523. command.CommandText = sql;
  524. try
  525. {
  526. int result = command.ExecuteNonQuery();
  527. tran.Commit();
  528. }
  529. catch (Exception ex)
  530. {
  531. tran.Rollback();
  532. throw ex;
  533. }
  534. }
  535. }
  536. }
  537. catch (Exception ex)
  538. {
  539. log.Error(ex.ToString() + Environment.NewLine + "异常SQL:" + Environment.NewLine + sql);
  540. throw ex;
  541. }
  542. finally
  543. {
  544. if (con.State == ConnectionState.Open)
  545. con.Close();
  546. con.Dispose();
  547. }
  548. }
  549. }
  550. public static string ApiSign(string app_id, string app_secret, long timestamp)
  551. {
  552. return ToMd5($"app_id{app_id}app_secret{app_secret}_timestamp{timestamp}");
  553. }
  554. /// <summary>
  555. /// Md5
  556. /// </summary>
  557. /// <param name="txt"></param>
  558. /// <returns></returns>
  559. public static string ToMd5(string txt)
  560. {
  561. byte[] sor = Encoding.UTF8.GetBytes(txt);
  562. MD5 md5 = MD5.Create();
  563. byte[] result = md5.ComputeHash(sor);
  564. StringBuilder strbul = new StringBuilder(40);
  565. for (int i = 0; i < result.Length; i++)
  566. {
  567. //加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
  568. strbul.Append(result[i].ToString("x2"));
  569. }
  570. return strbul.ToString();
  571. }
  572. }
  573. }