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.

1039 lines
40 KiB

11 months ago
  1. using ICSSoft.ERPWMS.SQL;
  2. using Microsoft.Data.SqlClient;
  3. using Newtonsoft.Json;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Reflection;
  7. using System.Text;
  8. namespace ICSSoft.ERPWMS.Entity
  9. {
  10. public class ICSHelper
  11. {
  12. public static int Count = 10; //每次执行command对象时的个数,sql语句循环增加,一次执行
  13. public static string FileNameCompanyCon = "DLL\\CompanyConnect.txt"; //数据库链接文件
  14. public static string FileNameCompanyCode = "DLL\\CompanyCode.txt"; //公司代码文件
  15. private static log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  16. // private static string appConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
  17. #region 读取配置文件
  18. public static Dictionary<string, string> ReadConfig(string FileName)
  19. {
  20. try
  21. {
  22. //fileName = System.Web.Hosting.HostingEnvironment.MapPath("~") + "\\" + fileName;
  23. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  24. StreamReader sr = new StreamReader(FileName, Encoding.Default);
  25. string company;
  26. while ((company = sr.ReadLine()) != null)
  27. {
  28. log.Debug(company);
  29. if (string.IsNullOrEmpty(company))
  30. continue;
  31. string[] str = company.Split(':');
  32. if (str.Length > 1)
  33. {
  34. dictionary.Add(str[0], str[1]);
  35. }
  36. else
  37. {
  38. throw new Exception("配置文件格式错误,请检查文件:" + FileName + "," + str[0] + "\r\n");
  39. }
  40. }
  41. sr.Close();
  42. return dictionary;
  43. }
  44. catch (Exception ex)
  45. {
  46. //log.Error("读取配置文件异常:" + ex.ToString());
  47. throw ex;
  48. }
  49. }
  50. #endregion
  51. public static DataTable GetDataTable(string sql)
  52. {
  53. try
  54. {
  55. using (SqlConnection m_cnn = new SqlConnection(ReadConfig(FileNameCompanyCon)["WMS"].ToString()))//GetConnectStringTest(key)
  56. {
  57. DataTable dt = new DataTable();
  58. SqlDataAdapter m_da = new SqlDataAdapter(sql, m_cnn);
  59. m_da.SelectCommand.CommandTimeout = 6000;
  60. m_da.SelectCommand.CommandType = CommandType.Text;
  61. m_da.SelectCommand.CommandText = sql;
  62. m_da.Fill(dt);
  63. return dt;
  64. }
  65. }
  66. catch (Exception ex)
  67. {
  68. //log.Error("查询SQL异常:" + ex.ToString());
  69. throw ex;
  70. }
  71. }
  72. public static DataTable GetDataTableERP(string sql)
  73. {
  74. try
  75. {
  76. using (SqlConnection m_cnn = new SqlConnection(ReadConfig(FileNameCompanyCon)["ERP"].ToString()))
  77. {
  78. DataTable dt = new DataTable();
  79. SqlDataAdapter m_da = new SqlDataAdapter(sql, m_cnn);
  80. m_da.SelectCommand.CommandTimeout = 6000;
  81. m_da.SelectCommand.CommandType = CommandType.Text;
  82. m_da.SelectCommand.CommandText = sql;
  83. m_da.Fill(dt);
  84. return dt;
  85. }
  86. }
  87. catch (Exception ex)
  88. {
  89. //log.Error("查询SQL异常:" + ex.ToString());
  90. throw ex;
  91. }
  92. }
  93. /// <summary>
  94. /// 事物取DataTable
  95. /// </summary>
  96. /// <param name="SQl"></param>
  97. /// <param name="cmd"></param>
  98. /// <returns></returns>
  99. public static DataTable SQlReturnData(string SQl, SqlCommand cmd)
  100. {
  101. DataTable dt = new DataTable();
  102. SqlDataAdapter dr = new SqlDataAdapter();
  103. cmd.CommandText = SQl;
  104. dr.SelectCommand = cmd;
  105. dr.Fill(dt);
  106. return dt;
  107. }
  108. public static bool ExecuteNonQuery(string sql, SqlCommand cmd)
  109. {
  110. try
  111. {
  112. cmd.CommandText = sql;
  113. cmd.ExecuteNonQuery();
  114. return true;
  115. //if (result > 0)
  116. //{
  117. // return true;
  118. //}
  119. //else
  120. //{
  121. // log.Info("SQL执行受影响行数<0;" + sql);
  122. // return false;
  123. //}
  124. }
  125. catch (Exception ex)
  126. {
  127. string Params = string.Empty;
  128. foreach (SqlParameter parameter in cmd.Parameters)
  129. {
  130. Params += parameter.SqlValue + "||";
  131. }
  132. log.Error("异常:" + ex.Message + ";\r\n SQL:" + sql + "参数:" + Params);
  133. return false;
  134. }
  135. }
  136. public static int ExecuteSqlERP(string sqlUpdate)
  137. {
  138. using (SqlConnection conn = new SqlConnection(ReadConfig(FileNameCompanyCon)["ERP"].ToString()))
  139. {
  140. try
  141. {
  142. SqlCommand cmd = new SqlCommand();
  143. cmd.CommandText = sqlUpdate;
  144. if (conn.State != ConnectionState.Open)
  145. {
  146. conn.Open();
  147. }
  148. cmd.Connection = conn;
  149. return cmd.ExecuteNonQuery();
  150. }
  151. catch (Exception ex)
  152. {
  153. throw new Exception(ex.Message);
  154. }
  155. finally
  156. {
  157. if (conn.State != ConnectionState.Closed)
  158. {
  159. conn.Close();
  160. }
  161. }
  162. }
  163. }
  164. public static int ExecuteSql(string sqlUpdate)
  165. {
  166. using (SqlConnection conn = new SqlConnection(ReadConfig(FileNameCompanyCon)["WMS"].ToString()))
  167. {
  168. try
  169. {
  170. SqlCommand cmd = new SqlCommand();
  171. cmd.CommandText = sqlUpdate;
  172. if (conn.State != ConnectionState.Open)
  173. {
  174. conn.Open();
  175. }
  176. cmd.Connection = conn;
  177. return cmd.ExecuteNonQuery();
  178. }
  179. catch (Exception ex)
  180. {
  181. throw new Exception(ex.Message);
  182. }
  183. finally
  184. {
  185. if (conn.State != ConnectionState.Closed)
  186. {
  187. conn.Close();
  188. }
  189. }
  190. }
  191. }
  192. public static void ExecuteDateERP(string sql)
  193. {
  194. try
  195. {
  196. using (SqlConnection con = new SqlConnection(ReadConfig(FileNameCompanyCon)["ERP"].ToString()))
  197. {
  198. con.Open();
  199. try
  200. {
  201. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  202. using (SqlTransaction tran = con.BeginTransaction())
  203. {
  204. using (SqlCommand command = new SqlCommand())
  205. {
  206. command.Connection = con;
  207. command.Transaction = tran;
  208. command.CommandTimeout = 100;
  209. command.CommandText = sql;
  210. try
  211. {
  212. int result = command.ExecuteNonQuery();
  213. tran.Commit();
  214. }
  215. catch (Exception ex)
  216. {
  217. tran.Rollback();
  218. log.Error(ex.ToString() + Environment.NewLine + "异常SQL:" + Environment.NewLine + sql);
  219. }
  220. }
  221. }
  222. }
  223. catch (Exception ex)
  224. {
  225. log.Error(ex.ToString());
  226. throw ex;
  227. }
  228. finally
  229. {
  230. if (con.State == ConnectionState.Open)
  231. con.Close();
  232. con.Dispose();
  233. }
  234. }
  235. }
  236. catch (Exception ex)
  237. {
  238. log.Error(ex.ToString());
  239. throw ex;
  240. }
  241. }
  242. public static void ExecuteDate(string sql)
  243. {
  244. try
  245. {
  246. using (SqlConnection con = new SqlConnection(ReadConfig(FileNameCompanyCon)["WMS"].ToString()))
  247. {
  248. con.Open();
  249. try
  250. {
  251. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  252. using (SqlTransaction tran = con.BeginTransaction())
  253. {
  254. using (SqlCommand command = new SqlCommand())
  255. {
  256. command.Connection = con;
  257. command.Transaction = tran;
  258. command.CommandTimeout = 100;
  259. command.CommandText = sql;
  260. try
  261. {
  262. int result = command.ExecuteNonQuery();
  263. tran.Commit();
  264. }
  265. catch (Exception ex)
  266. {
  267. tran.Rollback();
  268. log.Error(ex.ToString() + Environment.NewLine + "异常SQL:" + Environment.NewLine + sql);
  269. }
  270. }
  271. }
  272. }
  273. catch (Exception ex)
  274. {
  275. log.Error(ex.ToString());
  276. throw ex;
  277. }
  278. finally
  279. {
  280. if (con.State == ConnectionState.Open)
  281. con.Close();
  282. con.Dispose();
  283. }
  284. }
  285. }
  286. catch (Exception ex)
  287. {
  288. log.Error(ex.ToString());
  289. throw ex;
  290. }
  291. }
  292. public static string GetConnectStringTest(string key)
  293. {
  294. try
  295. {
  296. Dictionary<string, string> ss = ReadConfig(FileNameCompanyCode);
  297. if (ss.ContainsKey(key))
  298. {
  299. return ss[key];
  300. }
  301. else
  302. {
  303. return "NotExit";
  304. }
  305. }
  306. catch (Exception ex)
  307. {
  308. return ex.Message;
  309. }
  310. }
  311. public static Dictionary<string, string> InsertDate(string conStr, Dictionary<string, string> sqls)
  312. {
  313. try
  314. {
  315. SqlConnection con = new SqlConnection(conStr);
  316. con.Open();
  317. try
  318. {
  319. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  320. foreach (var sql in sqls)
  321. {
  322. using (SqlTransaction tran = con.BeginTransaction())
  323. {
  324. using (SqlCommand command = new SqlCommand())
  325. {
  326. command.Connection = con;
  327. command.Transaction = tran;
  328. command.CommandText = sql.Value;
  329. try
  330. {
  331. int result = command.ExecuteNonQuery();
  332. //获取sql中插入条数
  333. //int count = Regex.Matches(sql.ToUpper(), "INSERT").Count;
  334. //if (result < count)
  335. if (result <= 0)
  336. {
  337. throw new Exception("插入数据失败!");
  338. }
  339. tran.Commit();
  340. }
  341. catch (Exception ex)
  342. {
  343. tran.Rollback();
  344. log.Error(sql.Key + Environment.NewLine + ex.ToString() + Environment.NewLine + "异常SQL:" + Environment.NewLine + sql.Value);
  345. dictionary.Add(sql.Key, ex.ToString());
  346. }
  347. }
  348. }
  349. }
  350. return dictionary;
  351. }
  352. catch (Exception ex)
  353. {
  354. //log.Error(ex.ToString());
  355. throw ex;
  356. }
  357. finally
  358. {
  359. if (con.State == ConnectionState.Open)
  360. con.Close();
  361. con.Dispose();
  362. }
  363. }
  364. catch (Exception ex)
  365. {
  366. //log.Error(ex.ToString());
  367. throw ex;
  368. }
  369. }
  370. /// <summary>
  371. /// 执行Insert 或者 Update
  372. /// </summary>
  373. /// <param name="sql"></param>
  374. /// <param name="cmd"></param>
  375. /// <param name="message"></param>
  376. public static void CmdExecuteNonQuery(string sql, SqlCommand cmd, string message)
  377. {
  378. try
  379. {
  380. cmd.CommandText = sql;
  381. int count = cmd.ExecuteNonQuery();
  382. if (count <= 0)
  383. {
  384. string Msg = string.Empty;
  385. foreach (SqlParameter parameter in cmd.Parameters)
  386. {
  387. Msg += "参数名:" + parameter.ParameterName + "参数值:" + parameter.Value;
  388. }
  389. log.Info("受影响行数小于0;" + sql + "\r\n" + Msg);
  390. throw new Exception(message);
  391. }
  392. }
  393. catch (Exception ex)
  394. {
  395. string Msg = string.Empty;
  396. foreach (SqlParameter parameter in cmd.Parameters)
  397. {
  398. Msg += "参数名:" + parameter.ParameterName + "参数值:" + parameter.Value;
  399. }
  400. log.Info("异常:" + ex.Message + "\r\n " + message + "\r\n SQL:" + sql + "\r\n" + Msg);
  401. throw new Exception(message + Environment.NewLine + ex.Message);
  402. }
  403. }
  404. //public static List<OutInventoryModel> OutDate(string conStr, Dictionary<string, string> sqls,string uid,string meg)
  405. //{
  406. // List<OutInventoryModel> lonm = new List<OutInventoryModel>();
  407. // List<OutInventory> lon = new List<OutInventory>();
  408. // OutInventoryModel otm = new OutInventoryModel();
  409. // try
  410. // {
  411. // SqlConnection con = new SqlConnection(conStr);
  412. // con.Open();
  413. // try
  414. // {
  415. // foreach (var sql in sqls)
  416. // {
  417. // //S:成功E:失败
  418. // using (SqlTransaction tran = con.BeginTransaction())
  419. // {
  420. // using (SqlCommand command = new SqlCommand())
  421. // {
  422. // command.Connection = con;
  423. // command.Transaction = tran;
  424. // command.CommandText = sql.Value;
  425. // try
  426. // {
  427. // int result = command.ExecuteNonQuery();
  428. // //获取sql中插入条数
  429. // //int count = Regex.Matches(sql.ToUpper(), "INSERT").Count;
  430. // //if (result < count)
  431. // if (result <= 0)
  432. // {
  433. // throw new Exception("插入数据失败!");
  434. // }
  435. // else
  436. // {
  437. // if (meg != "")
  438. // {
  439. // OutInventory otn = new OutInventory();
  440. // otn.id = sql.Key;
  441. // otn.result = "E";
  442. // otn.message = meg;
  443. // lon.Add(otn);
  444. // otm.UID = uid;
  445. // otm.product = lon;
  446. // lonm.Add(otm);
  447. // }
  448. // else
  449. // {
  450. // OutInventory otn = new OutInventory();
  451. // otn.id = sql.Key;
  452. // otn.result = "S";
  453. // otn.message = "";
  454. // lon.Add(otn);
  455. // otm.UID = uid;
  456. // otm.product = lon;
  457. // lonm.Add(otm);
  458. // }
  459. // }
  460. // tran.Commit();
  461. // }
  462. // catch (Exception ex)
  463. // {
  464. // tran.Rollback();
  465. // log.Error(sql.Key + Environment.NewLine + ex.ToString() + Environment.NewLine + "异常SQL:" + Environment.NewLine + sql.Value);
  466. // OutInventory otn = new OutInventory();
  467. // otn.id = sql.Key;
  468. // otn.result = "E";
  469. // string exe=ex.ToString().Substring(0, ex.ToString().IndexOf("在 System")).Replace("\u000d\u000a", "").ToString()+meg;
  470. // otn.message = exe.Substring(exe.IndexOf(":"));
  471. // lon.Add(otn);
  472. // otm.UID = uid;
  473. // otm.product = lon;
  474. // lonm.Add(otm);
  475. // }
  476. // }
  477. // }
  478. // }
  479. // List<OutInventoryModel> lom = new List<OutInventoryModel>();
  480. // lom.Add(lonm[0]);
  481. // return lom;
  482. // }
  483. // catch (Exception ex)
  484. // {
  485. // //log.Error(ex.ToString());
  486. // throw ex;
  487. // }
  488. // finally
  489. // {
  490. // if (con.State == ConnectionState.Open)
  491. // con.Close();
  492. // con.Dispose();
  493. // }
  494. // }
  495. // catch (Exception ex)
  496. // {
  497. // //log.Error(ex.ToString());
  498. // throw ex;
  499. // }
  500. //}
  501. /// <summary>
  502. /// 根据传入的日期,需要增加的天数返回一个字符串
  503. /// </summary>
  504. /// <param name="data"></param>
  505. /// <param name="str"></param>
  506. public static string ReTime(DateTime data, int str)
  507. {
  508. int year = data.Year;
  509. int month = data.Month;
  510. int day = data.Day;
  511. int n = DateTime.DaysInMonth(year, month);
  512. int k = day + str;
  513. if (k > n)
  514. {
  515. day = str - (n - day);
  516. month = month + 1;
  517. if (month > 12)
  518. {
  519. month = 1;
  520. year = year + 1;
  521. }
  522. }
  523. else
  524. {
  525. day = day + str;
  526. }
  527. string c = year + "-" + month + "-" + day;
  528. return c;
  529. }
  530. public static string GetIDSql(string caccId, string cVouchType, string key, GetID type)
  531. {
  532. try
  533. {
  534. string sql = "";
  535. if (type.Equals(GetID.ALL))
  536. {
  537. sql = @"DECLARE @ID" + key + @" int
  538. DECLARE @DID" + key + @" int
  539. SET @ID" + key + @" = 0
  540. SET @DID" + key + @" = 0
  541. IF NOT EXISTS (SELECT * FROM UFSystem..ua_identity WHERE cacc_id = '{0}' AND cVouchType = '{1}')
  542. BEGIN
  543. INSERT INTO UFSystem..ua_identity(cAcc_Id,cVouchType,iFatherId,iChildId) VALUES('{0}','{1}',1,1)
  544. END
  545. ELSE
  546. BEGIN
  547. UPDATE UFSystem..ua_identity
  548. SET ifatherID = ifatherID + 1,ichildID = ichildID + 1
  549. WHERE cAcc_id = '{0}' AND cVouchType = '{1}'
  550. END
  551. SELECT @ID" + key + @" = ifatherID,@DID" + key + @" = ichildID
  552. FROM UFSystem..ua_identity
  553. WHERE cAcc_id = '{0}' AND cVouchType = '{1}'";
  554. }
  555. else if (type.Equals(GetID.FATHER))
  556. {
  557. sql = @"DECLARE @ID" + key + @" int
  558. SET @ID" + key + @" = 0
  559. IF NOT EXISTS (SELECT * FROM UFSystem..ua_identity WHERE cacc_id = '{0}' AND cVouchType = '{1}')
  560. BEGIN
  561. INSERT INTO UFSystem..ua_identity(cAcc_Id,cVouchType,iFatherId,iChildId) VALUES('{0}','{1}',1,1)
  562. END
  563. ELSE
  564. BEGIN
  565. UPDATE UFSystem..ua_identity
  566. SET ifatherID = ifatherID + 1
  567. WHERE cAcc_id = '{0}' AND cVouchType = '{1}'
  568. END
  569. SELECT @ID" + key + @" = ifatherID
  570. FROM UFSystem..ua_identity
  571. WHERE cAcc_id = '{0}' AND cVouchType = '{1}'";
  572. }
  573. else if (type.Equals(GetID.CHILD))
  574. {
  575. sql = @" DECLARE @DID" + key + @" int
  576. SET @DID" + key + @" = 0
  577. IF NOT EXISTS (SELECT * FROM UFSystem..ua_identity WHERE cacc_id = '{0}' AND cVouchType = '{1}')
  578. BEGIN
  579. INSERT INTO UFSystem..ua_identity(cAcc_Id,cVouchType,iFatherId,iChildId) VALUES('{0}','{1}',1,1)
  580. END
  581. ELSE
  582. BEGIN
  583. UPDATE UFSystem..ua_identity
  584. SET ichildID = ichildID + 1
  585. WHERE cAcc_id = '{0}' AND cVouchType = '{1}'
  586. END
  587. SELECT @DID" + key + @" = ichildID
  588. FROM UFSystem..ua_identity
  589. WHERE cAcc_id = '{0}' AND cVouchType = '{1}'";
  590. }
  591. sql = string.Format(sql, caccId, cVouchType);
  592. return sql;
  593. }
  594. catch (Exception)
  595. {
  596. throw;
  597. }
  598. }
  599. public static string GetVouchSql(string CardNumber, string key)
  600. {
  601. try
  602. {
  603. string sql = @"DECLARE @Num" + key + @" int,@seed VARCHAR(4)
  604. SET @Num" + key + @" = 0
  605. SET @seed=Substring(Convert( varchar(100),GetDate(),112),3,4)
  606. IF NOT EXISTS (SELECT cNumber FROM VoucherHistory WHERE cSeed = @seed and CardNumber = '{1}')
  607. BEGIN
  608. INSERT INTO VoucherHistory(CardNumber,cContent,cContentRule,cSeed,cNumber) VALUES('{1}','','',@seed,'1')
  609. END
  610. ELSE
  611. BEGIN
  612. UPDATE VoucherHistory
  613. SET cNumber = cNumber + 1
  614. WHERE cSeed = @seed and CardNumber = '{1}'
  615. END
  616. SELECT @Num" + key + @" = cNumber
  617. FROM VoucherHistory
  618. WHERE cSeed = @seed and CardNumber = '{1}'";
  619. sql = string.Format(sql, "{0}", CardNumber);
  620. return sql;
  621. }
  622. catch (Exception)
  623. {
  624. throw;
  625. }
  626. }
  627. public static string GetVTID(string CardNumber, string key)
  628. {
  629. try
  630. {
  631. string sql = @"DECLARE @VTID" + key + @" INT
  632. SELECT @VTID" + key + @"=DEF_ID FROM Vouchers WHERE CardNumber = '{0}' ";
  633. sql = string.Format(sql, CardNumber);
  634. return sql;
  635. }
  636. catch (Exception)
  637. {
  638. throw;
  639. }
  640. }
  641. public static object ExecuteScalar(CommandType cmdType, string cmdText, string conn)
  642. {
  643. try
  644. {
  645. DbCommand cmd = CreateDbCommand();
  646. using (DbConnection connection = CreateDbConnection(conn))
  647. {
  648. PrepareCommand(cmd, connection, null, cmdType, cmdText, null);
  649. object val = cmd.ExecuteScalar();
  650. cmd.Parameters.Clear();
  651. return val;
  652. }
  653. }
  654. catch (Exception ex)
  655. {
  656. //log.Error(ex.Message);
  657. throw;
  658. }
  659. }
  660. /// <summary>
  661. /// 数据库类型
  662. /// </summary>
  663. public static DatabaseType DbType { get; set; }
  664. /// <summary>
  665. /// 根据配置文件中所配置的数据库类型和传入的
  666. /// 数据库链接字符串来创建相应数据库连接对象
  667. /// </summary>
  668. /// <param name="connectionString"></param>
  669. /// <returns></returns>
  670. public static DbConnection CreateDbConnection(string connectionString)
  671. {
  672. DbConnection conn = null;
  673. switch (DbType)
  674. {
  675. case DatabaseType.SqlServer:
  676. conn = new SqlConnection(connectionString);
  677. break;
  678. //case DatabaseType.Oracle:
  679. // conn = new OracleConnection(connectionString);
  680. // break;
  681. //case DatabaseType.MySql:
  682. // conn = new MySqlConnection(connectionString);
  683. // break;
  684. //case DatabaseType.Access:
  685. // conn = new OleDbConnection(connectionString);
  686. // break;
  687. //case DatabaseType.SQLite:
  688. // conn = new SQLiteConnection(connectionString);
  689. // break;
  690. default:
  691. throw new Exception("数据库类型目前不支持!");
  692. }
  693. return conn;
  694. }
  695. /// <summary>
  696. /// 根据配置文件中所配置的数据库类型
  697. /// 来创建相应数据库命令对象
  698. /// </summary>
  699. /// <returns></returns>
  700. public static DbCommand CreateDbCommand()
  701. {
  702. DbCommand cmd = null;
  703. switch (DbType)
  704. {
  705. case DatabaseType.SqlServer:
  706. cmd = new SqlCommand();
  707. break;
  708. //case DatabaseType.Oracle:
  709. // cmd = new OracleCommand();
  710. // break;
  711. //case DatabaseType.MySql:
  712. // cmd = new MySqlCommand();
  713. // break;
  714. //case DatabaseType.Access:
  715. // cmd = new OleDbCommand();
  716. // break;
  717. //case DatabaseType.SQLite:
  718. // cmd = new SQLiteCommand();
  719. // break;
  720. default:
  721. throw new Exception("数据库类型目前不支持!");
  722. }
  723. return cmd;
  724. }
  725. /// <summary>
  726. /// 方法一:获取编号 返回Dictionary字典,调用该方法用Dictionary字典接收,只需要遍历Dictionary即可得到响应的值
  727. /// </summary>
  728. /// <param name="cAcc_Id"></param>
  729. /// <param name="cVouchType"></param>
  730. /// <param name="iAmount"></param>
  731. /// <returns></returns>
  732. public static Dictionary<string, int> GetAllCode(string cAcc_Id, string cVouchType, string iAmount, string key)
  733. {
  734. string iFatherId = string.Empty, iChildId = string.Empty;
  735. Dictionary<string, int> dic = new Dictionary<string, int>();
  736. try
  737. {
  738. SqlConnection conn = new SqlConnection(GetConnectStringTest(key));
  739. SqlCommand cmd = new SqlCommand("sp_GetIDWithoutRemote", conn);
  740. cmd.CommandType = CommandType.StoredProcedure;
  741. cmd.Parameters.AddWithValue("@cAcc_Id", cAcc_Id);  //给输入参数赋值
  742. cmd.Parameters.AddWithValue("@cVouchType", cVouchType);  //给输入参数赋值
  743. cmd.Parameters.AddWithValue("@iAmount", iAmount);  //给输入参数赋值
  744. //cmd.Parameters.AddWithValue("@iFatherId", iFatherId);  //给输入参数赋值
  745. //cmd.Parameters.AddWithValue("@iChildId", iChildId);  //给输入参数赋值
  746. SqlParameter parOutput = cmd.Parameters.Add("@iFatherId", SqlDbType.NVarChar, 50);  //定义输出参数
  747. cmd.Parameters["@iFatherId"].Direction = ParameterDirection.Output;
  748. SqlParameter parOutputs = cmd.Parameters.Add("@iChildId", SqlDbType.NVarChar, 50);  //定义输出参数
  749. cmd.Parameters["@iChildId"].Direction = ParameterDirection.Output;
  750. SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
  751. parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
  752. cmd.Parameters.Add(parReturn);
  753. conn.Open();
  754. cmd.ExecuteNonQuery();
  755. iFatherId = cmd.Parameters["@iFatherId"].Value.ToString();
  756. iChildId = cmd.Parameters["@iChildId"].Value.ToString();
  757. if (!string.IsNullOrEmpty(iFatherId))//判断iFatherId是否为空,不为空的话将值放入dictionary字典中,否则int.Parse()会抛出异常
  758. {
  759. dic.Add("iFatherId", int.Parse(iFatherId));
  760. dic.Add("iChildId", int.Parse(iChildId));
  761. }
  762. }
  763. catch (Exception ex)
  764. {
  765. throw ex;
  766. }
  767. return dic;
  768. }
  769. /// <summary>
  770. /// 方法二 使用输出参数值
  771. /// </summary>
  772. /// <param name="cAcc_Id"></param>
  773. /// <param name="cVouchType"></param>
  774. /// <param name="iAmount"></param>
  775. /// <returns></returns>
  776. public static string GetAllRDCode(string CardNumber, string dDate, string UserCode, string key)
  777. {
  778. string iBaseCodeLen = string.Empty; string cVouchCodeBase = string.Empty;
  779. Dictionary<string, int> dic = new Dictionary<string, int>();
  780. try
  781. {
  782. SqlConnection conn = new SqlConnection(GetConnectStringTest(key));
  783. SqlCommand cmd = new SqlCommand("ICS_VoucherNumber", conn);
  784. cmd.CommandType = CommandType.StoredProcedure;
  785. cmd.Parameters.AddWithValue("@CardNumber", CardNumber);  //给输入参数赋值
  786. cmd.Parameters.AddWithValue("@dDate", dDate);  //给输入参数赋值
  787. cmd.Parameters.AddWithValue("@UserCode", UserCode);  //给输入参数赋值
  788. SqlParameter parOutput = cmd.Parameters.Add("@number", SqlDbType.NVarChar, 50);  //定义输出参数
  789. parOutput.Direction = ParameterDirection.Output;
  790. //SqlParameter parReturn = new SqlParameter("@return", SqlDbType.Int);
  791. //parReturn.Direction = ParameterDirection.ReturnValue;   //参数类型为ReturnValue
  792. //cmd.Parameters.Add(parReturn);
  793. conn.Open();
  794. cmd.ExecuteNonQuery();
  795. return parOutput.Value.ToString();
  796. //iBaseCodeLen = cmd.Parameters["@iBaseCodeLen"].Value.ToString();
  797. // cVouchCodeBase = cmd.Parameters["@cVouchCodeBase"].Value.ToString();
  798. //UserCode= cmd.Parameters["@cVouchCodePreFix"].Value.ToString();
  799. ////if (!string.IsNullOrWhiteSpace(iBaseCodeLen))//判断iFatherId是否为空,不为空的话将值放入dictionary字典中,否则int.Parse()会抛出异常
  800. ////{
  801. //// dic.Add("iBaseCodeLen", int.Parse(iBaseCodeLen));
  802. ////}
  803. ////else
  804. ////{
  805. //// dic.Add("cVouchCodeBase", int.Parse(cVouchCodeBase));
  806. // UserCode= UserCode + (cVouchCodeBase.ToString().PadLeft(int.Parse(iBaseCodeLen), '0'));
  807. ////}
  808. }
  809. catch (Exception ex)
  810. {
  811. throw ex;
  812. }
  813. //return UserCode;
  814. }
  815. public static int CheckTimes(string Class,string Type)
  816. {
  817. DataTable dtRecordCheck = new DataTable();
  818. string sqlRecordCheck = "Select Times from ICSApiRecord Where ApiName='{0}' and DateTime ='{1}'";
  819. sqlRecordCheck = string.Format(sqlRecordCheck, Class, DateTime.Now.ToString("yyyyMMdd"));
  820. if (Type=="ERP")
  821. {
  822. dtRecordCheck = GetDataTableERP(sqlRecordCheck);
  823. }
  824. else
  825. {
  826. dtRecordCheck = GetDataTable(sqlRecordCheck);
  827. }
  828. if (dtRecordCheck != null && dtRecordCheck.Rows.Count > 0)
  829. {
  830. return Convert.ToInt32(dtRecordCheck.Rows[0]["Times"].ToString());
  831. }
  832. else
  833. {
  834. return 0;
  835. }
  836. }
  837. //获取Token
  838. public static TokenResult GetAuthkey(string Secret,string LoginID,string Type)
  839. {
  840. TokenResult res = new TokenResult();
  841. if (Secret==""|| LoginID=="")
  842. {
  843. res.IsSuccess = false;
  844. res.Message = "参数为空!";
  845. }
  846. else
  847. {
  848. try
  849. {
  850. GetToken action = new GetToken();
  851. string resultStr = action.Get(new GetToken.ICSLogin { Secret = Secret,LoginID = LoginID,Type = Type});
  852. if (resultStr.Length > 0)
  853. {
  854. res.IsSuccess = true;
  855. res.Message = "调用成功!";
  856. res.Authkey = resultStr;
  857. }
  858. else
  859. {
  860. res.IsSuccess = false;
  861. res.Message = "调用失败";
  862. }
  863. }
  864. catch (Exception ex)
  865. {
  866. log.Error("调用后台失败:" + ex.ToString());
  867. res.IsSuccess = false;
  868. res.Message = ex.Message;
  869. }
  870. }
  871. return res;
  872. }
  873. public enum DatabaseType
  874. {
  875. /// <summary>
  876. /// 数据库类型:Oracle
  877. /// </summary>
  878. Oracle,
  879. /// <summary>
  880. /// 数据库类型:SqlServer
  881. /// </summary>
  882. SqlServer,
  883. /// <summary>
  884. /// 数据库类型:Access
  885. /// </summary>
  886. Access,
  887. /// <summary>
  888. /// 数据库类型:MySql
  889. /// </summary>
  890. MySql,
  891. /// <summary>
  892. /// 数据库类型:SQLite
  893. /// </summary>
  894. SQLite
  895. }
  896. /// <summary>
  897. /// 为即将执行准备一个命令
  898. /// </summary>
  899. /// <param name="cmd">SqlCommand对象</param>
  900. /// <param name="conn">SqlConnection对象</param>
  901. /// <param name="isOpenTrans">DbTransaction对象</param>
  902. /// <param name="cmdType">执行命令的类型(存储过程或T-SQL,等等)</param>
  903. /// <param name="cmdText">存储过程名称或者T-SQL命令行, e.g. Select * from Products</param>
  904. /// <param name="cmdParms">SqlParameters to use in the command</param>
  905. private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction isOpenTrans, CommandType cmdType, string cmdText, DbParameter[] cmdParms)
  906. {
  907. if (conn.State != ConnectionState.Open)
  908. conn.Open();
  909. cmd.Connection = conn;
  910. cmd.CommandText = cmdText;
  911. if (isOpenTrans != null)
  912. cmd.Transaction = isOpenTrans;
  913. cmd.CommandType = cmdType;
  914. if (cmdParms != null)
  915. {
  916. cmd.Parameters.AddRange(cmdParms);
  917. }
  918. }
  919. }
  920. public enum GetID
  921. {
  922. ALL,
  923. FATHER,
  924. CHILD
  925. }
  926. /// <summary>
  927. /// data转List
  928. /// </summary>
  929. /// <typeparam name="T"></typeparam>
  930. public class ModelConvertHelper<T> where T : new()
  931. {
  932. public static IList<T> ConvertToModel(DataTable dt)
  933. {
  934. // 定义集合
  935. IList<T> ts = new List<T>();
  936. // 获得此模型的类型
  937. Type type = typeof(T);
  938. string tempName = "";
  939. foreach (DataRow dr in dt.Rows)
  940. {
  941. T t = new T();
  942. // 获得此模型的公共属性
  943. PropertyInfo[] propertys = t.GetType().GetProperties();
  944. foreach (PropertyInfo pi in propertys)
  945. {
  946. tempName = pi.Name; // 检查DataTable是否包含此列
  947. if (dt.Columns.Contains(tempName))
  948. {
  949. // 判断此属性是否有Setter
  950. if (!pi.CanWrite) continue;
  951. object value = dr[tempName];
  952. if (value != DBNull.Value)
  953. pi.SetValue(t, value, null);
  954. }
  955. }
  956. ts.Add(t);
  957. }
  958. return ts;
  959. }
  960. }
  961. }