supplierBuildFile.aspx.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using Aliyun.OSS;
  2. using Aliyun.OSS.Common;
  3. using Aspose.Imaging.FileFormats.Tiff.FileManagement;
  4. using BizCom;
  5. using ICSharpCode.SharpZipLib.Zip;
  6. using MSharp.Framework;
  7. using NPOI.OpenXmlFormats.Dml.Diagram;
  8. using NPOI.OpenXmlFormats.Shared;
  9. using NPOI.POIFS.Properties;
  10. using SiteCore.Handler;
  11. using SiteCore.Redis;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Configuration;
  15. using System.Data;
  16. using System.Data.SqlClient;
  17. using System.Diagnostics;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Net;
  21. using System.Runtime.InteropServices;
  22. using System.Security.Principal;
  23. using System.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using System.Web;
  27. using System.Web.Services.Description;
  28. using System.Web.UI;
  29. public partial class supplierBuildFile : System.Web.UI.Page
  30. {
  31. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  32. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  33. public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
  34. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  35. public static extern uint DecFile(string filename);
  36. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  37. public static extern int IsFileEncrypted(string filename);//返回1为加密,0为未被加密
  38. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  39. public static extern void CreateUserKey(StringBuilder key, int len);
  40. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  41. public static extern int InitAesKey(StringBuilder key, int len);
  42. [DllImport("DrvInterface64.dll")]
  43. public static extern int IsInitedAesKey();
  44. private void conErc(string msg)
  45. {
  46. XLog.SaveLog(0, msg);
  47. Response.Write(msg);
  48. //Response.StatusCode = (int)HttpStatusCode.NotFound;
  49. //Response.End();
  50. }
  51. private void conSuc(string msg)
  52. {
  53. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  54. //Response.End();
  55. }
  56. protected void Page_Load(object sender, EventArgs e)
  57. {
  58. if (!IsPostBack)
  59. {
  60. Response.Buffer = true;
  61. downloadMore();
  62. }
  63. }
  64. private string getCanDownFile(string fileName)
  65. {
  66. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  67. foreach (string ext in extArr)
  68. {
  69. string fname = fileName + ext;
  70. if (File.Exists(fname))
  71. {
  72. return ext;
  73. }
  74. }
  75. return "";
  76. }
  77. static bool running = false;
  78. private void downloadMore()
  79. {
  80. if (running)
  81. {
  82. conSuc("运行中!");
  83. return;
  84. }
  85. running = true;
  86. var identity = WindowsIdentity.GetCurrent();
  87. var principal = new WindowsPrincipal(identity);
  88. Task.Run(async () =>
  89. {
  90. using (identity.Impersonate())
  91. {
  92. StringBuilder sql = new StringBuilder();
  93. sql.AppendFormat("select * from CE_ErpPackData WITH(nolock) where upStatus = 0");
  94. int userId = 1;
  95. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  96. string updateSql = "";
  97. if (dt != null && dt.Rows.Count > 0)
  98. {
  99. foreach (DataRow dr in dt.Rows)
  100. {
  101. string packId = dr["ID"].ToString();
  102. try
  103. {
  104. CeErpTradeLog.ExecuteNonQuery(string.Format("update CE_ErpPackData set upStatus = 1 where ID= {0} ;", packId));
  105. DataTable itemData = CeErpTradeCell.ExecuteDataset(string.Format("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,OrderSn,tid from view_erptradecell where FinishDesignTime is not null and ctid in (SELECT ctid FROM CE_ErpPackDataItem WHERE packId = {0})", packId)).Tables[0];
  106. List<string> files = new List<string>();
  107. List<string> tids = new List<string>();
  108. int upStatus = 3;
  109. string url = "";
  110. if (itemData != null && itemData.Rows.Count > 0)
  111. {
  112. foreach (DataRow row in itemData.Rows)
  113. {
  114. string finishDesignTime = getDesignTime(row["FinishDesignTime"]);
  115. string ctid = row["ctid"].ToString();
  116. string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(row["seller_memo"]);
  117. string ext = getCanDownFile(df_name);
  118. if (string.IsNullOrEmpty(ext))
  119. {
  120. //不存在则打包失败
  121. updateSql += string.Format("update CE_ErpPackDataItem set message = '文件不存在!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  122. files = new List<string>();
  123. break;
  124. }
  125. string fname = df_name + ext;
  126. if (Convert.ToInt16(row["OrderState"]) != 6)
  127. {
  128. updateSql += string.Format("update CE_ErpPackDataItem set message = '订单状态不正确!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  129. continue;
  130. }
  131. int IsFileEncrypt = IsFileEncrypted(fname);
  132. if (IsFileEncrypt == 1 && File.Exists(fname))
  133. {
  134. string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
  135. var sb = new StringBuilder(key);
  136. //Linux系统的接口要调用一次,Windows系统要调用两次
  137. CreateUserKey(sb, key.Length);
  138. CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
  139. int result = InitAesKey(sb, sb.Length);
  140. result = IsInitedAesKey();
  141. if (result != 1)
  142. {
  143. addLog(ctid, userId, "初始化秘钥失败" + result, 0);
  144. continue;
  145. }
  146. uint a = DecFile(fname);
  147. if (a != 0)
  148. {
  149. addLog(ctid, userId, "解密失败" + a, 0);
  150. continue;
  151. }
  152. }
  153. if (string.IsNullOrEmpty(fname))
  154. {
  155. continue;
  156. }
  157. try
  158. {
  159. copyFile(getDesignDate(row["FinishDesignTime"]), row["SupplierName"].ToString(), fname);
  160. files.Add(fname);
  161. tids.Add("'" + ctid + "'");
  162. }
  163. catch (Exception ex)
  164. {
  165. writeLog("打包复制文件出错!" + ex.Message);
  166. updateSql += string.Format("update CE_ErpPackDataItem set message = '复制文件出错!{2}' where packId= {0} and ctid='{1}' ;", packId, ctid, ex.Message);
  167. files = new List<string>();//清空数据
  168. break;
  169. }
  170. }
  171. if (files.Count == 0)
  172. {
  173. updateSql += string.Format("update CE_ErpPackData set upStatus = 3,message='没有可打包文件!' where ID= {0} ;", packId);
  174. continue;
  175. }
  176. else
  177. {
  178. MemoryStream ms = new MemoryStream();
  179. byte[] buffer = null;
  180. using (ZipFile file = ZipFile.Create(ms))
  181. {
  182. file.BeginUpdate();
  183. //file.NameTransform = new ZipNameTransform();
  184. file.NameTransform = new MyNameTransfom();
  185. for (int i = 0; i < files.Count; i++)
  186. {
  187. if (File.Exists(files[i]))
  188. {
  189. try
  190. {
  191. file.Add(files[i]);
  192. }
  193. catch (Exception ex)
  194. {
  195. }
  196. }
  197. }
  198. file.CommitUpdate();
  199. buffer = new byte[ms.Length];
  200. ms.Position = 0;
  201. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  202. ms.Flush();
  203. ms.Close();
  204. }
  205. url = FileOssUp(buffer, dr["fileName"].ToString());
  206. if (url != null)
  207. {
  208. upStatus = 2;
  209. updateSql += string.Format("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", string.Join(",", tids), (int)OrderState.下单完成, 0, "下载设计文件");
  210. updateSql += string.Format("update ce_erptradecell set UpdateTime=getdate() where ctid in ({0}) ;", string.Join(",", tids));
  211. }
  212. }
  213. }
  214. updateSql += string.Format("update CE_ErpPackData set upStatus = {1},fileUrl='{2}' where ID= {0} ;", packId, upStatus, url);
  215. }
  216. catch (Exception ex)
  217. {
  218. writeLog("打包文件出错!" + ex.Message);
  219. updateSql += string.Format("update CE_ErpPackData set upStatus = 3 where ID= {0} ;", packId);
  220. }
  221. }
  222. CeErpTradeLog.ExecuteNonQuery(updateSql);
  223. }
  224. running = false;
  225. }
  226. });
  227. conSuc("运行结束!");
  228. //FileOssUp();
  229. }
  230. private string formatMemo(object memo)
  231. {
  232. string m = memo.ToString();
  233. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  234. return m;
  235. }
  236. private void copyFile(string date, string supplier, string file)
  237. {
  238. string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
  239. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  240. string fname = Path.GetFileName(file);
  241. File.Copy(file, path + "\\" + fname, true);
  242. if (!File.Exists(path + "\\" + fname))
  243. {
  244. File.Copy(file, path + "\\" + fname, true);
  245. }
  246. }
  247. private string getDesignTime(object v)
  248. {
  249. if (v.ToString() == "") return "";
  250. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  251. }
  252. private string getDesignDate(object v)
  253. {
  254. return DateTime.Now.ToString("yyyy-MM-dd");
  255. /*if (v.ToString() == "") return "";
  256. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
  257. }
  258. private string FileOssUp(byte[] buffer, string fileName)
  259. {
  260. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  261. var endpoint = "https://oss-cn-fuzhou.aliyuncs.com";
  262. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  263. var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
  264. var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
  265. // 填写Bucket名称,例如examplebucket。
  266. var bucketName = "dfdiyfile";
  267. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
  268. var objectName = "supplierFile/" + fileName;
  269. // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
  270. string region = "cn-fuzhou";
  271. // 创建ClientConfiguration实例,按照您的需要修改默认参数。
  272. var conf = new ClientConfiguration();
  273. // 设置v4签名。
  274. conf.SignatureVersion = SignatureVersion.V4;
  275. // 创建OssClient实例。
  276. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
  277. client.SetRegion(region);
  278. try
  279. {
  280. MemoryStream requestContent = new MemoryStream(buffer);
  281. // 上传文件。
  282. client.PutObject(bucketName, objectName, requestContent);
  283. }
  284. catch (Exception ex)
  285. {
  286. writeLog("打包文件上传oss出错!" + ex.Message);
  287. return null;
  288. }
  289. return "https://dfdiyfile.oss-cn-fuzhou.aliyuncs.com/" + objectName;
  290. }
  291. /// 批量进行多个文件压缩到一个文件
  292. /// </summary>
  293. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  294. /// <param name="zipFileName">生成的zip文件名称</param>
  295. private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient)
  296. {
  297. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  298. var endpoint = "https://oss-cn-fuzhou.aliyuncs.com";
  299. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  300. var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
  301. var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
  302. // 填写Bucket名称,例如examplebucket。
  303. var bucketName = "dfdiyfile";
  304. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
  305. var objectName = "exampledir/exampleobject.txt";
  306. // 填写字符串。
  307. var objectContent = "More than just cloud.";
  308. // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
  309. const string region = "oss-cn-fuzhou";
  310. // 创建ClientConfiguration实例,按照您的需要修改默认参数。
  311. var conf = new ClientConfiguration();
  312. // 设置v4签名。
  313. conf.SignatureVersion = SignatureVersion.V4;
  314. // 创建OssClient实例。
  315. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
  316. client.SetRegion(region);
  317. try
  318. {
  319. MemoryStream ms = new MemoryStream();
  320. byte[] buffer = null;
  321. using (ZipFile file = ZipFile.Create(ms))
  322. {
  323. file.BeginUpdate();
  324. //file.NameTransform = new ZipNameTransform();
  325. file.NameTransform = new MyNameTransfom();
  326. file.Add("C:\\Users\\231010\\Downloads\\setup.exe");
  327. file.CommitUpdate();
  328. buffer = new byte[ms.Length];
  329. ms.Position = 0;
  330. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  331. ms.Flush();
  332. ms.Close();
  333. }
  334. MemoryStream requestContent = new MemoryStream(buffer);
  335. // 上传文件。
  336. client.PutObject(bucketName, objectName, requestContent);
  337. Console.WriteLine("Put object succeeded");
  338. }
  339. catch (Exception ex)
  340. {
  341. Console.WriteLine("Put object failed, {0}", ex.Message);
  342. }
  343. conSuc("上传成功!");
  344. return;
  345. //for (int i = 0; i < addFiles.Count; i++)
  346. //{
  347. // updateIsDownSuccess(userId, addCtid[i]);
  348. //}
  349. //StringBuilder sql = new StringBuilder();
  350. //string tids = string.Join(",", addCtid);
  351. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  352. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  353. //sql = new StringBuilder();
  354. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
  355. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  356. }
  357. //public static object downfileObj = new object();
  358. private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
  359. {
  360. string filePath = file;
  361. string dfile = Path.GetFileName(file);
  362. FileStream fs = new FileStream(filePath, FileMode.Open);
  363. byte[] bytes = new byte[(int)fs.Length];
  364. fs.Read(bytes, 0, bytes.Length);
  365. fs.Close();
  366. Response.Clear();
  367. //
  368. Response.ClearContent();
  369. Response.ClearHeaders();
  370. Response.ContentType = "application/octet-stream";
  371. //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
  372. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
  373. //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  374. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
  375. Response.AddHeader("Content-Length", bytes.Length.ToString());
  376. Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
  377. Response.BinaryWrite(bytes);
  378. Response.Flush();
  379. //updateIsDownSuccess(userId, ctid);
  380. //StringBuilder sql = new StringBuilder();
  381. //string tids = string.Join(",", ctid);
  382. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  383. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  384. //sql = new StringBuilder();
  385. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
  386. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  387. }
  388. public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
  389. {
  390. CeErpTradeLog log = new CeErpTradeLog();
  391. log.tid = ctid;
  392. log.UserId = userid;
  393. log.Con = con;
  394. log.OrderState = orderState;
  395. log.AfterSaleState = aftersaleState;
  396. log.OperateTime = DateTime.Now;
  397. log.Create();
  398. }
  399. private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
  400. private static object logFlag = new object();
  401. public static void writeLog(string log)
  402. {
  403. lock (logFlag)
  404. {
  405. using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
  406. {
  407. using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
  408. {
  409. sw.Write(log + " ------时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
  410. sw.Flush();
  411. }
  412. }
  413. }
  414. }
  415. }