supplierBuildFile.aspx.cs 23 KB

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