supplierBuildFile.aspx.cs 20 KB

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