| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230 | using Aitex.Common.Util;using Aitex.Core.RT.Event;using Aitex.Core.RT.Log;using Aitex.Core.Util;using Aitex.Core.Utilities;using Aitex.Core.WCF;using MECF.Framework.Common.Equipment;using MECF.Framework.Common.Properties;using MECF.Framework.Common.RecipeCenter;using System;using System.Collections.Generic;using System.IO;using System.Text;using System.Text.RegularExpressions;using System.Xml;using System.Xml.Schema;using Venus_Core;namespace Aitex.Core.RT.RecipeCenter{    public class RecipeFileManager : Singleton<RecipeFileManager>    {        //sequence文件 统一放在 Recipes/Sequence 文件夹下面        public const string SequenceFolder = "Sequence";        public const string SourceModule = "Recipe";        private bool _recipeIsValid;        private List<string> _validationErrors = new List<string>();        private List<string> _validationWarnings = new List<string>();                IRecipeFileContext _rcpContext;        private ISequenceFileContext _seqContext;        public void Initialize(IRecipeFileContext context)        {            Initialize(context, null, true);        }        public void Initialize(IRecipeFileContext context, bool enableService)        {            Initialize(context, null, enableService);        }        public void Initialize(IRecipeFileContext rcpContext, ISequenceFileContext seqContext, bool enableService)        {            _rcpContext = rcpContext == null ? new DefaultRecipeFileContext() : rcpContext;            _seqContext = seqContext == null ? new DefaultSequenceFileContext() : seqContext;            CultureSupported.UpdateCoreCultureResource(CultureSupported.English);            //if (enableService)            //{            //    Singleton<WcfServiceManager>.Instance.Initialize(new Type[]            //    {            //        typeof(RecipeService)            //    });            //}            var dir = string.Format("{0}{1}\\", PathManager.GetRecipeDir(), SequenceFolder);            DirectoryInfo di = new DirectoryInfo(dir);            if (!di.Exists)            {                di.Create();            }        }        private void ValidationEventHandler(object sender, ValidationEventArgs e)        {            switch (e.Severity)            {                case XmlSeverityType.Error:                    _validationErrors.Add(e.Message);                    _recipeIsValid = false;                    break;                case XmlSeverityType.Warning:                    _validationWarnings.Add(e.Message);                    break;            }        }        /// <summary>        /// XML schema checking        /// </summary>        /// <param name="chamId"></param>        /// <param name="recipeName"></param>        /// <param name="recipeContent"></param>        /// <param name="reason"></param>        /// <returns></returns>        public bool ValidateRecipe(string chamberId, string recipeName, string recipeContent, out List<string> reason)        {            try            {                XmlDocument document = new XmlDocument();                document.LoadXml(recipeContent);                MemoryStream schemaStream = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(GetRecipeSchema(chamberId)));                XmlReader xmlSchemaReader = XmlReader.Create(schemaStream);                XmlSchema schema1 = XmlSchema.Read(xmlSchemaReader, ValidationEventHandler);                document.Schemas.Add(schema1);                document.LoadXml(recipeContent);                ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);                _recipeIsValid = true;                _validationErrors = new List<string>();                _validationWarnings = new List<string>();                // Validates recipe.                document.Validate(eventHandler);            }            catch (Exception ex)            {                LOG.WriteExeption(ex);                _recipeIsValid = false;            }            if (!_recipeIsValid && _validationErrors.Count == 0)            {                _validationErrors.Add(Resources.RecipeFileManager_ValidateRecipe_XMLSchemaValidateFailed);            }            reason = _validationErrors;            return _recipeIsValid;        }        /// <summary>        /// Check recipe content        /// </summary>        /// <param name="chamId"></param>        /// <param name="recipeContent"></param>        /// <param name="reasons"></param>        /// <returns></returns>        public bool CheckRecipe(string chamberId, string recipeContent, out List<string> reasons)        {            reasons = new List<string>();            //add recipe content validation here            try            {                var xmlFormat = new XmlDocument();                xmlFormat.LoadXml(GetRecipeFormatXml(chamberId));                var mfcDic = new Dictionary<string, double>(); //name + scale                var pcDic = new Dictionary<string, double>(); //name + scale                foreach (XmlElement mfc in xmlFormat.SelectNodes("/TableRecipeFormat/Catalog/Group/Step[@DeviceType='MFC']"))                {                    mfcDic.Add(mfc.Attributes["ControlName"].Value, Convert.ToDouble(mfc.Attributes["Max"].Value));                }                foreach (XmlElement pc in xmlFormat.SelectNodes("/TableRecipeFormat/Catalog/Group/Step[@DeviceType='PC']"))                {                    pcDic.Add(pc.Attributes["ControlName"].Value, Convert.ToDouble(pc.Attributes["Max"].Value));                }                //var spindleMaxSpeed = Convert.ToDouble(xmlFormat.SelectSingleNode("/TableRecipeFormat/Catalog/Group/Step[@ControlName='Spindle.Speed']").Attributes["Max"].Value);                var xmlRecipe = new XmlDocument();                xmlRecipe.LoadXml(recipeContent);                //read in all recipe items                Dictionary<int, Dictionary<string, string>> recipeItems = new Dictionary<int, Dictionary<string, string>>();                var stepElements = xmlRecipe.SelectNodes("/TableRecipeData/Step");                for (int stepNo = 0; stepNo < stepElements.Count; stepNo++)                {                    var stepElement = stepElements[stepNo] as XmlElement;                    var step = new Dictionary<string, string>();                    recipeItems.Add(stepNo, step);                    foreach (XmlAttribute att1 in stepElement.Attributes)                    {                        step.Add(att1.Name, att1.Value);                    }                    foreach (XmlElement subNd1 in stepElement.ChildNodes)                    {                        foreach (XmlAttribute att2 in subNd1.Attributes)                        {                            step.Add(att2.Name, att2.Value);                        }                        foreach (XmlElement subNd2 in subNd1.ChildNodes)                        {                            foreach (XmlAttribute att3 in subNd2.Attributes)                            {                                step.Add(att3.Name, att3.Value);                            }                            foreach (XmlElement subNd3 in subNd2.ChildNodes)                            {                                foreach (XmlAttribute att4 in subNd3.Attributes)                                {                                    step.Add(att4.Name, att4.Value);                                }                            }                        }                    }                }                #region check loop control                for (int j = 0; j < recipeItems.Count; j++)                {                    var loopStr = recipeItems[j]["Loop"];                    bool isLoopStart = Regex.IsMatch(loopStr, @"^Loop\x20\d+$");                    bool isLoopEnd = Regex.IsMatch(loopStr, @"^Loop End$");                    bool isNullOrEmpty = string.IsNullOrWhiteSpace(loopStr);                    if (!isLoopEnd && !isLoopStart && !isNullOrEmpty)                    {                        string reason = string.Format("Value '{0}' not valid", loopStr);                        reasons.Add(string.Format("第{0}步,{1}。", j + 1, reason));                    }                    if (isLoopEnd)                    {                        string reason = "Loop Start 缺失";                        reasons.Add(string.Format("第{0}步,{1}。", j + 1, reason));                    }                    else if (isLoopStart)                    {                        for (int k = j + 1; k < recipeItems.Count; k++)                        {                            var loopStr2 = recipeItems[k]["Loop"];                            bool isCurStepLoopStart = Regex.IsMatch(loopStr2, @"^Loop\x20\d+$");                            bool isCurStepLoopEnd = Regex.IsMatch(loopStr2, @"^Loop End$");                            isNullOrEmpty = string.IsNullOrWhiteSpace(loopStr2);                            if (!isCurStepLoopEnd && !isCurStepLoopStart && !isNullOrEmpty)                            {                                string reason = string.Format("Value '{0}' not valid", loopStr2);                                reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));                            }                            else if (isCurStepLoopStart)                            {                                string reason = "前面循环没有结束,不能设置新的Loop Start标志";                                reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));                            }                            else if (isCurStepLoopEnd)                            {                                j = k;                                break;                            }                            if (k == recipeItems.Count - 1)                            {                                j = k;                                string reason = "Loop End 缺失";                                reasons.Add(string.Format("第{0}步,{1}。", k + 1, reason));                            }                        }                    }                }                #endregion                //check mfc range                for (int stepNo = 0; stepNo < recipeItems.Count; stepNo++)                {                    foreach (var mfcName in mfcDic.Keys)                    {                        if (recipeItems[stepNo].ContainsKey(mfcName))                        {                            var mfcSetpoint = Convert.ToDouble(recipeItems[stepNo][mfcName]);                            if (mfcSetpoint < 0 || mfcSetpoint > mfcDic[mfcName])                            {                                reasons.Add(string.Format("第{0}步,{1}设定{2},超出 0~{3}sccm范围。", stepNo + 1, mfcName, mfcSetpoint, mfcDic[mfcName]));                            }                        }                    }                    //check pc range                    foreach (var pcName in pcDic.Keys)                    {                        if (recipeItems[stepNo].ContainsKey(pcName))                        {                            var pcSetpoint = Convert.ToDouble(recipeItems[stepNo][pcName]);                            if (pcSetpoint < 0 || pcSetpoint > pcDic[pcName])                            {                                reasons.Add(string.Format("第{0}步,{1}设定{2},超出 0~{3}mbar范围。", stepNo + 1, pcName, pcSetpoint, pcDic[pcName]));                            }                        }                    }                }                #region recipe parameter validation                //reading predefined varaible                var recipePredfine = new Dictionary<string, string>();                foreach (XmlElement nd in xmlFormat.SelectNodes("/TableRecipeFormat/Validation/Predefine/Item"))                {                    recipePredfine.Add(nd.Attributes["VarName"].Value, nd.Attributes["Value"].Value);                }                #endregion            }            catch (Exception ex)            {                reasons.Add(Resources.RecipeFileManager_CheckRecipe_RecipeValidationFailed + ex.Message);                LOG.WriteExeption(ex);                return false;            }            return reasons.Count == 0;        }        /// <summary>        /// This method will be invoked by two places:        /// (1) Load a recipe from server to GUI for editing (do not need validation when loading, do validation when saving);        /// (2) Load a recipe from recipe engine to run process(always do a validation before run recipe);        /// </summary>        /// <param name="recipeName"></param>        /// <param name="needValidation">indicate whether a recipe format validation is needed or not</param>        /// <returns></returns>        public string LoadRecipe(string chamberId, string recipeName, bool needValidation)        {            string rcp = string.Empty;            try            {                using (StreamReader fs = new StreamReader(GenerateRecipeFilePath(chamberId, recipeName)))                {                    rcp = fs.ReadToEnd();                    fs.Close();                }            }            catch (Exception ex)            {                LOG.WriteExeption($"load recipe file failed, {recipeName}", ex);                rcp = string.Empty;            }            return rcp;        }        public string LoadRecipeByPath(string path)        {            string rcp = string.Empty;            try            {                using (StreamReader fs = new StreamReader(path))                {                    rcp = fs.ReadToEnd();                    fs.Close();                }            }            catch (Exception ex)            {               // LOG.WriteExeption($"load recipe file failed, {recipeName}", ex);                rcp = string.Empty;            }            return rcp;        }        /// <summary>        /// This method will be invoked by two places:        /// (1) Load a recipe from server to GUI for editing (do not need validation when loading, do validation when saving);        /// (2) Load a recipe from recipe engine to run process(always do a validation before run recipe);        /// </summary>        /// <param name="recipeName"></param>        /// <param name="needValidation">indicate whether a recipe format validation is needed or not</param>        /// <returns></returns>        public string LoadRecipe(string chamberId, string recipeName, bool needValidation,string type)        {            string rcp = string.Empty;            try            {                using (StreamReader fs = new StreamReader(GenerateRecipeFilePath2(chamberId,type, recipeName)))                {                    rcp = fs.ReadToEnd();                    fs.Close();                }            }            catch (Exception ex)            {                LOG.WriteExeption($"load recipe file failed, {recipeName}", ex);                rcp = string.Empty;            }            return rcp;        }        /// <summary>        /// Get recipe list        /// </summary>        /// <param name="chamId"></param>        /// <param name="includingUsedRecipe"></param>        /// <returns></returns>        public IEnumerable<string> GetRecipes(string chamberId, bool includingUsedRecipe)        {            return _rcpContext.GetRecipes(chamberId, includingUsedRecipe);        }        /// <summary>        /// Get recipe list in xml format        /// </summary>        /// <param name="chamId"></param>        /// <param name="includingUsedRecipe"></param>        /// <returns></returns>        public string GetXmlRecipeList(string chamberId, bool includingUsedRecipe)        {            XmlDocument doc = new XmlDocument();            var baseFolderPath = getRecipeDirPath(chamberId);            DirectoryInfo curFolderInfo = new DirectoryInfo(baseFolderPath);            doc.AppendChild(GenerateRecipeList(chamberId, curFolderInfo, doc, includingUsedRecipe));            return doc.OuterXml;        }        public void SaveRecipeHistory(string chamberId, string recipeName, string recipeContent, bool needSaveAs = true)        {            try            {                if (!string.IsNullOrEmpty(recipeName) && needSaveAs)                {                    string newRecipeName = string.Format("HistoryRecipe\\{0}\\{1}", DateTime.Now.ToString("yyyyMM"), recipeName);                    SaveRecipe(chamberId, newRecipeName, recipeContent, true, false);                    //LOG.Write(string.Format("{0}通知TM保存工艺程序{1}", chamberId, recipeName));                }            }            catch (Exception ex)            {                LOG.WriteExeption(string.Format("保存{0}工艺程序{1}发生错误", chamberId, recipeName), ex);            }        }        /// <summary>        /// generate recipe list information in current directory        /// </summary>        /// <param name="chamId"></param>        /// <param name="currentDir"></param>        /// <param name="doc"></param>        /// <returns></returns>        XmlElement GenerateRecipeList(string chamberId, DirectoryInfo currentDir, XmlDocument doc, bool includingUsedRecipe)        {            int trimLength = getRecipeDirPath(chamberId).Length;            XmlElement folderEle = doc.CreateElement("Folder");            folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));            DirectoryInfo[] dirInfos = currentDir.GetDirectories();            foreach (DirectoryInfo dirInfo in dirInfos)            {                if (!includingUsedRecipe && dirInfo.Name == "HistoryRecipe")                    continue;                folderEle.AppendChild(GenerateRecipeList(chamberId, dirInfo, doc, includingUsedRecipe));            }            FileInfo[] fileInfos = currentDir.GetFiles("*.rcp");            foreach (FileInfo fileInfo in fileInfos)            {                XmlElement fileNd = doc.CreateElement("File");                string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;                fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));                fileNd.SetAttribute("Name", fileStr);                folderEle.AppendChild(fileNd);            }            return folderEle;        }        /// <summary>        /// Delete a recipe by recipe name        /// </summary>        /// <param name="chamId"></param>        /// <param name="recipeName"></param>        /// <returns></returns>        public bool DeleteRecipe(string chamberId, string recipeName)        {            try            {                var path = GenerateRecipeFilePath(chamberId, recipeName);                if (!_rcpContext.EnableEdit(path))                    return false;                File.Delete(path);                InfoDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteSucceeded, recipeName));            }            catch (Exception ex)            {                LOG.WriteExeption("删除recipe file 出错", ex);                WarningDialog(string.Format(Resources.RecipeFileManager_DeleteRecipe_RecipeFile0DeleteFailed, recipeName));                return false;            }            return true;        }        /// <summary>        ///  Rename recipe        /// </summary>        /// <param name="chamId"></param>        /// <param name="oldName"></param>        /// <param name="newName"></param>        /// <returns></returns>        public bool RenameRecipe(string chamId, string oldName, string newName)        {            try            {                var path = GenerateRecipeFilePath(chamId, newName);                if (!_rcpContext.EnableEdit(path))                    return false;                if (File.Exists(path))                {                    WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0FileExisted, oldName));                    return false;                }                else                {                    File.Move(GenerateRecipeFilePath(chamId, oldName), GenerateRecipeFilePath(chamId, newName));                    InfoDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0Renamed, oldName, newName));                }            }            catch (Exception ex)            {                LOG.WriteExeption("重命名recipe file 出错", ex);                WarningDialog(string.Format(Resources.RecipeFileManager_RenameRecipe_RecipeFile0RenameFailed, oldName, newName));                return false;            }            return true;        }        //private void EventInfo(string message)        //{        //    _rcpContext.PostInfoEvent(message);        //}        //private void EventWarning(string message)        //{        //    _rcpContext.PostWarningEvent(message);        //}        //private void EventAlarm(string message)        //{        //    _rcpContext.PostAlarmEvent(message);        //}        private void InfoDialog(string message)        {            _rcpContext.PostInfoDialogMessage(message);        }        private void WarningDialog(string message)        {            _rcpContext.PostWarningDialogMessage(message);        }        //private void AlarmDialog(string message)        //{        //    _rcpContext.PostAlarmDialogMessage(message);        //}        private void EventDialog(string message, List<string> reason)        {            string msg = message;            foreach (var r in reason)            {                msg += "\r\n" + r;            }            _rcpContext.PostDialogEvent(msg);        }        /// <summary>        /// get recipe's file path        /// </summary>        /// <param name="recipeName"></param>        /// <returns></returns>        private string GenerateRecipeFilePath(string chamId, string recipeName)        {            return getRecipeDirPath(chamId) + recipeName + ".rcp";        }        private string GenerateRecipeFilePath2(string chamId,  string type,string recipeName)        {            return getRecipeDirPath(chamId) +type+"\\"+ recipeName + ".rcp";        }        private string GenerateSequenceFilePath(string chamId, string recipeName)        {            return getRecipeDirPath(chamId) + recipeName + ".seq";        }        /// <summary>        /// get recipe's dir path        /// </summary>        /// <param name="recipeName"></param>        /// <returns></returns>        private string getRecipeDirPath(string chamId)        {            var dir = string.Format("{0}{1}\\", PathManager.GetRecipeDir(), chamId);            DirectoryInfo di = new DirectoryInfo(dir);            if (!di.Exists) di.Create();            return dir;        }        /// <summary>        /// delete a recipe folder        /// </summary>        /// <param name="chamId"></param>        /// <param name="folderName"></param>        /// <returns></returns>        public bool DeleteFolder(string chamId, string folderName)        {            try            {                Directory.Delete(getRecipeDirPath(chamId) + folderName, true);                InfoDialog(string.Format(Resources.RecipeFileManager_DeleteFolder_RecipeFolder0DeleteSucceeded, folderName));            }            catch (Exception ex)            {                LOG.WriteExeption("删除recipe folder 出错", ex);                WarningDialog(string.Format("recipe folder  {0} delete failed", folderName));                return false;            }            return true;        }        /// <summary>        /// save as recipe content        /// </summary>        /// <param name="chamId"></param>        /// <param name="recipeName"></param>        /// <param name="recipeContent"></param>        /// <returns></returns>        public bool SaveAsRecipe(string chamId, string recipeName, string recipeContent)        {            var path = GenerateRecipeFilePath(chamId, recipeName);            //if (File.Exists(path))            //{            //    WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));            //    return false;            //}            return SaveRecipe(chamId, recipeName, recipeContent, true, true);        }        public bool SaveAsRecipe2(string chamId,string type, string recipeName, string recipeContent)        {            var path = GenerateRecipeFilePath(chamId, recipeName);            //if (File.Exists(path))            //{            //    WarningDialog(string.Format(Resources.RecipeFileManager_SaveAsRecipe_RecipeFile0savefailed, recipeName));            //    return false;            //}            return SaveRecipe2(chamId,type, recipeName, recipeContent, true, true);        }        /// <summary>        /// save recipe content        /// </summary>        /// <param name="chamId"></param>        /// <param name="recipeName"></param>        /// <param name="recipeContent"></param>        /// <returns></returns>        public bool SaveRecipe(string chamId, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)        {            bool ret = true;            try            {                var path = GenerateRecipeFilePath(chamId, recipeName);                if (!_rcpContext.EnableEdit(path))                    return false;                                FileInfo fi = new FileInfo(path);                if (!fi.Directory.Exists)                    fi.Directory.Create();                                File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);            }            catch (Exception ex)            {                LOG.WriteExeption("保存recipe file 出错", ex);                if (notifyUI)                {                    WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));                }                ret = false;            }            return ret;        }        /// <summary>        /// save recipe content        /// </summary>        /// <param name="chamId"></param>        /// <param name="recipeName"></param>        /// <param name="recipeContent"></param>        /// <returns></returns>        public bool SaveRecipe2(string chamId,string type, string recipeName, string recipeContent, bool clearBarcode, bool notifyUI)        {            bool ret = true;            try            {                var path = GenerateRecipeFilePath2(chamId, type, recipeName);                if (!_rcpContext.EnableEdit(path))                    return false;                FileInfo fi = new FileInfo(path);                if (!fi.Directory.Exists)                    fi.Directory.Create();                File.WriteAllText(path, RecipeUnity.ConvertJsonString(recipeContent), Encoding.UTF8);            }            catch (Exception ex)            {                LOG.WriteExeption("保存recipe file 出错", ex);                if (notifyUI)                {                    WarningDialog(string.Format(Resources.RecipeFileManager_SaveRecipe_RecipeFile0SaveFailed, recipeName));                }                ret = false;            }            return ret;        }        /// <summary>        /// move recipe file        /// </summary>        /// <param name="chamId"></param>        /// <param name="recipeName"></param>        /// <returns></returns>        public bool MoveRecipeFile(string chamId, string recipeName, string tragetFolderName, bool clearBarcode, bool notifyUI)        {            bool ret = true;            try            {                var path = getRecipeDirPath(chamId);                string fullFileName = path + recipeName + ".rcp";                string tragetFullFilePath = path + tragetFolderName;                File.Move(fullFileName, tragetFullFilePath + "\\" + recipeName.Split('\\')[recipeName.Split('\\').Length - 1] + ".rcp");                if (notifyUI)                {                    InfoDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));                }                else                {                    LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveCompleted, recipeName));                }            }            catch (Exception ex)            {                LOG.WriteExeption("移动 recipe file 出错", ex);                if (notifyUI)                {                    WarningDialog(string.Format(Resources.RecipeFileManager_MoveRecipe_RecipeFile0MoveFailed, recipeName));                }                ret = false;            }            return ret;        }        /// <summary>        /// create a new recipe folder        /// </summary>        /// <param name="chamId"></param>        /// <param name="folderName"></param>        /// <returns></returns>        public bool CreateFolder(string chamId, string folderName)        {            try            {                Directory.CreateDirectory(getRecipeDirPath(chamId) + folderName);                InfoDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0Created, folderName));            }            catch (Exception ex)            {                LOG.WriteExeption("创建recipe folder 出错", ex);                WarningDialog(string.Format(Resources.RecipeFileManager_CreateFolder_RecipeFolder0CreateFailed, folderName));                return false;            }            return true;        }        /// <summary>        /// Rename recipe folder name        /// </summary>        /// <param name="chamId"></param>        /// <param name="oldName"></param>        /// <param name="newName"></param>        /// <returns></returns>        public bool RenameFolder(string chamId, string oldName, string newName)        {            try            {                string oldPath = getRecipeDirPath(chamId) + oldName;                string newPath = getRecipeDirPath(chamId) + newName;                Directory.Move(oldPath, newPath);                InfoDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0renamed, oldName, newName));            }            catch (Exception ex)            {                LOG.WriteExeption("重命名recipe folder 出错", ex);                WarningDialog(string.Format(Resources.RecipeFileManager_RenameFolder_RecipeFolder0RenameFailed, oldName, newName));                return false;            }            return true;        }        private string GetRecipeBody(string chamberId, string nodePath)        {            if (_rcpContext == null)                return string.Empty;            string schema = _rcpContext.GetRecipeDefiniton(chamberId);            XmlDocument dom = new XmlDocument();            dom.LoadXml(schema);            XmlNode node = dom.SelectSingleNode(nodePath);            return node.OuterXml;        }        /// <summary>        /// get reactor's recipe format define file        /// </summary>        /// <param name="chamId"></param>        /// <returns></returns>        public string GetRecipeFormatXml(string chamberId)        {            return GetRecipeBody(chamberId, "/Aitex/TableRecipeFormat");        }        /// <summary>        /// get reactor's template recipe file        /// </summary>        /// <param name="chamId"></param>        /// <returns></returns>        public string GetRecipeTemplate(string chamberId)        {            if (_rcpContext != null)                return _rcpContext.GetRecipeTemplate(chamberId);            return GetRecipeBody(chamberId, "/Aitex/TableRecipeData");        }        /// <summary>        /// get reactor's template recipe file        /// </summary>        /// <param name="chamId"></param>        /// <returns></returns>        public string GetRecipeSchema(string chamberId)        {            if (_rcpContext == null)                return string.Empty;            string schema = _rcpContext.GetRecipeDefiniton(chamberId);            XmlDocument dom = new XmlDocument();            dom.LoadXml(schema);            XmlNode node = dom.SelectSingleNode("/Aitex/TableRecipeSchema");            return node.InnerXml;        }        public string GetRecipeByBarcode(string chamberId, string barcode)        {            try            {                string recipePath = PathManager.GetRecipeDir() + chamberId + "\\";                var di = new DirectoryInfo(recipePath);                var fis = di.GetFiles("*.rcp", SearchOption.AllDirectories);                XmlDocument xml = new XmlDocument();                foreach (var fi in fis)                {                    string str = fi.FullName.Substring(recipePath.Length);                    if (!str.Contains("HistoryRecipe\\"))                    {                        xml.Load(fi.FullName);                        if (xml.SelectSingleNode(string.Format("/TableRecipeData[@Barcode='{0}']", barcode)) != null)                        {                            return str.Substring(0, str.LastIndexOf('.'));                        }                    }                }                return string.Empty;            }            catch (Exception ex)            {                LOG.WriteExeption(ex);                return string.Empty;            }        }        #region Sequence         private string GetSequenceConfig(string nodePath)        {            if (_seqContext == null)                return string.Empty;            string schema = _seqContext.GetConfigXml();            XmlDocument dom = new XmlDocument();            dom.LoadXml(schema);            XmlNode node = dom.SelectSingleNode(nodePath);            return node.OuterXml;        }        public string GetSequence(string sequenceName, bool needValidation)        {            string seq = string.Empty;            try            {                using (StreamReader fs = new StreamReader(GenerateSequenceFilePath(SequenceFolder, sequenceName)))                {                    seq = fs.ReadToEnd();                    fs.Close();                }                if (needValidation && !_seqContext.Validation(seq))                {                    LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"Read {sequenceName} failed, validation failed");                    seq = string.Empty;                }            }            catch (Exception ex)            {                LOG.WriteExeption(ex);                seq = string.Empty;            }            return seq;        }        private void TryAppendNode(XmlElement preOrNextNode, XmlElement curPM,XmlDocument dom, bool isLeft)        {            if (preOrNextNode != null && preOrNextNode.GetAttribute("Position") != "LL" && preOrNextNode.GetAttribute("Position") != "PM")            {                XmlElement newNode = dom.CreateElement("Step");                newNode.SetAttribute("Position", "LL");                newNode.SetAttribute("LLSelection", "LLA,LLB");                if (isLeft)                    curPM.ParentNode.InsertBefore(newNode, curPM);                else                    curPM.ParentNode.InsertAfter(newNode, curPM);            }        }        public string GetSequenceAndTryAppendLL(string sequenceName, bool needValidation)        {            string seq = string.Empty;            try            {                seq = GetSequence(sequenceName, needValidation);                if(!string.IsNullOrWhiteSpace(seq))                {                    XmlDocument dom = new XmlDocument();                    dom.LoadXml(seq);                    XmlNodeList lstStepNode = dom.SelectNodes("Aitex/TableSequenceData/Step");                    if (lstStepNode != null)                    {                        List<XmlElement> pmList = new List<XmlElement>();                        foreach (XmlElement nodeStep in lstStepNode)                        {                            var positionValue = nodeStep.GetAttribute("Position");                            if (positionValue == "PM")                            {                                pmList.Add(nodeStep);                            }                        }                        foreach (XmlElement pmNode in pmList)                        {                            TryAppendNode((XmlElement)pmNode.PreviousSibling, pmNode, dom, true);                            TryAppendNode((XmlElement)pmNode.NextSibling, pmNode, dom, false);                        }                        using (var ms = new MemoryStream())                        using (var writer = new XmlTextWriter(ms, null))                        {                            writer.Formatting = Formatting.Indented;                            dom.Save(writer);                            return Encoding.UTF8.GetString(ms.ToArray());                        }                    }                }            }            catch(Exception ex)            {                LOG.WriteExeption(ex);                seq = string.Empty;            }            return seq;        }        public List<string> GetSequenceNameList()        {            var result = new List<string>();            try            {                string recipePath = PathManager.GetRecipeDir() + SequenceFolder + "\\";                var di = new DirectoryInfo(recipePath);                var fis = di.GetFiles("*.seq", SearchOption.AllDirectories);                foreach (var fi in fis)                {                    string str = fi.FullName.Substring(recipePath.Length);                    str = str.Substring(0, str.LastIndexOf('.'));                    result.Add(str);                }            }            catch (Exception ex)            {                LOG.WriteExeption(ex);            }            return result;        }        public bool DeleteSequence(string sequenceName)        {            try            {                var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);                if (!_seqContext.EnableEdit(path))                    return false;                File.Delete(path);                LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {sequenceName} deleted");            }            catch (Exception ex)            {                LOG.WriteExeption(ex);                return false;            }            return true;        }        public bool SaveSequence(string sequenceName, string sequenceContent, bool notifyUI)        {            bool ret = true;            try            {                var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);                if (!_seqContext.EnableEdit(path))                    return false;                FileInfo fi = new FileInfo(path);                if (!fi.Directory.Exists)                {                    fi.Directory.Create();                }                XmlDocument xml = new XmlDocument();                xml.LoadXml(sequenceContent);                XmlTextWriter writer = new XmlTextWriter(path, null);                writer.Formatting = Formatting.Indented;                xml.Save(writer);                writer.Close();                if (notifyUI)                {                    EV.PostPopDialogMessage(EventLevel.Information, "Save Complete", $"Sequence {sequenceName} saved ");                }                else                {                    LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"Sequence {sequenceName} saved ");                }            }            catch (Exception ex)            {                LOG.WriteExeption(ex);                if (notifyUI)                {                    EV.PostPopDialogMessage(EventLevel.Alarm, "Save Error", $"save sequence {sequenceName} failed, " + ex.Message);                }                ret = false;            }            return ret;        }        public bool SaveAsSequence(string sequenceName, string sequenceContent)        {            var path = GenerateSequenceFilePath(SequenceFolder, sequenceName);            if (File.Exists(path))            {                LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"save sequence {sequenceName} failed, already exist");                return false;            }            return SaveSequence(sequenceName, sequenceContent, false);        }        public bool RenameSequence(string oldName, string newName)        {            try            {                var path = GenerateSequenceFilePath(SequenceFolder, oldName);                if (!_seqContext.EnableEdit(path))                    return false;                if (File.Exists(GenerateSequenceFilePath(SequenceFolder, newName)))                {                    LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"{newName} already exist, rename failed");                    return false;                }                else                {                    File.Move(path, GenerateSequenceFilePath(SequenceFolder, newName));                    LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"sequence {oldName} renamed to {newName}");                }            }            catch (Exception ex)            {                LOG.WriteExeption(ex);                return false;            }            return true;        }        public string GetSequenceFormatXml()        {            return GetSequenceConfig("/Aitex/TableSequenceFormat");        }        internal bool DeleteSequenceFolder(string folderName)        {            try            {                Directory.Delete(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName, true);                LOG.Write(eEvent.EV_SEQUENCE,ModuleName.System,  "Folder " + folderName + "deleted");            }            catch (Exception ex)            {                //LOG.Write(ex, "delete sequence folder exception");                LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not delete folder {folderName}, {ex.Message}");                return false;            }            return true;        }        internal bool CreateSequenceFolder(string folderName)        {            try            {                Directory.CreateDirectory(PathManager.GetRecipeDir() + SequenceFolder + "\\" + folderName);                LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, "Folder " + folderName + "created");            }            catch (Exception ex)            {                //LOG.Write(ex, "sequence folder create exception");                LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not create folder {folderName}, {ex.Message}");                return false;            }            return true;        }        internal bool RenameSequenceFolder(string oldName, string newName)        {            try            {                string oldPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + oldName;                string newPath = PathManager.GetRecipeDir() + SequenceFolder + "\\" + newName;                Directory.Move(oldPath, newPath);                LOG.Write(eEvent.EV_SEQUENCE, ModuleName.System, $"rename folder  from {oldName} to {newName}");            }            catch (Exception ex)            {                //LOG.Write(ex, "rename sequence folder failed");                LOG.Write(eEvent.WARN_SEQUENCE, ModuleName.System, $"can not rename folder {oldName}, {ex.Message}");                return false;            }            return true;        }        public string GetXmlSequenceList(string chamberId)        {            XmlDocument doc = new XmlDocument();            DirectoryInfo curFolderInfo = new DirectoryInfo(PathManager.GetRecipeDir() + SequenceFolder + "\\");            doc.AppendChild(GenerateSequenceList(chamberId, curFolderInfo, doc));            return doc.OuterXml;        }        XmlElement GenerateSequenceList(string chamberId, DirectoryInfo currentDir, XmlDocument doc)        {            int trimLength = (PathManager.GetRecipeDir() + SequenceFolder + "\\").Length;            XmlElement folderEle = doc.CreateElement("Folder");            folderEle.SetAttribute("Name", currentDir.FullName.Substring(trimLength));            DirectoryInfo[] dirInfos = currentDir.GetDirectories();            foreach (DirectoryInfo dirInfo in dirInfos)            {                folderEle.AppendChild(GenerateSequenceList(chamberId, dirInfo, doc));            }            FileInfo[] fileInfos = currentDir.GetFiles("*.seq");            foreach (FileInfo fileInfo in fileInfos)            {                XmlElement fileNd = doc.CreateElement("File");                string fileStr = fileInfo.FullName.Substring(trimLength).TrimStart(new char[] { '\\' }); ;                fileStr = fileStr.Substring(0, fileStr.LastIndexOf("."));                fileNd.SetAttribute("Name", fileStr);                folderEle.AppendChild(fileNd);            }            return folderEle;        }        #endregion    }}
 |