Esempio n. 1
0
        void test_Mtch_2()
        {
            Log.set(" test_Mtch_2: Rule 15 и Group < B12,5 , 1900x1600 > ");
            rule = new Rule.Rule(15);
            ElmAttSet.ElmAttSet elB = new ElmAttSet.ElmAttSet(
                "ID56A7442F-0000-0D7B-3134-353338303236",
                "B12,5", "Concrete", "1900x1600", 0, 0, 0, 1000);
            Dictionary <string, ElmAttSet.ElmAttSet> els = new Dictionary <string, ElmAttSet.ElmAttSet>();

            els.Add(elB.guid, elB);
            List <string> guids = new List <string>(); guids.Add(elB.guid);
            var           model = new Model.Model();

            model.setElements(els);
            model.getGroups();
            var gr = model.elmGroups[0];

            TST.Eq(gr.guids.Count, 1);
            var match = new Mtch(gr, rule);

            TST.Eq(match.ok == OK.Match, true);
            var cmp = match.component;

//31/3            TST.Eq(cmp.fps[SType.Material].pars[0].par.ToString(), "b12,5");
            Log.exit();
        }
Esempio n. 2
0
 private static void testFP_Int_Col()
 {
     Log.set("test__Int_Col(fp)");
     FingerPrint fp = new FingerPrint(type.CompSet, "PRF: L{2}");
     TST.Eq(fp.Col(), 2);
     Log.exit();
 }
Esempio n. 3
0
 /// <summary>
 /// List<Form> Init(int toc_line) - initiate all Forms for Document in toc_line.
 /// </summary>
 /// <param name="toc_line">line number in TOC</param>
 /// <returns>form list</returns>
 public static List<Form> Init(int toc_line)
 {
     Log.set("Init(" + toc_line + ")");
     //------------------------------------------------------------------------------
     language = true; //en-US for Englisg Debug. Remove or comment this line later  !
     //------------------------------------------------------------------------------
     List<Form> Forms = new List<Form>();
     for (int col = Decl.DOC_FORMS, i = 0; i < 10; i++)
     {
         string s = Lang(tocMtr.Strng(toc_line, col++));
         if (string.IsNullOrEmpty(s)) continue;
         if (FileOp.isNamedRangeExist(Wb, s))
         {
             List<int> _r = new List<int>();
             List<int> _c = new List<int>();
             string sf = s + "_F";
             if (FileOp.isNamedRangeExist(Wb, sf))
             {
                 Mtr format = new Mtr(Wb.Names.Item(sf).RefersToRange.Value);
                 for (int c = 1; c <= format.iEOC(); c++)
                     for (int r = 1; r <= format.iEOL(); r++)
                     {
                         string f = format.Strng(r, c);
                         if (f.Contains("{") & f.Contains("}")) { _r.Add(r); _c.Add(c); }
                     }
             }
             Forms.Add(new Form(s, _r, _c));
         }
     }
     Log.exit();
     return Forms;
 }
Esempio n. 4
0
 public void Recover(string repNm, RecoverToDo to_do)
 {
     Log.set(@"SR.Recover(" + repNm + "\")");
     if (!CheckModelIntegrity(model)) Msg.AskFOK("Recovery impossible");
     switch (to_do)
     {
         case RecoverToDo.CreateRep:
             Msg.AskFOK("В каталоге модели нет TSmatchINFO.xlsx/" + repNm + ". Создать?");
             resetDialog = false;
             Docs.getDoc(repNm, reset: true, create_if_notexist: true);
             if (!Docs.IsDocExist(repNm)) Msg.F("SaveDoc.Recover cannot create ", repNm);
             Recover(repNm, RecoverToDo.ResetRep);
             break;
         case RecoverToDo.ResetRep:
             if (resetDialog) Msg.AskFOK("Вы действительно намерены переписать TSmatchINFO.xlsx/" + repNm + "?");
             var w = new WrMod();
             switch (repNm)
             {
                 case Decl.TSMATCHINFO_MODELINFO:
                     w.wrModel(WrM.ModelINFO, model);
                     break;
                 case Decl.TSMATCHINFO_REPORT:
                     log.Info(">>mod.MD5=" + model.MD5 + " =?= " + model.getMD5(model.elements));
                     mh.Pricing(ref model);
                     log.Info(">>mod.MD5=" + model.MD5 + " =?= " + model.getMD5(model.elements));
                     w.wrModel(WrM.Report, model);
                     break;
             }
             break;
     }
     Log.exit();
 }
Esempio n. 5
0
 /// <summary>
 /// GetSavedRules(Mod mod, [init] - read Rules from Rules Sheet in TSmatchINFO.xlsx; Initiate them if init=true
 /// </summary>
 /// <param name="mod"></param>
 /// <param name="init"></param>
 /// <returns></returns>
 public Mod GetSavedRules(Mod mod, bool init = false)
 {
     Log.set("SR.getSavedRules()");
     model = mod;
     dRul = Docs.getDoc(Decl.TSMATCHINFO_RULES, create_if_notexist: false, fatal: false);
     if (dRul == null)
     { // when TXmatchINFO.xlsx/Rules unavailable - initialise them from TSmatch/InitialRules
         Docs ir = Docs.getDoc("InitialRules");
         for (int i = ir.i0; i < ir.il; i++)
             model.Rules.Add(new Rule.Rule(ir, i));
     }
     else
     { // Rules available, read them
         model.Rules.Clear();
         for (int i = dRul.i0; i <= dRul.il; i++)
         {
             try { model.Rules.Add(new Rule.Rule(i)); }
             catch {}
         }
     }
     if (init) foreach (var rule in model.Rules) rule.Init();
     log.Info("GetSavedRules: Rules.Count = " + model.Rules.Count
         + (init ? "" : " NOT") + "Initialized");
     if (!CheckModelIntegrity(model)) error();
     Log.exit();
     return model;
 }
Esempio n. 6
0
        /// <summary>
        /// GetTSmatchINFO(Model) - Main SaveReport method. Read TSmatchINFO.xlsx and Raw.xml
        /// </summary>
        /// <remarks>When no TSmatchINFO.xlsx or Raw.xml files exists, create (or mark to create) them, and check model integrity</remarks>
        protected void GetTSmatchINFO(Mod mod, bool initRules = false)
        {
            Log.set("SR.GetTSmatchINFO(\"" + mod.name + "\")");
            model = mod;
            dINFO = Docs.getDoc(sINFO, fatal: false);
            if (dINFO == null) error();

            model.elements = Raw(model);

            if (model.isChanged)
            { //-- no information available from TSmatchINFO.xlsx or it was changed -- doing re-Pricing
                model.mh.Pricing(ref model, initRules);
            }
            else
            { //- get ModelINFO and pricing from TSmatchINFO.xlsx
                model.name = dINFO.Body.Strng(Decl.MODINFO_NAME_R, 2);
                model.setCity(dINFO.Body.Strng(Decl.MODINFO_ADDRESS_R, 2));
                //20/8/2017                model.dir = dINFO.Body.Strng(Decl.MODINFO_DIR_R, 2).Trim();
                model.date = Lib.getDateTime(dINFO.Body.Strng(Decl.MODINFO_DATE_R, 2));
                model.pricingDate = Lib.getDateTime(dINFO.Body.Strng(Decl.MODINFO_PRCDAT_R, 2));
                model.pricingMD5 = dINFO.Body.Strng(Decl.MODINFO_PRCMD5_R, 2);
                GetSavedReport();
                GetSavedRules(model, initRules);
            }
            if (!CheckModelIntegrity(model)) error();
            Log.exit();
        }
Esempio n. 7
0
//#endif
        public object get(int i, int j)
        {
            object v = null;
            try { v = _matr[i, j]; }
            catch { Log.FATAL("ошибка при обращении к Matr[" + i + "," + j + "]"); }
            return v;
        }
Esempio n. 8
0
 /// <summary>
 /// Raw() - read elements from Raw.xml or re-write it, if necessary 
 ///<para>
 ///re-write reasons could be: Raw.xml not exists, or error found in ModelINFO
 ///</para>
 /// </summary>
 /// <returns>updated list of elements in file and in memory</returns>
 public List<Elm> Raw(Mod mod)
 {
     const string me = "SavedReport__Raw_";
     Log.set("SR.Raw(" + mod.name + ")");
     model = mod;
     List<Elm> elms = new List<Elm>();
     if (!FileOp.isDirExist(model.dir)) Msg.F(me + "No model dir", model.dir);
     string file = Path.Combine(model.dir, Decl.RAWXML);
     if(FileOp.isFileExist(file))
     {                               // Read Raw.xml
         elms = rwXML.XML.ReadFromXmlFile<List<Elm>>(file);
         model.date = File.GetLastWriteTime(file);
     }
     else
     {                               // get from CAD and Write or re-Write Raw.xml 
         Msg.AskFOK(me + "CAD Read");
         model.Read();
         rwXML.XML.WriteToXmlFile(file, model.elements);
         elms = model.elements;
     }
     model.MD5 = model.getMD5(elms);
     log.Info("Raw.xml: { elmCount, MD5} ==" + elms.Count + ", " + model.MD5);
     Log.exit();
     return elms;
 }
Esempio n. 9
0
        } // end update
#endif //FOR_FUTURE 6/4/2017
        /// <summary>
        /// modelListUpdate(name, dir, Made, MD5) - update list of models in TSmatch.xlsx/Models
        /// </summary>
        /// <param name="name">Model name</param>
        /// <param name="dir">Model path in File sistem</param>
        /// <param name="Made">version name of TS.Read - important as AttSet field list identifier</param>
        /// <param name="MD5">checksum of all Model parts</param>
        /// <returns>Model, updated in the list of models in TSmatch</returns>
        /// <history> 6.3.2016 PKh
        /// 15.3.16 return Model instead of null in case of completely new model; wrToFile handle
        ///  5.4.16 Current Phase handling
        ///  6.8.16 non static method
        /// </history>
        Model modelListUpdate(string name, string dir = null, string Made = null,
                                     string MD5 = null, string Phase = null, string str = null)
        {
            Log.set("modelListUpdate");
            Models.Clear(); Start();        // renowate Models list from TSmatch.xlsx
            Model mod = getModel(name);
            if (mod == null)    // mod==null - means this is completely new model
            {
                Models.Add(new Model(name, dir, ifcPath, Made, Phase, MD5));
                mod = getModel(name);
                mod.wrToFile = true;
            }
            else
            {
                if (dir != null) mod.dir = dir;
                if (Made != null) mod.Made = Made;
                if (Phase != null) mod.Phase = Phase;
                if (MD5 != null) mod.MD5 = MD5;
                if (str != null)
                {
                    mod.strListRules = str;
                    foreach (int n in Lib.GetPars(str))
                        mod.Rules.Add(new TSmatch.Rule.Rule(n));
                }
                //!!!!!!!!!!!!!!!!!!!!!!!!!!!! ЗДЕСЬ
                // 1) проверить, доступен ли каталог dir? Если нет -> запустить FileWindowsDialog, потом рекурсивно вызвать modelListUpdate
                // 2) проверить, изменился ли MD5 и список Правил str? Если нет -> список моделей не переписываем, оставляем прежднюю дату
                // 3) читать ModelINFO / MD5 в файле, чтобы понять, нужно ли в него переписать модель (установить флаг wrToFile)

            }
            Log.exit();
            return mod;
        }
Esempio n. 10
0
        public static void txt(Severity type, string msgcode, object p0 = null, object p1 = null, object p2 = null)
        {
            Message msg = Messages.Find(x => x.MessageID == msgcode);

            if (msg == null)
            {
                log.Fatal("TSmatch internal Message system error: Message \n\t" + msgcode
                          + "\nnot foung in collection Messages."
                          + " Possibly Message system not initiated yet, or this message not listed in TSmatch.xlsx/Message");
                Log.FATAL("ERR_03 - Message Code Not Found");
            }
            string str = string.Format(msg.text, p0, p1, p2);

            mes(str, (int)type);

            //////bool ok = false;
            //////foreach (var v in Messages)
            //////{
            //////    if (v.MessageID == msgcode)
            //////    {
            //////        string s = String.Format(v.text, p0, p1, p2);
            //////        mes(s, (int)type);
            //////        ok = true;
            //////        break;
            //////    }
            ////////////////////}
            ////////////////////if (!ok)
            ////////////////////    if (Messages.Count > 0) F("ERR_03_NOMSG", msgcode);
            ////////////////////    else Log.FATAL("Internal ERROR: Message system is not initiated");
        }
Esempio n. 11
0
 public MainWindow()
 {
     Log.START(VERSION);
     InitializeComponent();
     new SplashScreen(VERSION).ShowDialog();
     MainWindowLoad();
 }
Esempio n. 12
0
        public Model UpdateFrTekla()
        {
            Log.set(@"UpdateFrTekla()");
            //            Elm.Elements = TS.Read();
            List <Elm> elements = TS.Read();

            new Log(@"Модель = " + TS.ModInfo.ModelName + "\t" + Elm.Elements.Count + " компонентов.");
            string mod_name  = TS.ModInfo.ModelName;
            string mod_dir   = TS.ModInfo.ModelPath;
            string mod_phase = TS.ModInfo.CurrentPhase.ToString();
            Model  mod       = modelListUpdate(mod_name, mod_dir, TS.MyName, Elm.ElementsMD5(), mod_phase);

            mod.elements = elements;
            if (mod.wrToFile)
            {
                mod.wrModel(Decl.TSMATCHINFO_RAW);
                mod.wrModel(Decl.TSMATCHINFO_MODELINFO);
                ////ElmGr.setGroups();            // Group Elements by Materials and Profile
                ////ElmMGr.setMgr();        // Additionally group Groups by Material
                setModel(mod.name);     // Load price-list for the model
//revision 2016.12.05                Mtch.UseRules(mod);     // Search for Model Groups matching Components
                mod.wrModel(Decl.TSMATCHINFO_REPORT);
                mod.wrModel(Decl.TSMATCHINFO_SUPPLIERS);
                saveModel(mod.name);    // а теперь запишем в Журнал Моделей обновленную информацию
            }
            else
            {
                new Log("------- Эта модель уже есть в TSmatch. Ничего не записываем --------");
            }
            Elm.Elements.Clear();
            mod.wrToFile = false;
            Log.exit();
            return(mod);
        } // end update
Esempio n. 13
0
        /// <summary>
        /// HeghlightElements(List<Elm>elements, color) - change color of elements in list 
        /// </summary>
        /// <param name="elements"></param>
        /// <param name="color"></param>
        public void HighlightElements(Dictionary<string, Elm> els, int color = 1)
        {
            Log.set("TS_OpenAPI.HighLightElements");
            TSM.ModelObjectSelector selector = model.GetModelObjectSelector();
            System.Type[] Types = new System.Type[1];
            Types.SetValue(typeof(Part), 0);

            TSM.ModelObjectEnumerator objectList = selector.GetAllObjectsWithType(Types);
            int totalCnt = objectList.GetSize();

            var colorObjects = new List<ModelObject>();

            while (objectList.MoveNext())
            {
                TSM.Part myPart = objectList.Current as TSM.Part;
                if (myPart != null)
                {
                    string guid = string.Empty;
                    myPart.GetReportProperty("GUID", ref guid);
                    if (els.ContainsKey(guid)) colorObjects.Add(myPart);
                }
            }
            var _color = new Color(0.0, 0.0, 1.0);
            ModelObjectVisualization.SetTransparencyForAll(TemporaryTransparency.SEMITRANSPARENT);
            ModelObjectVisualization.SetTemporaryState(colorObjects, _color);
            log.Info("\tTotal elements without price = " + colorObjects.Count);
            Log.exit();
        }
Esempio n. 14
0
 /// <summary>
 /// getDoc(name) - get Document name - when nor read yet - from the file. If necessary - Create new Sheet
 /// </summary>
 /// <param name="name">Document name</param>
 /// <param name="fatal">FATAL if this flag = true; else - return null if Document doesnt exists</param>
 /// <returns>Document or null</returns>
 /// <returns>Document</returns>
 /// <history> 25.12.2013 отлажено
 /// 25.12.2013 - чтение из файла, формирование Range Body
 /// 28.12.13 - теперь doc.Sheet и doc.Wb храним в структуре Документа
 /// 5.4.14  - инициализируем docDic, то есть подготавливаем набор данных для Fetch
 /// 22.12.15 - getDoc для нового документа - в Штампе он помечен N
 /// 6.1.16 - NOP если FiliDirectory содержит # - каталог Документа еще будет разворачиваться позже
 ///  5.3.16 - null if Document not found or exist
 /// 30.3.16 - get #template Path from Bootstrap.Template; try-catch rewritten
 ///  5.4.16 - bug fix - SheetReset for "N" Document
 /// 19.4.16 - use Templ.getPath in getDoc()
 /// 27.4.16 - optional flag load - if false -> don't load contents from the file
 /// </history>
 public static Document getDoc(string name = Decl.DOC_TOC, bool fatal = true, bool load = true)
 {
     Log.set("getDoc(" + name + ")");
     Document doc = null;
     string err = "Err getDoc: ", ex= "";
     try { doc = Documents[name]; }
     catch (Exception e) { err += "doc not in TOC"; ex = e.Message; doc = null; }
     if (doc != null && !doc.isOpen)
     {
         if (load)
         {
             if (doc.FileDirectory.Contains("#")) // #Template substitute with Path in Dictionary
                 doc.FileDirectory = Templates[doc.FileDirectory];
             //-------- Load Document from the file or create it ------------
             bool create = !string.IsNullOrEmpty(doc.type) && doc.type[0] == 'N' ? true : false;
             doc.Wb = FileOp.fileOpen(doc.FileDirectory, doc.FileName, create);
             try
             {
                 if (doc.type == Decl.DOC_TYPE_N) FileOp.SheetReset(doc.Wb, doc.SheetN);
                 doc.Sheet = doc.Wb.Worksheets[doc.SheetN];
             }
             catch (Exception e) { err += "no SheetN"; ex = doc.SheetN; doc = null; }
             if (create && doc != null) doc.Reset();
             else if (doc != null) doc.Body = FileOp.getSheetValue(doc.Sheet);
         }
     } // end if(!doc.isOpen)
     if(doc == null && fatal) Msg.F(err, ex, name);
     if(doc != null && doc.Body != null) doc.isOpen = true;
     Log.exit();
     return doc;
 }
Esempio n. 15
0
        public static Docs UpgradeFrExcel(Docs doc, string strToDo)
        {
            Log.set("UpgradeFrExcel(" + doc.name + ", " + strToDo + ")");
            if (strToDo != "DelEqPar1")
            {
                Log.FATAL("не написано!");
            }
//!!            List<string> Comp = getComp(doc);
            //////int i = doc.i0;
            //////foreach (string s in Comp)
            //////{
            //////    string str = Lib.ToLat(s);
            //////    List<int> pars = Mtch.GetPars(s);
            //////    if (pars[0] == pars[1])
            //////    {
            //////        string toDel = pars[0].ToString() + " x ";
            //////        str = str.Replace(toDel + toDel, toDel);
            //////    }
            //////    doc.Body[i++, 1] = str;
            //////}
            //////doc.isChanged = true;
            //////Docs.saveDoc(doc);

            //for (int i = doc.i0, iComp = 0; i <= doc.il; i++)
            //{
            //    // doc.Body.Strng(i, 1) = Copm;
            //}
            Log.exit();
            return(doc);
        }
Esempio n. 16
0
        /// <summary>
        /// Hndl(model) - find matching Components for model and total_price
        /// </summary>
        /// <param name="mod">model to be handled</param>
        public void Hndl(ref Mod mod)
        {
            Log.set("MH.Hndl");
            mod.elmGroups = getGrps(mod.elements);
            if (mod.elmGroups.Count < 1 || mod.Rules.Count < 1) Msg.F("No Rules or element Groups");
            if(testMode) { Log.exit(); return; }

            foreach (var rules in mod.Rules)
                if (rules.CompSet == null) rules.Init();
            // find matching Components with Rules by module Mtch 
            foreach (var gr in mod.elmGroups)
            {
                bool b = false;
                foreach (var rule in mod.Rules)
                {
                    Mtch _match = new Mtch(gr, rule);
                    if (_match.ok == Mtch.OK.Match)
                    {
                        mod.matches.Add(_match);
                        gr.CompSetName = _match.rule.sCS;
                        gr.SupplierName = _match.rule.sSupl;
                        gr.compDescription = _match.component.Str(Section.Section.SType.Description);
                        b = true; break;
                    }
                }
                if (!b) log.Info("No Match Group. mat= " + gr.mat + "\tprf=" + gr.prf);
            }
            // calculate prices for matches      
            mod.total_price = mod.elmGroups.Sum(x => x.totalPrice);
            mod.pricingDate = DateTime.Now;
            mod.pricingMD5 = mod.get_pricingMD5(mod.elmGroups);
            Log.Trace("price date=\t" + mod.pricingDate + "\tMD5=" + mod.pricingMD5);
            log.Info("Model.Hndl set " + mod.matches.Count + " groups. Total price=" + mod.total_price + " rub");
            Log.exit();
        }
Esempio n. 17
0
 //public void wrDoc(string form_name, params object[] objs)
 //{
 //    wrDoc(form_name, objs);
 //}
 ////////public void wrDoc(int iForm, object[] lst) // List<T> lst)
 ////////{
 ////////    Form frm = forms.Find(x => x.name == forms[iForm].name);
 ////////    string format_name = frm.name + "_F";
 ////////    if (!FileOp.isNamedRangeExist(Wb, format_name)) Msg.F("ERR __!!__.NOFORM_F", frm.name);
 ////////    object[] obj = new object[lst.Count];
 ////////    //!!-- fill obj[]
 ////////    wrDoc(frm.name, obj);
 ////////}
 ////public void wrDoc(string str)
 ////{
 ////    object[] t = { Lib.timeStr() };
 ////    wrDoc(str, t);
 ////    Body[1, 1] = t[0];
 ////}
 public void wrDoc(List<int> rows, List<int> cols, List<int> rFr, List<int> cFr)
 {
     Log.set("wrDoc(List rows, List cols, List rFr, List cFr)");
     Mtr tmpBody = FileOp.getSheetValue(this.Sheet);
     throw new NotImplementedException();
     Log.exit();
 }
Esempio n. 18
0
        private void getPricing()
        {
            Log.set("Models.getPricing()");
            int cnt = 0;
            var elms = new Dictionary<string, Elm>();
            foreach (var elm in elements) elms.Add(elm.guid, elm);
            foreach (var mgr in elmMgroups)
            {
                foreach (string id in mgr.guids)
                {
                    mgr.totalPrice += elms[id].price;
                }
                cnt += mgr.guids.Count();
            }

            var noPrice = new Dictionary<string, Elm>();
            foreach (var elm in elements)
            {
                if (elm.price == 0) noPrice.Add(elm.guid, elm);
            }
            ts.HighlightElements(noPrice);
#if TSM_Select
            Console.Write("\n\tPUSH ANY KEY => ");
            Console.ReadKey();
            ts.HighlightClear();
#endif
            Log.exit();
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            Log.START("TSmatch v2017.04.11");
            var bootstrap = new Bootstrap.Bootstrap();
            var model     = bootstrap.model;

            Test.Test.TSmatchTEST();

            model.Read();   // Read() - загружаем модель, последнюю по времени или ту, что в САПР
            model.Handler();
            model.Report();

            #region ----------- for future IFC testing ----------------
            //            model.Read("out.ifc");    // файл "out.ifc" создан Tekla Артемом Литвиновым только из стандартных элементов. IFC его не может прочитать
            //            model.Read("MyColumn.ifc");   // IFC не парсируется
            //--6.08.2016 model.Read("out.ifc")
            //model.Read("out3314.ifc");         // open most recent model - in Tekla, Excel File, or IFC file

            //            Supplier.SupplReport();

            //Docs doc = Docs.getDoc("Уголок Стальхолдинг??");
            //Cmp.UpgradeFrExcel(doc, "DelEqPar1");

            //6/8/16            Mod mod = Mod.UpdateFrTekla();
            //            Mtch.UseRules(mod);
            #endregion
//27/3            Console.ReadKey();
        }
Esempio n. 20
0
        /// <summary>
        /// IsTeklaActice() - return true if TeklaStructures Process exists in Windows, and model is available 
        /// </summary>
        /// <returns>true if Tekla is up and running</returns>
        public static bool isTeklaActive()
        {
            Log.set("isTeklaActive()");
            bool ok = false;
            const string Tekla = "TeklaStructures";
            foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.ToLower().Contains(Tekla.ToLower()))
                {
                    TSM.Model model = new TSM.Model();
                    if (!model.GetConnectionStatus()) goto error;
                    try
                    {
                        ModInfo = model.GetInfo();
                        ok = model.GetConnectionStatus() && ModInfo.ModelName != "";
                    }
                    catch { goto error; }
                    break;
                }
            }
            Log.exit();
            return ok;

            error: throw new Exception("isTeklaActive no model Connection");
        }
Esempio n. 21
0
        private static void testFP_testEqLst(FingerPrint fp)
        {
            Log.set("testFP_testEqLst");

            List<string> str1 = new List<string>();
            List<string> str2 = new List<string>();
            str1.Add("A"); str1.Add("B");
            str2.Add("A"); str2.Add("B"); str2.Add("C");


            TST.Eq(fp.EqLst(str1, str2), true);
            TST.Eq(fp.EqLst(str2, str1), true);
            str1.Add("XX");
            TST.Eq(fp.EqLst(str1, str2), false);

            str1.Clear();
            TST.Eq(fp.EqLst(str1, str2), true);
            str2.Clear();
            TST.Eq(fp.EqLst(str1, str2), true);

            str1.Add("xX");
            TST.Eq(fp.EqLst(str1, str2), true);
            str2.Add("X");
            TST.Eq(fp.EqLst(str1, str2), false);

            //-- test with int and double elements
            List<object> p1 = new List<object>();
            List<object> p2 = new List<object>();
            p1.Add(1); p2.Add("1");
            TST.Eq(fp.EqLst(p1, p2), true);
            p1.Add(2.58); p2.Add("2,58");
            TST.Eq(fp.EqLst(p1, p2), true);

            Log.exit();
        }
Esempio n. 22
0
        void test_Mtch_3()
        {
            Log.set(" test_Mtch_3: Rule 5 и Group < C235, Pl30 >");
            rule = new Rule.Rule(5);
            ElmAttSet.ElmAttSet elm = new ElmAttSet.ElmAttSet(
                "ID56A7442F-0000-0D74-3134-353338303236",
                "C235", "Steel", "Pl30", 0, 0, 0, 1001);
            Dictionary <string, ElmAttSet.ElmAttSet> els
                = new Dictionary <string, ElmAttSet.ElmAttSet>();

            els.Add(elm.guid, elm);
            List <string> guids = new List <string>(); guids.Add(elm.guid);
            var           model = new Model.Model();

            model.setElements(els);
            model.getGroups();
            var gr = model.elmGroups[0];
            //6/4/17           TST.Eq(gr.guids.Count, 1);
            //6/4/17           TST.Eq(gr.mat, "c235");
            //6/4/17TST.Eq(gr.prf, "pl30");
            var doc  = Docs.getDoc("Полоса СтальхолдингM");
            var csDP = new Dictionary <SType, string>();

//31/3            csFPs = rule.Parser(FP.type.CompSet, doc.LoadDescription);
// 2/4            Comp comp1 = new Comp(doc, 2, csDP);
// 2/4            Comp comp2 = new Comp(doc, 12, csDP);
// 2/4            List<Comp> comps = new List<Comp> { comp1, comp2 };
// 2/4            CS cs = new CS("test_CS", null, rule, doc.LoadDescription, comps);
// 2/4            TST.Eq(cs.csDP.Count, 4);

            //////////////////////////TST.Eq(comp1.isMatch(gr, rule), false);
            //////////////////////////TST.Eq(comp2.isMatch(gr, rule), true);
            Log.exit();
        }
Esempio n. 23
0
        /// <param name="fetch_rqst"></param>
        /// <example>FetchInit("SFacc/2:3")</example>
        public void FetchInit(string fetch_rqst)
        {
            Log.set("FetchInit(fetch_rqst)");
            try
            {
                if (string.IsNullOrEmpty(fetch_rqst)) { FetchInit(); return; }
                string[] ar_rqst = fetch_rqst.Split('/');
                if (!Documents.ContainsKey(ar_rqst[0])) Log.FATAL("нет такого Документа");
                string strFetch = ar_rqst[0] + "/" + ar_rqst[1];
                if (docDic.ContainsKey(strFetch)) return; // уже инициирован -> return
                Document doc = getDoc(ar_rqst[0]);
                string[] cols = ar_rqst[1].Split(':');
                int key = Lib.ToInt(cols[0]);
                int val = Lib.ToInt(cols[1]);
                Dictionary<string, string> keyDic = new Dictionary<string, string>();
                docDic.Add(strFetch, keyDic);
                DateTime t0 = DateTime.Now;
                for (int i = 1; i <= doc.Body.iEOL(); i++)
                {

                    string s1 = doc.Body.Strng(i, key);
                    if (s1 != "") try { keyDic.Add(s1, doc.Body.Strng(i, val)); }
                        catch
                        {
                            Log.Warning("Запрос \"" + fetch_rqst + " Строка " + i
                                + " неуникальное значение \"" + s1 + "\" в ключевом поле запроса!");
                        }
                }
                DateTime t1 = DateTime.Now;
                new Log("-> " + (t1 - t0));
            }
            catch { Log.FATAL("ошибка запроса \"" + fetch_rqst + "\" для Документа \"" + name + "\""); }
            finally { Log.exit(); }
        }
Esempio n. 24
0
 /// <summary>
 /// SetModel(boot) - initialize model by reading from TSmatchINFO.xlsx ans Raw.xml or from scratch
 /// </summary>
 /// <remarks>
 /// With unit_test_mode = true not full model initializing happened.
 /// It is used for testing methods are used on initialization stade.
 /// </remarks>
 /// <param name="boot"></param>
 /// <returns>initialized Model</returns>
 public Mod SetModel(Boot boot, bool initSupl = false)
 {
     Log.set("SR.Model(boot)");
     model = new Mod();
     SetModDir(boot);
     GetTSmatchINFO(model, initSupl);
     Log.exit();
     return model;
 }
Esempio n. 25
0
 /// <summary>
 /// Close([save_flag])   - Close document, save it when saveflag=true, default - false;
 /// </summary>
 /// <param name="save_flag">saveDoc if true. This case all rest parameters as in saveDoc</param>
 public void Close(bool save_flag = false, bool BodySave = true, string MD5 = "", int EOL = 0)
 {
     Log.set("Close(" + name + ")");
     if (save_flag) saveDoc(this, BodySave, MD5, EOL);
     this.isOpen = false;
     FileOp.DisplayAlert(false);
     try { this.Wb.Close(); }
     catch {  }
     FileOp.DisplayAlert(true);
     Log.exit();
 }
Esempio n. 26
0
 Form form;  // form set in wrDocSet
 internal void wrDocSetForm(string formName, int nStrBody = -1, bool AutoFit = false)
 {
     Log.set("wrDocSetForm");
     if (!Form.isFormExist(forms, formName)) Msg.F("Document.wrDoc no form", formName, this.name);
     form = Form.getFormByName(this, formName);
     form.AutoFit = AutoFit;
     Form.last_name = "";
     Form.nStr = nStrBody == -1 ? Body.iEOL() + 1 : nStrBody; // defualt nStr = Body.iEOL()+1
                                                              ///            Form.getFormByName(this, formName).AutoFit = AutoFit;
     Log.exit();
 }
Esempio n. 27
0
 public int elementsCount()
 {
     Log.set("TS_OpenAPI.elementsCount()");
     TSM.ModelObjectSelector selector = model.GetModelObjectSelector();
     System.Type[] Types = new System.Type[1];
     Types.SetValue(typeof(TSM.Part), 0);
     TSM.ModelObjectEnumerator objectList = selector.GetAllObjectsWithType(Types);
     Log.exit();
     int totalCnt = objectList.GetSize();
     return totalCnt;
 }
Esempio n. 28
0
        /// <summary>
        /// проверка, соответствует ли строка str набору синонимов и параметров
        /// !допустимы str без параметров; при этом pars == null
        /// !ограничение: str должен начинаться с непустого фрагмента текста, иначе Fatal Error
        /// </summary>
        /// <param name="str"></param>
        /// <param name="txs"></param>
        /// <param name="pars"></param>
        /// <returns></returns>
        /// <description> --- ОПИСАНИЕ ИДЕИ --------------------------
        /// Правило - это шаблон вида "tx1<par1>tx2<par2>"
        /// Правило уже разбрано в методе Rule.RuleParse, то есть на входе
        /// - str строка для обработки, она берется из прайс-листа или модели в САПР,
        /// - List<string> txts - список фрагментов текста, он
        /// - Dictionary<string,strins>pars -словарь параметров с еще не заполненными значениями,
        ///      то есть pars = { {{par.name},""},..,..}. isStrMatch заполняет pars.Values
        /// Разбор Правила и заполнение значений параметров в isStrMatch делается с применением
        /// технологии Regular Expression. Здесь использован код из Reverse String Format
        /// http://stackoverflow.com/questions/5346158/parse-string-using-format-template
        /// </description>
        //////////        internal bool isSectionMatch(string str, List<string> txs, ref Dictionary<string, string> pars)
        //////////        {
        //////////            bool ok = false;
        //////////            if (string.IsNullOrWhiteSpace(str)) goto Exit;
        //////////            string reg = "";
        //////////            foreach (var s in txs) reg += s + "*";
        //////////            ok = Regex.IsMatch(str, reg);
        //////////            if (!ok || pars == null) goto Exit;
        //////////            //-- fill pars.Values in Dictionary
        //////////            string pattern = "^" + Regex.Replace(reg, @"\*", "(.*?)") + "$";
        //////////            Regex r = new Regex(pattern);
        //////////            Match m = r.Match(str);
        //////////            string[] parNam = new string[pars.Keys.Count];
        //////////            pars.Keys.CopyTo(parNam, 0);
        ////////////            string[] parNam = pars.Keys.ToArray();
        //////////            if (parNam.Length != m.Groups.Count - 1) Msg.F("Err: inconsystant Rule text/parameters");
        //////////            pars.Clear();
        //////////            for (int i = 1; i < m.Groups.Count; i++)
        //////////            {
        //////////                string name = parNam[i - 1];
        //////////                string val = m.Groups[i].Value;
        //////////                val = val.Trim();
        //////////                pars.Add(name, val);
        //////////            }
        //////////Exit:       return ok;
        //////////        }
        /// <summary>
        /// isRuleMatch(group, rule) - check if rule could be applied with group of elements gr
        /// </summary>
        /// <desctiption>
        /// для TRUE нужно, чтобы Правило содержало Синонимы, допустимые для этой Группы.
        /// пустой список Синонимов означает "любое значение".
        /// если у элемента списка Синонимов есть параметры, их сопоставляют с данными Группы
        /// с помощью Регулярных выражений
        /// </desctiption>
        /// <param name="gr"></param>
        /// <param name="rule"></param>
        /// <returns>true if could be in match</returns>
        //////////////private bool isRuleMatch(ElmAttSet.Group gr, Rule.Rule rule)
        //////////////{
        //////////////    bool result = false;
        //////////////    throw new NotImplementedException();
        //////////////    return result;
        //////////////}

        #region ------ test Matcher -----
#if DEBUG
        internal static void testMtch()
        {
            Log.set("testMtch");
            Mtch mtch = new Mtch();

// 28/5            mtch.test_getSectionText();
// 28/5            mtch.test_isSectionMatch();
            //////////////////mtch.test_Mtch_1();
            //// 28/3 ////////mtch.test_Mtch_2();
            //////////////////mtch.test_Mtch_3();
            Log.exit();
        }
Esempio n. 29
0
 /// <summary>
 /// EOLstr(str) - return parsed string str into Int32, or return EOLinTOC, when str is EOL
 /// </summary>
 /// <returns>Int32 or EOLinTOC</returns>
 /// <history>20.3.2016</history>
 int EOLstr(string str)
 {
     Log.set("Document.Int(" + str + ")");
     int x = 0;
     if (!Int32.TryParse(str, out x))
     {
         if (this.type == "TSmatch") x = this.Sheet.UsedRange.Rows.Count;
         else if (str == "EOL") x = this.EOLinTOC;
     }
     Log.exit();
     return x;
 }
Esempio n. 30
0
 /// <summary>
 /// ReсentModel(List<Model> models) -- return most recent model in list
 /// </summary>
 /// <param name="models">model list</param>
 /// <returns>most recently saved Model in the list</returns>
 /// <history>
 /// 2016.11.21 - get RecentModel from TOC, not from memory
 /// </history>
 public Model ReсentModel(List<Model> models)
 {
     Log.set("ReсentModel");
     Model mod = null;
     if (models.Count > 0)
     {
         models.Sort();
         mod = models[0];
     }
     else mod = newModelOpenDialog(out models);
     Log.exit();
     return mod;
 }