RecipeFileManager.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. using Aitex.Common.Util;
  2. using Aitex.Core.RT.Event;
  3. using Aitex.Core.RT.Log;
  4. using Aitex.Core.Util;
  5. using Aitex.Core.Utilities;
  6. using Aitex.Core.WCF;
  7. using MECF.Framework.Common.Properties;
  8. using MECF.Framework.Common.RecipeCenter;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Xml;
  15. using System.Xml.Schema;
  16. using Venus_Core;
  17. namespace Aitex.Core.RT.RecipeCenter
  18. {
  19. public class RecipeFileManager : Singleton<RecipeFileManager>
  20. {
  21. //sequence文件 统一放在 Recipes/Sequence 文件夹下面
  22. public const string SequenceFolder = "Sequence";
  23. public const string SourceModule = "Recipe";
  24. private bool _recipeIsValid;
  25. private List<string> _validationErrors = new List<string>();
  26. private List<string> _validationWarnings = new List<string>();
  27. IRecipeFileContext _rcpContext;
  28. private ISequenceFileContext _seqContext;
  29. public void Initialize(IRecipeFileContext context)
  30. {
  31. Initialize(context, null, true);
  32. }
  33. public void Initialize(IRecipeFileContext context, bool enableService)
  34. {
  35. Initialize(context, null, enableService);
  36. }
  37. public void Initialize(IRecipeFileContext rcpContext, ISequenceFileContext seqContext, bool enableService)
  38. {
  39. _rcpContext = rcpContext == null ? new DefaultRecipeFileContext() : rcpContext;
  40. _seqContext = seqContext == null ? new DefaultSequenceFileContext() : seqContext;
  41. CultureSupported.UpdateCoreCultureResource(CultureSupported.English);
  42. //if (enableService)
  43. //{
  44. // Singleton<WcfServiceManager>.Instance.Initialize(new Type[]
  45. // {
  46. // typeof(RecipeService)
  47. // });
  48. //}
  49. var dir = string.Format("{0}{1}\\", PathManager.GetRecipeDir(), SequenceFolder);
  50. DirectoryInfo di = new DirectoryInfo(dir);
  51. if (!di.Exists)
  52. {
  53. di.Create();
  54. }
  55. }
  56. private void ValidationEventHandler(object sender, ValidationEventArgs e)
  57. {
  58. switch (e.Severity)
  59. {
  60. case XmlSeverityType.Error:
  61. _validationErrors.Add(e.Message);
  62. _recipeIsValid = false;
  63. break;
  64. case XmlSeverityType.Warning:
  65. _validationWarnings.Add(e.Message);
  66. break;
  67. }
  68. }
  69. /// <summary>
  70. /// XML schema checking
  71. /// </summary>
  72. /// <param name="chamId"></param>
  73. /// <param name="recipeName"></param>
  74. /// <param name="recipeContent"></param>
  75. /// <param name="reason"></param>
  76. /// <returns></returns>
  77. public bool ValidateRecipe(string chamberId, string recipeName, string recipeContent, out List<string> reason)
  78. {
  79. try
  80. {
  81. XmlDocument document = new XmlDocument();
  82. document.LoadXml(recipeContent);
  83. MemoryStream schemaStream = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(GetRecipeSchema(chamberId)));
  84. XmlReader xmlSchemaReader = XmlReader.Create(schemaStream);
  85. XmlSchema schema1 = XmlSchema.Read(xmlSchemaReader, ValidationEventHandler);
  86. document.Schemas.Add(schema1);
  87. document.LoadXml(recipeContent);
  88. ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
  89. _recipeIsValid = true;
  90. _validationErrors = new List<string>();
  91. _validationWarnings = new List<string>();
  92. // Validates recipe.
  93. document.Validate(eventHandler);
  94. }
  95. catch (Exception ex)
  96. {
  97. //LOG.Write(ex.Message);
  98. _recipeIsValid = false;
  99. }
  100. if (!_recipeIsValid && _validationErrors.Count == 0)
  101. {
  102. _validationErrors.Add(Resources.RecipeFileManager_ValidateRecipe_XMLSchemaValidateFailed);
  103. }
  104. reason = _validationErrors;
  105. return _recipeIsValid;
  106. }
  107. /// <summary>
  108. /// Check recipe content
  109. /// </summary>
  110. /// <param name="chamId"></param>
  111. /// <param name="recipeContent"></param>
  112. /// <param name="reasons"></param>
  113. /// <returns></returns>
  114. public bool CheckRecipe(string chamberId, string recipeContent, out List<string> reasons)
  115. {
  116. reasons = new List<string>();
  117. //add recipe content validation here
  118. try
  119. {
  120. var xmlFormat = new XmlDocument();
  121. xmlFormat.LoadXml(GetRecipeFormatXml(chamberId));
  122. var mfcDic = new Dictionary<string, double>(); //name + scale
  123. var pcDic = new Dictionary<string, double>(); //name + scale
  124. foreach (XmlElement mfc in xmlFormat.SelectNodes("/TableRecipeFormat/Catalog/Group/Step[@DeviceType='MFC']"))
  125. {
  126. mfcDic.Add(mfc.Attributes["ControlName"].Value, Convert.ToDouble(mfc.Attributes["Max"].Value));
  127. }
  128. foreach (XmlElement pc in xmlFormat.SelectNodes("/TableRecipeFormat/Catalog/Group/Step[@DeviceType='PC']"))
  129. {
  130. pcDic.Add(pc.Attributes["ControlName"].Value, Convert.ToDouble(pc.Attributes["Max"].Value));
  131. }
  132. //var spindleMaxSpeed = Convert.ToDouble(xmlFormat.SelectSingleNode("/TableRecipeFormat/Catalog/Group/Step[@ControlName='Spindle.Speed']").Attributes["Max"].Value);
  133. var xmlRecipe = new XmlDocument();
  134. xmlRecipe.LoadXml(recipeContent);
  135. //read in all recipe items
  136. Dictionary<int, Dictionary<string, string>> recipeItems = new Dictionary<int, Dictionary<string, string>>();
  137. var stepElements = xmlRecipe.SelectNodes("/TableRecipeData/Step");
  138. for (int stepNo = 0; stepNo < stepElements.Count; stepNo++)
  139. {
  140. var stepElement = stepElements[stepNo] as XmlElement;
  141. var step = new Dictionary<string, string>();
  142. recipeItems.Add(stepNo, step);
  143. foreach (XmlAttribute att1 in stepElement.Attributes)
  144. {
  145. step.Add(att1.Name, att1.Value);
  146. }
  147. foreach (XmlElement subNd1 in stepElement.ChildNodes)
  148. {
  149. foreach (XmlAttribute att2 in subNd1.Attributes)
  150. {
  151. step.Add(att2.Name, att2.Value);
  152. }
  153. foreach (XmlElement subNd2 in subNd1.ChildNodes)
  154. {
  155. foreach (XmlAttribute att3 in subNd2.Attributes)
  156. {
  157. step.Add(att3.Name, att3.Value);
  158. }
  159. foreach (XmlElement subNd3 in subNd2.ChildNodes)
  160. {
  161. foreach (XmlAttribute att4 in subNd3.Attributes)
  162. {
  163. step.Add(att4.Name, att4.Value);
  164. }
  165. }
  166. }
  167. }
  168. }
  169. #region check loop control
  170. for (int j = 0; j < recipeItems.Count; j++)
  171. {
  172. var loopStr = recipeItems[j]["Loop"];
  173. bool isLoopStart = Regex.IsMatch(loopStr, @"^Loop\x20\d+$");
  174. bool isLoopEnd = Regex.IsMatch(loopStr, @"^Loop End$");
  175. bool isNullOrEmpty = string.IsNullOrWhiteSpace(loopStr);
  176. if (!isLoopEnd && !isLoopStart && !isNullOrEmpty)
  177. {
  178. string reason = string.Format("Value '{0}' not valid", loopStr);
  179. reasons.Add(string.Format("第{0}步,{1}。", j + 1, reason));
  180. }
  181. if (isLoopEnd)
  182. {
  183. string reason = "Loop Start 缺失";
  184. reasons.Add(string.Format("第{0}步,{1}。", j + 1, reason));
  185. }
  186. else if (isLoopStart)
  187. {
  188. for (int k = j + 1; k < recipeItems.Count; k++)
  189. {
  190. var loopStr2 = recipeItems[k]["Loop"];
  191. bool isCurStepLoopStart = Regex.IsMatch(loopStr2, @"^Loop\x20\d+$");
  192. bool isCurStepLoopEnd = Regex.IsMatch(loopStr2, @"^Loop End$");
  193. isNullOrEmpty = string.IsNullOrWhiteSpace(loopStr2);
  194. if (!isCurStepLoopEnd && !isCurStepLoopStart && !isNullOrEmpty)
  195. {
  196. string reason = string.Format("Value '{0}' not valid", loopStr2);
  197. reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));
  198. }
  199. else if (isCurStepLoopStart)
  200. {
  201. string reason = "前面循环没有结束,不能设置新的Loop Start标志";
  202. reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));
  203. }
  204. else if (isCurStepLoopEnd)
  205. {
  206. j = k;
  207. break;
  208. }
  209. if (k == recipeItems.Count - 1)
  210. {
  211. j = k;
  212. string reason = "Loop End 缺失";
  213. reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));
  214. }
  215. }
  216. }
  217. }
  218. #endregion
  219. //check mfc range
  220. for (int stepNo = 0; stepNo < recipeItems.Count; stepNo++)
  221. {
  222. foreach (var mfcName in mfcDic.Keys)
  223. {
  224. if (recipeItems[stepNo].ContainsKey(mfcName))
  225. {
  226. var mfcSetpoint = Convert.ToDouble(recipeItems[stepNo][mfcName]);
  227. if (mfcSetpoint < 0 || mfcSetpoint > mfcDic[mfcName])
  228. {
  229. reasons.Add(string.Format("第{0}步,{1}设定{2},超出 0~{3}sccm范围。", stepNo + 1, mfcName, mfcSetpoint, mfcDic[mfcName]));
  230. }
  231. }
  232. }
  233. //check pc range
  234. foreach (var pcName in pcDic.Keys)
  235. {
  236. if (recipeItems[stepNo].ContainsKey(pcName))
  237. {
  238. var pcSetpoint = Convert.ToDouble(recipeItems[stepNo][pcName]);
  239. if (pcSetpoint < 0 || pcSetpoint > pcDic[pcName])
  240. {
  241. reasons.Add(string.Format("第{0}步,{1}设定{2},超出 0~{3}mbar范围。", stepNo + 1, pcName, pcSetpoint, pcDic[pcName]));
  242. }
  243. }
  244. }
  245. }
  246. #region recipe parameter validation
  247. //reading predefined varaible
  248. var recipePredfine = new Dictionary<string, string>();
  249. foreach (XmlElement nd in xmlFormat.SelectNodes("/TableRecipeFormat/Validation/Predefine/Item"))
  250. {
  251. recipePredfine.Add(nd.Attributes["VarName"].Value, nd.Attributes["Value"].Value);
  252. }
  253. #endregion
  254. }
  255. catch (Exception ex)
  256. {
  257. reasons.Add(Resources.RecipeFileManager_CheckRecipe_RecipeValidationFailed + ex.Message);
  258. //LOG.Write(ex);
  259. return false;
  260. }
  261. return reasons.Count == 0;
  262. }
  263. /// <summary>
  264. /// This method will be invoked by two places:
  265. /// (1) Load a recipe from server to GUI for editing (do not need validation when loading, do validation when saving);
  266. /// (2) Load a recipe from recipe engine to run process(always do a validation before run recipe);
  267. /// </summary>
  268. /// <param name="recipeName"></param>
  269. /// <param name="needValidation">indicate whether a recipe format validation is needed or not</param>
  270. /// <returns></returns>
  271. public string LoadRecipe(string chamberId, string recipeName, bool needValidation)
  272. {
  273. string rcp = string.Empty;
  274. try
  275. {
  276. using (StreamReader fs = new StreamReader(GenerateRecipeFilePath(chamberId, recipeName)))
  277. {
  278. rcp = fs.ReadToEnd();
  279. fs.Close();
  280. }
  281. //if (needValidation)
  282. //{
  283. // List<string> reason;
  284. // if (!ValidateRecipe(chamberId, recipeName, rcp, out reason))
  285. // {
  286. // rcp = string.Empty;
  287. // LOG.Write("校验recipe file 出错, " + string.Join(",", reason.ToArray()));
  288. // }
  289. //}
  290. }
  291. catch (Exception ex)
  292. {
  293. //LOG.Write(ex, $"load recipe file failed, {recipeName}");
  294. rcp = string.Empty;
  295. }
  296. return rcp;
  297. }
  298. /// <summary>
  299. /// Get recipe list
  300. /// </summary>
  301. /// <param name="chamId"></param>
  302. /// <param name="includingUsedRecipe"></param>
  303. /// <returns></returns>
  304. public IEnumerable<string> GetRecipes(string chamberId, bool includingUsedRecipe)
  305. {
  306. return _rcpContext.GetRecipes(chamberId, includingUsedRecipe);
  307. }
  308. /// <summary>
  309. /// Get recipe list in xml format
  310. /// </summary>
  311. /// <param name="chamId"></param>
  312. /// <param name="includingUsedRecipe"></param>
  313. /// <returns></returns>
  314. public string GetXmlRecipeList(string chamberId, bool includingUsedRecipe)
  315. {
  316. XmlDocument doc = new XmlDocument();
  317. var baseFolderPath = getRecipeDirPath(chamberId);
  318. DirectoryInfo curFolderInfo = new DirectoryInfo(baseFolderPath);
  319. doc.AppendChild(GenerateRecipeList(chamberId, curFolderInfo, doc, includingUsedRecipe));
  320. return doc.OuterXml;
  321. }
  322. public void SaveRecipeHistory(string chamberId, string recipeName, string recipeContent, bool needSaveAs = true)
  323. {
  324. try
  325. {
  326. if (!string.IsNullOrEmpty(recipeName) && needSaveAs)
  327. {
  328. string newRecipeName = string.Format("HistoryRecipe\\{0}\\{1}", DateTime.Now.ToString("yyyyMM"), recipeName);
  329. SaveRecipe(chamberId, newRecipeName, recipeContent, true, false);
  330. //LOG.Write(string.Format("{0}通知TM保存工艺程序{1}", chamberId, recipeName));
  331. }
  332. }
  333. catch (Exception ex)
  334. {
  335. //LOG.Write(ex, string.Format("保存{0}工艺程序{1}发生错误", chamberId, recipeName));
  336. }
  337. }
  338. /// <summary>
  339. /// generate recipe list information in current directory
  340. /// </summary>
  341. /// <param name="chamId"></param>
  342. /// <param name="currentDir"></param>
  343. /// <param name="doc"></param>
  344. /// <returns></returns>
  345. XmlElement GenerateRecipeList(string chamberId, DirectoryInfo currentDir, XmlDocument doc, bool includingUsedRecipe)
  346. {
  347. int trimLength = getRecipeDirPath(chamberId).Length;
  348. XmlElement folderEle = doc.CreateElement("Folder");
  349. folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));
  350. DirectoryInfo[] dirInfos = currentDir.GetDirectories();
  351. foreach (DirectoryInfo dirInfo in dirInfos)
  352. {
  353. if (!includingUsedRecipe && dirInfo.Name == "HistoryRecipe")
  354. continue;
  355. folderEle.AppendChild(GenerateRecipeList(chamberId, dirInfo, doc, includingUsedRecipe));
  356. }
  357. FileInfo[] fileInfos = currentDir.GetFiles("*.rcp");
  358. foreach (FileInfo fileInfo in fileInfos)
  359. {
  360. XmlElement fileNd = doc.CreateElement("File");
  361. string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;
  362. fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));
  363. fileNd.SetAttribute("Name", fileStr);
  364. folderEle.AppendChild(fileNd);
  365. }
  366. return folderEle;
  367. }
  368. /// <summary>
  369. /// Delete a recipe by recipe name
  370. /// </summary>
  371. /// <param name="chamId"></param>
  372. /// <param name="recipeName"></param>
  373. /// <returns></returns>
  374. public bool DeleteRecipe(string chamberId, string recipeName)
  375. {
  376. try
  377. {
  378. var path = GenerateRecipeFilePath(chamberId, recipeName);
  379. if (!_rcpContext.EnableEdit(path))
  380. return false;
  381. File.Delete(path);
  382. InfoDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteSucceeded, recipeName));
  383. }
  384. catch (Exception ex)
  385. {
  386. //LOG.Write(ex, "删除recipe file 出错");
  387. WarningDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteFailed, recipeName));
  388. return false;
  389. }
  390. return true;
  391. }
  392. /// <summary>
  393. /// Rename recipe
  394. /// </summary>
  395. /// <param name="chamId"></param>
  396. /// <param name="oldName"></param>
  397. /// <param name="newName"></param>
  398. /// <returns></returns>
  399. public bool RenameRecipe(string chamId, string oldName, string newName)
  400. {
  401. try
  402. {
  403. var path = GenerateRecipeFilePath(chamId, newName);
  404. if (!_rcpContext.EnableEdit(path))
  405. return false;
  406. if (File.Exists(path))
  407. {
  408. WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0FileExisted, oldName));
  409. return false;
  410. }
  411. else
  412. {
  413. File.Move(GenerateRecipeFilePath(chamId, oldName), GenerateRecipeFilePath(chamId, newName));
  414. InfoDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0Renamed, oldName, newName));
  415. }
  416. }
  417. catch (Exception ex)
  418. {
  419. //LOG.Write(ex, "重命名recipe file 出错");
  420. WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0RenameFailed, oldName, newName));
  421. return false;
  422. }
  423. return true;
  424. }
  425. //private void EventInfo(string message)
  426. //{
  427. // _rcpContext.PostInfoEvent(message);
  428. //}
  429. //private void EventWarning(string message)
  430. //{
  431. // _rcpContext.PostWarningEvent(message);
  432. //}
  433. //private void EventAlarm(string message)
  434. //{
  435. // _rcpContext.PostAlarmEvent(message);
  436. //}
  437. private void InfoDialog(string message)
  438. {
  439. _rcpContext.PostInfoDialogMessage(message);
  440. }
  441. private void WarningDialog(string message)
  442. {
  443. _rcpContext.PostWarningDialogMessage(message);
  444. }
  445. //private void AlarmDialog(string message)
  446. //{
  447. // _rcpContext.PostAlarmDialogMessage(message);
  448. //}
  449. private void EventDialog(string message, List<string> reason)
  450. {
  451. string msg = message;
  452. foreach (var r in reason)
  453. {
  454. msg += "\r\n" + r;
  455. }
  456. _rcpContext.PostDialogEvent(msg);
  457. }
  458. /// <summary>
  459. /// get recipe's file path
  460. /// </summary>
  461. /// <param name="recipeName"></param>
  462. /// <returns></returns>
  463. private string GenerateRecipeFilePath(string chamId, string recipeName)
  464. {
  465. return getRecipeDirPath(chamId) + recipeName + ".rcp";
  466. }
  467. private string GenerateSequenceFilePath(string chamId, string recipeName)
  468. {
  469. return getRecipeDirPath(chamId) + recipeName + ".seq";
  470. }
  471. /// <summary>
  472. /// get recipe's dir path
  473. /// </summary>
  474. /// <param name="recipeName"></param>
  475. /// <returns></returns>
  476. private string getRecipeDirPath(string chamId)
  477. {
  478. var dir = string.Format("{0}{1}\\", PathManager.GetRecipeDir(), chamId);
  479. DirectoryInfo di = new DirectoryInfo(dir);
  480. if (!di.Exists) di.Create();
  481. return dir;
  482. }
  483. /// <summary>
  484. /// delete a recipe folder
  485. /// </summary>
  486. /// <param name="chamId"></param>
  487. /// <param name="folderName"></param>
  488. /// <returns></returns>
  489. public bool DeleteFolder(string chamId, string folderName)
  490. {
  491. try
  492. {
  493. Directory.Delete(getRecipeDirPath(chamId) + folderName, true);
  494. InfoDialog(string.Format(Resources.RecipeFileManager_DeleteFolder_RecipeFolder0DeleteSucceeded, folderName));
  495. }
  496. catch (Exception ex)
  497. {
  498. //LOG.Write(ex, "删除recipe folder 出错");
  499. WarningDialog(string.Format("recipe folder {0} delete failed", folderName));
  500. return false;
  501. }
  502. return true;
  503. }
  504. /// <summary>
  505. /// save as recipe content
  506. /// </summary>
  507. /// <param name="chamId"></param>
  508. /// <param name="recipeName"></param>
  509. /// <param name="recipeContent"></param>
  510. /// <returns></returns>
  511. public bool SaveAsRecipe(string chamId, string recipeName, string recipeContent)
  512. {
  513. var path = GenerateRecipeFilePath(chamId, recipeName);
  514. //if (File.Exists(path))
  515. //{
  516. // WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));
  517. // return false;
  518. //}
  519. return SaveRecipe(chamId, recipeName, recipeContent, true, true);
  520. }
  521. /// <summary>
  522. /// save recipe content
  523. /// </summary>
  524. /// <param name="chamId"></param>
  525. /// <param name="recipeName"></param>
  526. /// <param name="recipeContent"></param>
  527. /// <returns></returns>
  528. public bool SaveRecipe(string chamId, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)
  529. {
  530. //validate recipe format when saving a recipe file
  531. //var reasons1 = new List<string>();
  532. //var reasons2 = new List<string>();
  533. //ValidateRecipe(chamId, recipeName, recipeContent, out reasons1);
  534. //CheckRecipe(chamId, recipeContent, out reasons2);
  535. //reasons1.AddRange(reasons2);
  536. //if (reasons1.Count > 0)
  537. //{
  538. // EventDialog(string.Format( Resources.RecipeFileManager_SaveRecipe_SaveRecipeContentError, recipeName), reasons1);
  539. //}
  540. bool ret = true;
  541. try
  542. {
  543. var path = GenerateRecipeFilePath(chamId, recipeName);
  544. if (!_rcpContext.EnableEdit(path))
  545. return false;
  546. FileInfo fi = new FileInfo(path);
  547. if (!fi.Directory.Exists)
  548. fi.Directory.Create();
  549. File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);
  550. //XmlDocument xml = new XmlDocument();
  551. //xml.LoadXml(recipeContent);
  552. //XmlTextWriter writer = new XmlTextWriter(path, null);
  553. //writer.Formatting = Formatting.Indented;
  554. //xml.Save(writer);
  555. //writer.Close();
  556. //if (notifyUI)
  557. //{
  558. // InfoDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveCompleted, recipeName));
  559. //}
  560. //else
  561. //{
  562. // EV.PostMessage("System", EventEnum.GeneralInfo, string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveCompleted, recipeName));
  563. //}
  564. }
  565. catch (Exception ex)
  566. {
  567. //LOG.Write(ex, "保存recipe file 出错");
  568. if (notifyUI)
  569. {
  570. WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));
  571. }
  572. ret = false;
  573. }
  574. return ret;
  575. }
  576. /// <summary>
  577. /// move recipe file
  578. /// </summary>
  579. /// <param name="chamId"></param>
  580. /// <param name="recipeName"></param>
  581. /// <returns></returns>
  582. public bool MoveRecipeFile(string chamId, string recipeName, string tragetFolderName, bool clearBarcode, bool notifyUI)
  583. {
  584. bool ret = true;
  585. try
  586. {
  587. var path = getRecipeDirPath(chamId);
  588. string fullFileName = path + recipeName + ".rcp";
  589. string tragetFullFilePath = path + tragetFolderName;
  590. File.Move(fullFileName, tragetFullFilePath + "\\" + recipeName.Split('\\')[recipeName.Split('\\').Length - 1] + ".rcp");
  591. if (notifyUI)
  592. {
  593. InfoDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  594. }
  595. else
  596. {
  597. EV.PostMessage("System", EventEnum.GeneralInfo, string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));
  598. }
  599. }
  600. catch (Exception ex)
  601. {
  602. //LOG.Write(ex, "移动 recipe file 出错");
  603. if (notifyUI)
  604. {
  605. WarningDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveFailed, recipeName));
  606. }
  607. ret = false;
  608. }
  609. return ret;
  610. }
  611. /// <summary>
  612. /// create a new recipe folder
  613. /// </summary>
  614. /// <param name="chamId"></param>
  615. /// <param name="folderName"></param>
  616. /// <returns></returns>
  617. public bool CreateFolder(string chamId, string folderName)
  618. {
  619. try
  620. {
  621. Directory.CreateDirectory(getRecipeDirPath(chamId) + folderName);
  622. InfoDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0Created, folderName));
  623. }
  624. catch (Exception ex)
  625. {
  626. //LOG.Write(ex, "创建recipe folder 出错");
  627. WarningDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0CreateFailed, folderName));
  628. return false;
  629. }
  630. return true;
  631. }
  632. /// <summary>
  633. /// Rename recipe folder name
  634. /// </summary>
  635. /// <param name="chamId"></param>
  636. /// <param name="oldName"></param>
  637. /// <param name="newName"></param>
  638. /// <returns></returns>
  639. public bool RenameFolder(string chamId, string oldName, string newName)
  640. {
  641. try
  642. {
  643. string oldPath = getRecipeDirPath(chamId) + oldName;
  644. string newPath = getRecipeDirPath(chamId) + newName;
  645. Directory.Move(oldPath, newPath);
  646. InfoDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0renamed, oldName, newName));
  647. }
  648. catch (Exception ex)
  649. {
  650. //LOG.Write(ex, "重命名recipe folder 出错");
  651. WarningDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0RenameFailed, oldName, newName));
  652. return false;
  653. }
  654. return true;
  655. }
  656. private string GetRecipeBody(string chamberId, string nodePath)
  657. {
  658. if (_rcpContext == null)
  659. return string.Empty;
  660. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  661. XmlDocument dom = new XmlDocument();
  662. dom.LoadXml(schema);
  663. XmlNode node = dom.SelectSingleNode(nodePath);
  664. return node.OuterXml;
  665. }
  666. /// <summary>
  667. /// get reactor's recipe format define file
  668. /// </summary>
  669. /// <param name="chamId"></param>
  670. /// <returns></returns>
  671. public string GetRecipeFormatXml(string chamberId)
  672. {
  673. return GetRecipeBody(chamberId, "/Aitex/TableRecipeFormat");
  674. }
  675. /// <summary>
  676. /// get reactor's template recipe file
  677. /// </summary>
  678. /// <param name="chamId"></param>
  679. /// <returns></returns>
  680. public string GetRecipeTemplate(string chamberId)
  681. {
  682. if (_rcpContext != null)
  683. return _rcpContext.GetRecipeTemplate(chamberId);
  684. return GetRecipeBody(chamberId, "/Aitex/TableRecipeData");
  685. }
  686. /// <summary>
  687. /// get reactor's template recipe file
  688. /// </summary>
  689. /// <param name="chamId"></param>
  690. /// <returns></returns>
  691. public string GetRecipeSchema(string chamberId)
  692. {
  693. if (_rcpContext == null)
  694. return string.Empty;
  695. string schema = _rcpContext.GetRecipeDefiniton(chamberId);
  696. XmlDocument dom = new XmlDocument();
  697. dom.LoadXml(schema);
  698. XmlNode node = dom.SelectSingleNode("/Aitex/TableRecipeSchema");
  699. return node.InnerXml;
  700. }
  701. public string GetRecipeByBarcode(string chamberId, string barcode)
  702. {
  703. try
  704. {
  705. string recipePath = PathManager.GetRecipeDir() + chamberId + "\\";
  706. var di = new DirectoryInfo(recipePath);
  707. var fis = di.GetFiles("*.rcp", SearchOption.AllDirectories);
  708. XmlDocument xml = new XmlDocument();
  709. foreach (var fi in fis)
  710. {
  711. string str = fi.FullName.Substring(recipePath.Length);
  712. if (!str.Contains("HistoryRecipe\\"))
  713. {
  714. xml.Load(fi.FullName);
  715. if (xml.SelectSingleNode(string.Format("/TableRecipeData[@Barcode='{0}']", barcode)) != null)
  716. {
  717. return str.Substring(0, str.LastIndexOf('.'));
  718. }
  719. }
  720. }
  721. return string.Empty;
  722. }
  723. catch (Exception ex)
  724. {
  725. //LOG.Write(ex);
  726. return string.Empty;
  727. }
  728. }
  729. #region Sequence
  730. private string GetSequenceConfig(string nodePath)
  731. {
  732. if (_seqContext == null)
  733. return string.Empty;
  734. string schema = _seqContext.GetConfigXml();
  735. XmlDocument dom = new XmlDocument();
  736. dom.LoadXml(schema);
  737. XmlNode node = dom.SelectSingleNode(nodePath);
  738. return node.OuterXml;
  739. }
  740. public string GetSequence(string sequenceName, bool needValidation)
  741. {
  742. string seq = string.Empty;
  743. try
  744. {
  745. using (StreamReader fs = new StreamReader(GenerateSequenceFilePath(SequenceFolder, sequenceName)))
  746. {
  747. seq = fs.ReadToEnd();
  748. fs.Close();
  749. }
  750. if (needValidation && !_seqContext.Validation(seq))
  751. {
  752. EV.PostWarningLog(SourceModule, $"Read {sequenceName} failed, validation failed");
  753. seq = string.Empty;
  754. }
  755. }
  756. catch (Exception ex)
  757. {
  758. //LOG.Write(ex);
  759. EV.PostWarningLog(SourceModule, $"Read {sequenceName} failed, " + ex.Message);
  760. seq = string.Empty;
  761. }
  762. return seq;
  763. }
  764. public List<string> GetSequenceNameList()
  765. {
  766. var result = new List<string>();
  767. try
  768. {
  769. string recipePath = PathManager.GetRecipeDir() + SequenceFolder + "\\";
  770. var di = new DirectoryInfo(recipePath);
  771. var fis = di.GetFiles("*.seq", SearchOption.AllDirectories);
  772. foreach (var fi in fis)
  773. {
  774. string str = fi.FullName.Substring(recipePath.Length);
  775. str = str.Substring(0, str.LastIndexOf('.'));
  776. result.Add(str);
  777. }
  778. }
  779. catch (Exception ex)
  780. {
  781. //LOG.Write(ex);
  782. EV.PostWarningLog(SourceModule, "Get sequence list failed, " + ex.Message);
  783. }
  784. return result;
  785. }
  786. public bool DeleteSequence(string sequenceName)
  787. {
  788. try
  789. {
  790. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  791. if (!_seqContext.EnableEdit(path))
  792. return false;
  793. File.Delete(path);
  794. EV.PostInfoLog(SourceModule, $"sequence {sequenceName} deleted");
  795. }
  796. catch (Exception ex)
  797. {
  798. //LOG.Write(ex);
  799. EV.PostWarningLog(SourceModule, $"delete {sequenceName} failed, " + ex.Message);
  800. return false;
  801. }
  802. return true;
  803. }
  804. public bool SaveSequence(string sequenceName, string sequenceContent, bool notifyUI)
  805. {
  806. bool ret = true;
  807. try
  808. {
  809. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  810. if (!_seqContext.EnableEdit(path))
  811. return false;
  812. FileInfo fi = new FileInfo(path);
  813. if (!fi.Directory.Exists)
  814. {
  815. fi.Directory.Create();
  816. }
  817. XmlDocument xml = new XmlDocument();
  818. xml.LoadXml(sequenceContent);
  819. XmlTextWriter writer = new XmlTextWriter(path, null);
  820. writer.Formatting = Formatting.Indented;
  821. xml.Save(writer);
  822. writer.Close();
  823. if (notifyUI)
  824. {
  825. EV.PostPopDialogMessage(EventLevel.Information, "Save Complete", $"Sequence {sequenceName} saved ");
  826. }
  827. else
  828. {
  829. EV.PostInfoLog(SourceModule, $"Sequence {sequenceName} saved ");
  830. }
  831. }
  832. catch (Exception ex)
  833. {
  834. //LOG.Write(ex);
  835. EV.PostWarningLog(SourceModule, $"save sequence {sequenceName} failed, " + ex.Message);
  836. if (notifyUI)
  837. {
  838. EV.PostPopDialogMessage(EventLevel.Alarm, "Save Error", $"save sequence {sequenceName} failed, " + ex.Message);
  839. }
  840. ret = false;
  841. }
  842. return ret;
  843. }
  844. public bool SaveAsSequence(string sequenceName, string sequenceContent)
  845. {
  846. var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);
  847. if (File.Exists(path))
  848. {
  849. EV.PostWarningLog(SourceModule, $"save sequence {sequenceName} failed, already exist");
  850. return false;
  851. }
  852. return SaveSequence(sequenceName, sequenceContent, false);
  853. }
  854. public bool RenameSequence(string oldName, string newName)
  855. {
  856. try
  857. {
  858. var path = GenerateSequenceFilePath(SequenceFolder, oldName);
  859. if (!_seqContext.EnableEdit(path))
  860. return false;
  861. if (File.Exists(GenerateSequenceFilePath(SequenceFolder, newName)))
  862. {
  863. EV.PostWarningLog(SourceModule, $"{newName} already exist, rename failed");
  864. return false;
  865. }
  866. else
  867. {
  868. File.Move(path, GenerateSequenceFilePath(SequenceFolder, newName));
  869. EV.PostInfoLog(SourceModule, $"sequence {oldName} renamed to {newName}");
  870. }
  871. }
  872. catch (Exception ex)
  873. {
  874. //LOG.Write(ex);
  875. EV.PostWarningLog(SourceModule, $"rename {oldName} failed, " + ex.Message);
  876. return false;
  877. }
  878. return true;
  879. }
  880. public string GetSequenceFormatXml()
  881. {
  882. return GetSequenceConfig("/Aitex/TableSequenceFormat");
  883. }
  884. internal bool DeleteSequenceFolder(string folderName)
  885. {
  886. try
  887. {
  888. Directory.Delete(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName, true);
  889. EV.PostInfoLog(SourceModule, "Folder " + folderName + "deleted");
  890. }
  891. catch (Exception ex)
  892. {
  893. //LOG.Write(ex, "delete sequence folder exception");
  894. EV.PostWarningLog(SourceModule, $"can not delete folder {folderName}, {ex.Message}");
  895. return false;
  896. }
  897. return true;
  898. }
  899. internal bool CreateSequenceFolder(string folderName)
  900. {
  901. try
  902. {
  903. Directory.CreateDirectory(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName);
  904. EV.PostInfoLog(SourceModule, "Folder " + folderName + "created");
  905. }
  906. catch (Exception ex)
  907. {
  908. //LOG.Write(ex, "sequence folder create exception");
  909. EV.PostWarningLog(SourceModule, $"can not create folder {folderName}, {ex.Message}");
  910. return false;
  911. }
  912. return true;
  913. }
  914. internal bool RenameSequenceFolder(string oldName, string newName)
  915. {
  916. try
  917. {
  918. string oldPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + oldName;
  919. string newPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + newName;
  920. Directory.Move(oldPath, newPath);
  921. EV.PostInfoLog(SourceModule, $"rename folder from {oldName} to {newName}");
  922. }
  923. catch (Exception ex)
  924. {
  925. //LOG.Write(ex, "rename sequence folder failed");
  926. EV.PostWarningLog(SourceModule, $"can not rename folder {oldName}, {ex.Message}");
  927. return false;
  928. }
  929. return true;
  930. }
  931. public string GetXmlSequenceList(string chamberId)
  932. {
  933. XmlDocument doc = new XmlDocument();
  934. DirectoryInfo curFolderInfo = new DirectoryInfo(PathManager.GetRecipeDir() + SequenceFolder + "\\");
  935. doc.AppendChild(GenerateSequenceList(chamberId, curFolderInfo, doc));
  936. return doc.OuterXml;
  937. }
  938. XmlElement GenerateSequenceList(string chamberId, DirectoryInfo currentDir, XmlDocument doc)
  939. {
  940. int trimLength = (PathManager.GetRecipeDir() + SequenceFolder + "\\").Length;
  941. XmlElement folderEle = doc.CreateElement("Folder");
  942. folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));
  943. DirectoryInfo[] dirInfos = currentDir.GetDirectories();
  944. foreach (DirectoryInfo dirInfo in dirInfos)
  945. {
  946. folderEle.AppendChild(GenerateSequenceList(chamberId, dirInfo, doc));
  947. }
  948. FileInfo[] fileInfos = currentDir.GetFiles("*.seq");
  949. foreach (FileInfo fileInfo in fileInfos)
  950. {
  951. XmlElement fileNd = doc.CreateElement("File");
  952. string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;
  953. fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));
  954. fileNd.SetAttribute("Name", fileStr);
  955. folderEle.AppendChild(fileNd);
  956. }
  957. return folderEle;
  958. }
  959. #endregion
  960. }
  961. }