RecipeFileManager.cs 40 KB

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