ComBase.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. using Castle.ActiveRecord;
  2. using Castle.ActiveRecord.Framework;
  3. using NHibernate.Criterion;
  4. using SQLData;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Data.SqlClient;
  9. using System.Text.RegularExpressions;
  10. namespace BizCom
  11. {
  12. public class ComBase<T> : ActiveRecordBase<T>
  13. {
  14. #region 自定义
  15. private static readonly Dictionary<Type, string> _dicTable = new Dictionary<Type, string>();
  16. private static object dicTable_Flag = 1;
  17. /// <summary>
  18. /// 表名
  19. /// </summary>
  20. public string TName
  21. {
  22. get { return GetTableName(); }
  23. }
  24. public static IDataAccess DbConn
  25. {
  26. get { return DbHelper.DbConn; }
  27. }
  28. public static DbTrans DbTran
  29. {
  30. get { return DbHelper.DbTran; }
  31. }
  32. /// <summary>
  33. /// 返回ProgID
  34. /// </summary>
  35. /// <returns>ProgId</returns>
  36. public virtual string GetTableName()
  37. {
  38. Type lType = GetType();
  39. if (!_dicTable.ContainsKey(lType))
  40. {
  41. lock (dicTable_Flag)
  42. {
  43. if (!_dicTable.ContainsKey(lType))
  44. {
  45. var attribute = GetAttribute<ActiveRecordAttribute>(lType);
  46. _dicTable.Add(lType, attribute.Table);
  47. }
  48. }
  49. }
  50. return _dicTable[lType];
  51. }
  52. private T GetAttribute<T>(Type lType) where T : Attribute
  53. {
  54. object[] aArr = lType.GetCustomAttributes(false);
  55. for (int i = 0; i < aArr.Length; i++)
  56. {
  57. if (typeof(T) == aArr[i].GetType())
  58. return (T)aArr[i];
  59. }
  60. return null;
  61. }
  62. /// <summary>
  63. /// 返回ProgID
  64. /// </summary>
  65. /// <returns>ProgId</returns>
  66. public static string GetViewName()
  67. {
  68. string gName = GetName();
  69. gName = Regex.Replace(gName, "X_", "view_", RegexOptions.IgnoreCase);
  70. gName = Regex.Replace(gName, "S_", "view_", RegexOptions.IgnoreCase);
  71. return gName;
  72. }
  73. /// <summary>
  74. /// 返回ProgID
  75. /// </summary>
  76. /// <returns>ProgId</returns>
  77. public static string GetName()
  78. {
  79. Type lType = typeof(T);
  80. if (!_dicTable.ContainsKey(lType))
  81. {
  82. lock (dicTable_Flag)
  83. {
  84. if (!_dicTable.ContainsKey(lType))
  85. {
  86. var attribute = GetAttributeByView<ActiveRecordAttribute>(lType);
  87. _dicTable.Add(lType, attribute.Table);
  88. }
  89. }
  90. }
  91. return _dicTable[lType];
  92. }
  93. private static T GetAttributeByView<T>(Type lType) where T : Attribute
  94. {
  95. object[] aArr = lType.GetCustomAttributes(false);
  96. for (int i = 0; i < aArr.Length; i++)
  97. {
  98. if (typeof(T) == aArr[i].GetType())
  99. return (T)aArr[i];
  100. }
  101. return null;
  102. }
  103. #region 单表查询
  104. public static DataTable SimpleQuery()
  105. {
  106. return SimpleQuery(0, "", "", "");
  107. }
  108. public static DataTable SimpleQuery(string where)
  109. {
  110. return SimpleQuery(0, "", "", where);
  111. }
  112. public static DataTable SimpleQuery(int top, string filter, string orderby, string where)
  113. {
  114. string topRecord = "";
  115. if (top > 0) topRecord = " top " + top;
  116. if (filter == "") filter = "*";
  117. if (orderby != "") orderby = " order by " + orderby;
  118. if (where != "") where = " where " + where;
  119. string sql = string.Format("select {4} {0} from {1} {2} {3}", filter, GetName(), where, orderby, topRecord);
  120. WirteLog(sql);
  121. return DbConn.ExecuteDataset(sql).Tables[0];
  122. }
  123. #endregion
  124. public static DataSet MultiQuery(string sql)
  125. {
  126. WirteLog(sql);
  127. return DbConn.ExecuteDataset(sql);
  128. }
  129. #region 视图查询
  130. /// <summary>
  131. /// 查询
  132. /// </summary>
  133. /// <param name="top">取记录数</param>
  134. /// <param name="filter">字段</param>
  135. /// <param name="orderby">排序</param>
  136. /// <param name="where">条件</param>
  137. /// <returns></returns>
  138. public static DataTable Query(int top, string filter, string orderby, string where)
  139. {
  140. string topRecord = "";
  141. if (top > 0) topRecord = " top " + top;
  142. if (filter == "") filter = "*";
  143. if (orderby != "") orderby = " order by " + orderby;
  144. if (where != "") where = " where " + where;
  145. string sql = string.Format("select {4} {0} from {1} {2} {3}", filter, GetViewName(), where, orderby, topRecord);
  146. WirteLog(sql);
  147. return DbConn.ExecuteDataset(sql).Tables[0];
  148. }
  149. /// <summary>
  150. /// 查询
  151. /// </summary>
  152. /// <param name="top">取记录数</param>
  153. /// <param name="where">条件</param>
  154. /// <returns></returns>
  155. public static DataTable Query(int top, string where)
  156. {
  157. return Query(top, "", "", where);
  158. }
  159. /// <summary>
  160. /// 查询
  161. /// </summary>
  162. /// <param name="topRecord">取几条</param>
  163. /// <returns></returns>
  164. public static DataTable Query(int topRecord)
  165. {
  166. return Query(topRecord, "");
  167. }
  168. /// <summary>
  169. /// 查询
  170. /// </summary>
  171. /// <param name="filter"></param>
  172. /// <param name="orderby"></param>
  173. /// <param name="where"></param>
  174. /// <returns></returns>
  175. public static DataTable Query(string filter, string orderby, string where)
  176. {
  177. return Query(0, filter, orderby, where);
  178. }
  179. /// <summary>
  180. /// 查询
  181. /// </summary>
  182. /// <param name="orderby"></param>
  183. /// <param name="where"></param>
  184. /// <returns></returns>
  185. public static DataTable Query(string orderby, string where)
  186. {
  187. return Query(0, "", orderby, where);
  188. }
  189. /// <summary>
  190. /// 查询
  191. /// </summary>
  192. /// <param name="where">条件</param>
  193. /// <returns></returns>
  194. public static DataTable Query(string where)
  195. {
  196. return Query(0, where);
  197. }
  198. /// <summary>
  199. /// 查询
  200. /// </summary>
  201. /// <returns></returns>
  202. public static DataTable Query()
  203. {
  204. return Query("");
  205. }
  206. #endregion
  207. /// <summary>
  208. /// 事务执行
  209. /// </summary>
  210. /// <param name="sql">多条语句,单条少用</param>
  211. public static void TransExecuteNonQuery(string sql)
  212. {
  213. WirteLog(sql);
  214. using (TransactionScope transaction = new TransactionScope())
  215. {
  216. try
  217. {
  218. ExecuteNonQuery(sql);
  219. transaction.VoteCommit();
  220. }
  221. catch (Exception ex)
  222. {
  223. transaction.VoteRollBack();
  224. throw;
  225. }
  226. }
  227. }
  228. #endregion
  229. public static string CreateCode(string field, string table, string tag)
  230. {
  231. DateTime dt = DateTime.Now;
  232. string prev = dt.ToString("yyMM");
  233. string sql = string.Format("select isnull(max({1}),'') from {2} where {1} like '{0}%'", tag + prev, field, table);
  234. object result = ExecuteScalar(sql);
  235. if (result != null && result.ToString() != "")
  236. {
  237. string tmp = result.ToString();
  238. tmp = tmp.Replace(tag + prev, "");
  239. int num = Convert.ToInt32(tmp) + 1;
  240. return tag + prev + num.ToString().PadLeft(4, '0');
  241. }
  242. else
  243. {
  244. return tag + prev + "0001";
  245. }
  246. }
  247. public static string CreateNoPrevCode(string field, string table, string tag)
  248. {
  249. DateTime dt = DateTime.Now;
  250. string sql = string.Format("select isnull(max({1}),'') from {2} where {1} like '{0}%'", tag, field, table);
  251. object result = ExecuteScalar(sql);
  252. if (result != null && result.ToString() != "")
  253. {
  254. string tmp = result.ToString();
  255. tmp = tmp.Replace(tag, "");
  256. int num = Convert.ToInt32(tmp) + 1;
  257. return tag + num.ToString().PadLeft(5, '0');
  258. }
  259. else
  260. {
  261. return tag + "00001";
  262. }
  263. }
  264. public static string AutoCode(string field, string table, string tag, int len)
  265. {
  266. DateTime dt = DateTime.Now;
  267. string sql = string.Format("select isnull(max({1}),'') from {2} where {1} like '{0}%'", tag, field, table);
  268. object result = ExecuteScalar(sql);
  269. if (result != null && result.ToString() != "")
  270. {
  271. string tmp = result.ToString();
  272. tmp = tmp.Replace(tag, "");
  273. int num = Convert.ToInt32(tmp) + 1;
  274. return tag + num.ToString().PadLeft(len, '0');
  275. }
  276. else
  277. {
  278. return tag + "1".PadLeft(len, '0');
  279. }
  280. }
  281. public static object genCode = new object();
  282. public static string GetGenCode(string tag, string prefix, int len)
  283. {
  284. SqlParameter[] sqlParameter ={
  285. new SqlParameter("@tag", SqlDbType.VarChar,20),
  286. new SqlParameter("@prefix", SqlDbType.VarChar, 20),
  287. new SqlParameter("@codelen", SqlDbType.Int, 4),
  288. new SqlParameter("@otag", SqlDbType.VarChar, 50)};
  289. sqlParameter[0].Value = tag;
  290. sqlParameter[1].Value = prefix;
  291. sqlParameter[2].Value = len;
  292. sqlParameter[3].Direction = ParameterDirection.Output;
  293. lock (genCode)
  294. {
  295. ExecuteNonQueryStore("sp_getgencode", sqlParameter);
  296. return sqlParameter[3].Value.ToString();
  297. }
  298. }
  299. public static object genCode2 = new object();
  300. public static string GetGenCode2(string tag, string prefix, int len)
  301. {
  302. SqlParameter[] sqlParameter ={
  303. new SqlParameter("@tag", SqlDbType.VarChar,20),
  304. new SqlParameter("@prefix", SqlDbType.VarChar, 20),
  305. new SqlParameter("@codelen", SqlDbType.Int, 4),
  306. new SqlParameter("@otag", SqlDbType.VarChar, 50)};
  307. sqlParameter[0].Value = tag;
  308. sqlParameter[1].Value = prefix;
  309. sqlParameter[2].Value = len;
  310. sqlParameter[3].Direction = ParameterDirection.Output;
  311. lock (genCode2)
  312. {
  313. ExecuteNonQueryStore("sp_getgencode2", sqlParameter);
  314. return sqlParameter[3].Value.ToString();
  315. }
  316. }
  317. public static string GetHid(string tag, string prefix)
  318. {
  319. SqlParameter[] sqlParameter ={
  320. new SqlParameter("@compid", SqlDbType.NVarChar,10),
  321. new SqlParameter("@ls_hid", SqlDbType.NVarChar, 10),
  322. new SqlParameter("@indate", SqlDbType.NVarChar, 10),
  323. new SqlParameter("@inupd", SqlDbType.NVarChar, 10),
  324. new SqlParameter("@ls_rhid", SqlDbType.VarChar, 20)};
  325. sqlParameter[0].Value = "01";
  326. sqlParameter[1].Value = tag;
  327. sqlParameter[2].Value = prefix;
  328. sqlParameter[3].Value = "yes";
  329. sqlParameter[4].Direction = ParameterDirection.Output;
  330. ExecuteNonQueryStore("gf_GetHid", sqlParameter);
  331. return sqlParameter[4].Value.ToString();
  332. }
  333. public static T Get(object id)
  334. {
  335. return FindFirst(Expression.Eq("ID", Convert.ToInt32(id)));
  336. }
  337. public static DataSet ExecuteDataset(string sql)
  338. {
  339. WirteLog(sql);
  340. ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
  341. using (NHibernate.ISession session = sessionFactoryHolder.CreateSession(typeof(T)))
  342. {
  343. IDbCommand command = session.Connection.CreateCommand();
  344. command.CommandText = sql;
  345. if (session.Transaction.IsActive) session.Transaction.Enlist(command);
  346. IDbDataAdapter da = new SqlDataAdapter(command as SqlCommand);
  347. DataSet ds = new DataSet();
  348. da.Fill(ds);
  349. return ds;
  350. }
  351. //return command.ExecuteNonQuery();
  352. }
  353. public static int ExecuteNonQuery(string sql)
  354. {
  355. WirteLog(sql);
  356. ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
  357. using (NHibernate.ISession session = sessionFactoryHolder.CreateSession(typeof(T)))
  358. {
  359. IDbCommand command = session.Connection.CreateCommand();
  360. command.CommandText = sql;
  361. if (session.Transaction.IsActive) session.Transaction.Enlist(command);
  362. return command.ExecuteNonQuery();
  363. }
  364. }
  365. public static DataSet ExecuteDataSetStore(string sql, SqlParameter[] paras)
  366. {
  367. WirteLog(sql);
  368. ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
  369. using (NHibernate.ISession session = sessionFactoryHolder.CreateSession(typeof(T)))
  370. {
  371. IDbCommand command = session.Connection.CreateCommand();
  372. command.CommandType = CommandType.StoredProcedure;
  373. if (paras != null)
  374. {
  375. for (int j = 0; j < paras.Length; j++)
  376. {
  377. command.Parameters.Add(paras[j]);
  378. }
  379. }
  380. command.CommandText = sql;
  381. if (session.Transaction.IsActive) session.Transaction.Enlist(command);
  382. IDbDataAdapter da = new SqlDataAdapter(command as SqlCommand);
  383. DataSet ds = new DataSet();
  384. da.Fill(ds);
  385. return ds;
  386. }
  387. }
  388. public static int ExecuteNonQueryStore(string sql, SqlParameter[] paras)
  389. {
  390. WirteLog(sql);
  391. ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
  392. using (NHibernate.ISession session = sessionFactoryHolder.CreateSession(typeof(T)))
  393. {
  394. IDbCommand command = session.Connection.CreateCommand();
  395. command.CommandType = CommandType.StoredProcedure;
  396. //IDataParameterCollection
  397. if (paras != null)
  398. {
  399. for (int j = 0; j < paras.Length; j++)
  400. {
  401. command.Parameters.Add(paras[j]);
  402. }
  403. }
  404. command.CommandText = sql;
  405. if (session.Transaction.IsActive) session.Transaction.Enlist(command);
  406. return command.ExecuteNonQuery();
  407. }
  408. }
  409. public static object ExecuteScalar(string sql)
  410. {
  411. WirteLog(sql);
  412. ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
  413. //NHibernate.ISession session = sessionFactoryHolder.GetSessionFactory(typeof(CeErpInventory)).GetCurrentSession();
  414. //NHibernate.ISession session=sessionFactoryHolder.GetConfiguration(typeof(ActiveRecordBase)).BuildSessionFactory().OpenSession();
  415. using (NHibernate.ISession session = sessionFactoryHolder.CreateSession(typeof(T)))
  416. {
  417. IDbCommand command = session.Connection.CreateCommand();
  418. command.CommandText = sql;
  419. if (session.Transaction.IsActive) session.Transaction.Enlist(command);
  420. return command.ExecuteScalar();
  421. }
  422. }
  423. static log4net.ILog logger = log4net.LogManager.GetLogger("ComBase");//获取一个日志记录器
  424. private static void WirteLog(string text)
  425. {
  426. logger.Info(text);
  427. }
  428. }
  429. }