supplierBuildFile.aspx.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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,SupplierId 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> supplierIds = new List<string>();
  108. List<string> tids = new List<string>();
  109. int upStatus = 3;
  110. string url = "";
  111. if (itemData != null && itemData.Rows.Count > 0)
  112. {
  113. foreach (DataRow row in itemData.Rows)
  114. {
  115. string finishDesignTime = getDesignTime(row["FinishDesignTime"]);
  116. string ctid = row["ctid"].ToString();
  117. string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(row["seller_memo"]);
  118. string ext = getCanDownFile(df_name);
  119. if (string.IsNullOrEmpty(ext))
  120. {
  121. //不存在则打包失败
  122. updateSql += string.Format("update CE_ErpPackDataItem set message = '文件不存在!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  123. files = new List<string>();
  124. supplierIds = new List<string>();
  125. break;
  126. }
  127. string fname = df_name + ext;
  128. if (Convert.ToInt16(row["OrderState"]) != 6)
  129. {
  130. updateSql += string.Format("update CE_ErpPackDataItem set message = '订单状态不正确!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  131. continue;
  132. }
  133. int IsFileEncrypt = IsFileEncrypted(fname);
  134. if (IsFileEncrypt == 1 && File.Exists(fname))
  135. {
  136. string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
  137. var sb = new StringBuilder(key);
  138. //Linux系统的接口要调用一次,Windows系统要调用两次
  139. CreateUserKey(sb, key.Length);
  140. CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
  141. int result = InitAesKey(sb, sb.Length);
  142. result = IsInitedAesKey();
  143. if (result != 1)
  144. {
  145. addLog(ctid, userId, "初始化秘钥失败" + result, 0);
  146. updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  147. continue;
  148. }
  149. uint a = DecFile(fname);
  150. if (a != 0)
  151. {
  152. addLog(ctid, userId, "解密失败" + a, 0);
  153. updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  154. continue;
  155. }
  156. }
  157. if (string.IsNullOrEmpty(fname))
  158. {
  159. updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  160. continue;
  161. }
  162. try
  163. {
  164. copyFile(getDesignDate(row["FinishDesignTime"]), row["SupplierName"].ToString(), fname);
  165. files.Add(fname);
  166. supplierIds.Add(row["SupplierId"].ToString());
  167. tids.Add("'" + ctid + "'");
  168. }
  169. catch (Exception ex)
  170. {
  171. writeLog("打包复制文件出错!" + ex.Message);
  172. updateSql += string.Format("update CE_ErpPackDataItem set message = '复制文件出错!{2}' where packId= {0} and ctid='{1}' ;", packId, ctid, ex.Message);
  173. files = new List<string>();//清空数据
  174. supplierIds = new List<string>();
  175. break;
  176. }
  177. }
  178. if (files.Count == 0)
  179. {
  180. updateSql += string.Format("update CE_ErpPackData set upStatus = 3,message='没有可打包文件!' where ID= {0} ;", packId);
  181. continue;
  182. }
  183. else
  184. {
  185. MemoryStream ms = new MemoryStream();
  186. byte[] buffer = null;
  187. using (ZipFile file = ZipFile.Create(ms))
  188. {
  189. file.BeginUpdate();
  190. //file.NameTransform = new ZipNameTransform();
  191. file.NameTransform = new MyNameTransfom();
  192. for (int i = 0; i < files.Count; i++)
  193. {
  194. if (File.Exists(files[i]))
  195. {
  196. try
  197. {
  198. string fname = Path.GetFileName(files[i]);
  199. if ("14".Equals(supplierIds[i]))
  200. {
  201. fname = dealMemoName(fname);
  202. }
  203. file.Add(files[i], fname);
  204. }
  205. catch (Exception ex)
  206. {
  207. }
  208. }
  209. }
  210. file.CommitUpdate();
  211. buffer = new byte[ms.Length];
  212. ms.Position = 0;
  213. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  214. ms.Flush();
  215. ms.Close();
  216. }
  217. url = FileOssUp(buffer, dr["fileName"].ToString());
  218. if (url != null)
  219. {
  220. upStatus = 2;
  221. 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, "下载设计文件");
  222. updateSql += string.Format("update ce_erptradecell set UpdateTime=getdate() where ctid in ({0}) ;", string.Join(",", tids));
  223. }
  224. }
  225. }
  226. updateSql += string.Format("update CE_ErpPackData set upStatus = {1},fileUrl='{2}' where ID= {0} ;", packId, upStatus, url);
  227. }
  228. catch (Exception ex)
  229. {
  230. writeLog("打包文件出错!" + ex.Message);
  231. updateSql += string.Format("update CE_ErpPackData set upStatus = 3 where ID= {0} ;", packId);
  232. }
  233. CeErpTradeLog.ExecuteNonQuery(updateSql);
  234. updateSql = "";
  235. }
  236. }
  237. running = false;
  238. }
  239. });
  240. conSuc("运行结束!");
  241. //FileOssUp();
  242. }
  243. private string dealMemoName(string name)
  244. {
  245. string[] al = name.Split('-');
  246. List<string> list = new List<string>();
  247. string pa = string.Empty;
  248. for (int i = 0; i < al.Length; i++)
  249. {
  250. if (i == 1)
  251. {
  252. if (al[i].Contains("(") || al[i].Contains("("))
  253. {
  254. string tname = al[i].Replace(")", "").Replace(")", "").Replace("(", "").Replace("(", "");
  255. if (!string.IsNullOrEmpty(tname))
  256. {
  257. pa = al[i];
  258. }
  259. continue;
  260. }
  261. }
  262. list.Add(al[i]);
  263. }
  264. if (!string.IsNullOrEmpty(pa))
  265. {
  266. list.Insert(3, pa);
  267. }
  268. name = string.Join("-", list);
  269. return name;
  270. }
  271. private string formatMemo(object memo)
  272. {
  273. string m = memo.ToString();
  274. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  275. return m;
  276. }
  277. private void copyFile(string date, string supplier, string file)
  278. {
  279. string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
  280. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  281. string fname = Path.GetFileName(file);
  282. File.Copy(file, path + "\\" + fname, true);
  283. if (!File.Exists(path + "\\" + fname))
  284. {
  285. File.Copy(file, path + "\\" + fname, true);
  286. }
  287. }
  288. private string getDesignTime(object v)
  289. {
  290. if (v.ToString() == "") return "";
  291. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  292. }
  293. private string getDesignDate(object v)
  294. {
  295. return DateTime.Now.ToString("yyyy-MM-dd");
  296. /*if (v.ToString() == "") return "";
  297. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
  298. }
  299. private string FileOssUp(byte[] buffer, string fileName)
  300. {
  301. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  302. var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
  303. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  304. var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
  305. var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
  306. // 填写Bucket名称,例如examplebucket。
  307. var bucketName = "ltcloudfile";
  308. int year = DateTime.Now.Year;
  309. int month = DateTime.Now.Month;
  310. int day = DateTime.Now.Day;
  311. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
  312. var objectName = "supplierFile/" + year + "/" + month + "/" + day + "/" + fileName;
  313. // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
  314. string region = "cn-hangzhou";
  315. // 创建ClientConfiguration实例,按照您的需要修改默认参数。
  316. var conf = new ClientConfiguration();
  317. // 设置v4签名。
  318. conf.SignatureVersion = SignatureVersion.V4;
  319. // 创建OssClient实例。
  320. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
  321. client.SetRegion(region);
  322. try
  323. {
  324. MemoryStream requestContent = new MemoryStream(buffer);
  325. // 上传文件。
  326. client.PutObject(bucketName, objectName, requestContent);
  327. }
  328. catch (Exception ex)
  329. {
  330. writeLog("打包文件上传oss出错!" + ex.Message);
  331. return null;
  332. }
  333. return "https://ltcloudfile.oss-cn-hangzhou.aliyuncs.com/" + objectName;
  334. }
  335. /// 批量进行多个文件压缩到一个文件
  336. /// </summary>
  337. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  338. /// <param name="zipFileName">生成的zip文件名称</param>
  339. private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient)
  340. {
  341. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  342. var endpoint = "https://oss-cn-fuzhou.aliyuncs.com";
  343. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  344. var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
  345. var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
  346. // 填写Bucket名称,例如examplebucket。
  347. var bucketName = "dfdiyfile";
  348. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
  349. var objectName = "exampledir/exampleobject.txt";
  350. // 填写字符串。
  351. var objectContent = "More than just cloud.";
  352. // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
  353. const string region = "oss-cn-fuzhou";
  354. // 创建ClientConfiguration实例,按照您的需要修改默认参数。
  355. var conf = new ClientConfiguration();
  356. // 设置v4签名。
  357. conf.SignatureVersion = SignatureVersion.V4;
  358. // 创建OssClient实例。
  359. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
  360. client.SetRegion(region);
  361. try
  362. {
  363. MemoryStream ms = new MemoryStream();
  364. byte[] buffer = null;
  365. using (ZipFile file = ZipFile.Create(ms))
  366. {
  367. file.BeginUpdate();
  368. //file.NameTransform = new ZipNameTransform();
  369. file.NameTransform = new MyNameTransfom();
  370. file.Add("C:\\Users\\231010\\Downloads\\setup.exe");
  371. file.CommitUpdate();
  372. buffer = new byte[ms.Length];
  373. ms.Position = 0;
  374. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  375. ms.Flush();
  376. ms.Close();
  377. }
  378. MemoryStream requestContent = new MemoryStream(buffer);
  379. // 上传文件。
  380. client.PutObject(bucketName, objectName, requestContent);
  381. Console.WriteLine("Put object succeeded");
  382. }
  383. catch (Exception ex)
  384. {
  385. Console.WriteLine("Put object failed, {0}", ex.Message);
  386. }
  387. conSuc("上传成功!");
  388. return;
  389. //for (int i = 0; i < addFiles.Count; i++)
  390. //{
  391. // updateIsDownSuccess(userId, addCtid[i]);
  392. //}
  393. //StringBuilder sql = new StringBuilder();
  394. //string tids = string.Join(",", addCtid);
  395. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  396. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  397. //sql = new StringBuilder();
  398. //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, "下载设计文件");
  399. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  400. }
  401. //public static object downfileObj = new object();
  402. private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
  403. {
  404. string filePath = file;
  405. string dfile = Path.GetFileName(file);
  406. FileStream fs = new FileStream(filePath, FileMode.Open);
  407. byte[] bytes = new byte[(int)fs.Length];
  408. fs.Read(bytes, 0, bytes.Length);
  409. fs.Close();
  410. Response.Clear();
  411. //
  412. Response.ClearContent();
  413. Response.ClearHeaders();
  414. Response.ContentType = "application/octet-stream";
  415. //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
  416. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
  417. //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  418. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
  419. Response.AddHeader("Content-Length", bytes.Length.ToString());
  420. Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
  421. Response.BinaryWrite(bytes);
  422. Response.Flush();
  423. //updateIsDownSuccess(userId, ctid);
  424. //StringBuilder sql = new StringBuilder();
  425. //string tids = string.Join(",", ctid);
  426. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  427. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  428. //sql = new StringBuilder();
  429. //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, "下载设计文件");
  430. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  431. }
  432. public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
  433. {
  434. CeErpTradeLog log = new CeErpTradeLog();
  435. log.tid = ctid;
  436. log.UserId = userid;
  437. log.Con = con;
  438. log.OrderState = orderState;
  439. log.AfterSaleState = aftersaleState;
  440. log.OperateTime = DateTime.Now;
  441. log.Create();
  442. }
  443. private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
  444. private static object logFlag = new object();
  445. public static void writeLog(string log)
  446. {
  447. lock (logFlag)
  448. {
  449. using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
  450. {
  451. using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
  452. {
  453. sw.Write(log + " ------时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
  454. sw.Flush();
  455. }
  456. }
  457. }
  458. }
  459. }