예제 #1
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="jasonFilePath"></param>

        public DiagramFormat(string jasonFilePath)
        {
            // use 'Deserializing Partial JSON Fragments'
            JObject jObject;

            try
            {
                // Read JSON
                string text = HoUtil.ReadAllText(jasonFilePath);
                jObject = JObject.Parse(text);
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    $@"Can't read '{jasonFilePath}

Consider Resetting to factory settings
- File, Reset Factory Settings!!!'

{e}", @"Can't import Diagram Styles from Settings.json");
                return;
            }

            //----------------------------------------------------------------------
            // Deserialize "DiagramStyle", "DiagramObjectStyle",""DiagramLinkStyle"
            // get JSON result objects into a list
            DiagramStyleItems       = (List <DiagramStyleItem>)GetConfigurationStyleItems <DiagramStyleItem>(jObject, "DiagramStyle");
            DiagramObjectStyleItems = (List <DiagramObjectStyleItem>)GetConfigurationStyleItems <DiagramObjectStyleItem>(jObject, "DiagramObjectStyle");
            DiagramLinkStyleItems   = (List <DiagramLinkStyleItem>)GetConfigurationStyleItems <DiagramLinkStyleItem>(jObject, "DiagramLinkStyle");
            BulkElementItems        = (List <BulkElementItem>)GetConfigurationStyleItems <BulkElementItem>(jObject, "BulkItems");
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="jasonFilePath"></param>

        public ImportSetting(string jasonFilePath)
        {
            // use 'Deserializing Partial JSON Fragments'
            JObject jObject;

            try
            {
                // Read JSON
                string text = HoUtil.ReadAllText(jasonFilePath);
                jObject = JObject.Parse(text);
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    $@"Can't read '{jasonFilePath}

Consider Resetting to factory settings
- File, Reset Factory Settings!!!'

{e}", @"Can't import Chapter: 'Importer' from Settings.json");
                return;
            }

            //----------------------------------------------------------------------
            // Deserialize "DiagramStyle", "DiagramObjectStyle",""DiagramLinkStyle"
            // get JSON result objects into a list
            ImportSettings =
                (List <FileImportSettingsItem>)JasonHelper.GetConfigurationItems <FileImportSettingsItem>(
                    jObject, "Importer");
        }
        private int GetLineNumber(string file, string functionName)
        {
            string code  = HoUtil.ReadAllText(file);
            Regex  rx    = new Regex($@"\b{functionName}\b\s*\([^;{{}}]*;");
            Match  match = rx.Match(code);

            if (match.Success)
            {
                return(code.Take(match.Groups[0].Index).Count(c => c == '\n') + 1);
            }
            else
            {
                return(-1);
            }
        }
예제 #4
0
        public static string GetConnectionString(EA.Repository rep)
        {
            string s = rep.ConnectionString;

            if (s.Contains("DBType="))
            {
                return(s);
            }
            else
            {
                FileInfo f = new FileInfo(s);
                if (f.Length > 1025)
                {
                    return(s);
                }
                else
                {
                    return(HoUtil.ReadAllText(s));
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Deserialize Json settings into JObject.
        /// </summary>
        /// <param name="jsonFilePath"></param>
        /// <returns></returns>
        public static JObject DeserializeSettings(string jsonFilePath)
        {
            // use 'Deserializing Partial JSON Fragments'
            try
            {
                // Read JSON
                string text = HoUtil.ReadAllText(jsonFilePath);
                return(JObject.Parse(text));
            }
            catch (Exception e)
            {
                MessageBox.Show($@"Can't read '{jsonFilePath}!'

Consider resetting to Factory Settings.

{e}

",
                                @"Can't import 'setting.json'.");
                return(null);
            }
        }
        /// <summary>
        /// Generate provided Interface. All functions called from not component modules
        /// -
        /// </summary>
        /// <param name="db"></param>
        /// <param name="folderNameOfClass"></param>
        /// <param name="fileNamesOfClassTree"></param>
        /// <param name="allCompImplementations"></param>
        /// <returns></returns>
        private static DataTable ShowProvidedInterface(BROWSEVCDB db,
                                                       string folderNameOfClass,
                                                       IQueryable <string> fileNamesOfClassTree,
                                                       IEnumerable <ImplFunctionItem> allCompImplementations)
        {
            var compImplementations = (from f in allCompImplementations
                                       where f.FilePath.StartsWith(folderNameOfClass) || f.FilePath == ""
                                       select new
            {
                Imp = new ImplFunctionItem(f.Interface, f.Implementation, f.FilePath, "", f.LineStart),
                // Rx to find a call to function, should be fast, later detailed test
                // 'function('
                RxImplementation = new Regex($@"\b{f.Implementation}\s*\("),
                RxInterface = new Regex($@"\b{f.Interface}\s*\(")
            }).ToArray();

            // over all files except Class/Component Tree (files not part of component/class/sub folder)
            IQueryable <string> fileNamesCalledImplementation = (from f in db.Files
                                                                 where !fileNamesOfClassTree.Any(x => x == f.Name) &&
                                                                 (f.LeafName.ToLower().EndsWith(".c") || f.LeafName.ToLower().EndsWith(".cpp"))
                                                                 select f.Name).Distinct();

            foreach (var fileName in fileNamesCalledImplementation)
            {
                if (!File.Exists(fileName))
                {
                    MessageBox.Show($@"File:{Environment.NewLine}'{fileName}'{Environment.NewLine}{Environment.NewLine}Root:{Environment.NewLine}{_folderRoot}",
                                    @"Can't open implementation of provided interface, skip!!!");
                    continue;
                }
                // only files in implementation
                if (fileName.ToLower().Contains(_folderRoot.ToLower()))
                {
                    string code = HoService.DeleteComment(HoUtil.ReadAllText(fileName));
                    foreach (var f1 in compImplementations)
                    {
                        if (f1.RxImplementation.IsMatch(code) || f1.RxInterface.IsMatch(code))
                        {
                            Regex rx = f1.Imp.Implementation == f1.Imp.Interface
                                ? new Regex($@"^.*\b{f1.Imp.Implementation}\s*\([^}}{{;]*;", RegexOptions.Multiline)
                                : new Regex($@"^.*\b({f1.Imp.Implementation}|{f1.Imp.Interface})\s*\([^}}{{;]*;", RegexOptions.Multiline);

                            Match match = rx.Match(code);
                            while (match.Success)
                            {
                                // That's not an call to a function
                                if (match.Value.Trim().StartsWith("FUNC(") || match.Value.Trim().StartsWith("void ") || match.Value.Trim().StartsWith("static ") || match.Value.Trim().StartsWith("extern "))
                                {
                                    match = match.NextMatch();
                                    continue;
                                }

                                f1.Imp.FilePathCallee = fileName;
                                break;
                            }

                            //f1.Imp.FilePathCallee = fileName;
                        }
                    }
                }
            }
            // Sort: Function, FileName
            var outputList = (from f in compImplementations
                              orderby f.Imp.Interface, f.Imp.Implementation
                              select new
            {
                Interface = f.Imp.Interface,
                Implementation = f.Imp.Implementation == f.Imp.Interface ? "" : f.Imp.Implementation,
                FileName = f.Imp.FileName,
                FileNameCallee = f.Imp.FileNameCallee,
                // no root path
                FilePath = f.Imp.FilePath.Length > _folderRoot.Length ? f.Imp.FilePath.Substring(_folderRoot.Length) : "",
                FilePathCallee = f.Imp.FilePathCallee.Length > _folderRoot.Length ? f.Imp.FilePathCallee.Substring(_folderRoot.Length) : "",
                isCalled = f.Imp.IsCalled,
                LineStart = f.Imp.LineStart
            }).Distinct();

            return(outputList.ToDataTable());
        }
        /// <summary>
        /// Get all required Interfaces of Component (root folder of component)
        /// </summary>
        /// <param name="db"></param>
        /// <param name="folderNameOfClass"></param>
        /// <param name="filesPathOfClassTree"></param>
        /// <param name="allImplementations"></param>
        /// <returns></returns>
        private static DataTable ShowRequiredInterface(BROWSEVCDB db,
                                                       string folderNameOfClass,
                                                       IQueryable <string> filesPathOfClassTree,
                                                       IEnumerable <ImplFunctionItem> allImplementations)
        {
            // Estimate all possible function calls of passed files
            Regex rx = new Regex(@"(\b[A-Z]\w*_\w*)\s*\(", RegexOptions.IgnoreCase);
            List <CallFunctionItem> lFunctionCalls = new List <CallFunctionItem>();

            foreach (var file in filesPathOfClassTree)
            {
                // only files that are in source folder, no library files.
                if (file.ToLower().Contains(_folderRoot.ToLower()))
                {
                    string code  = HoService.DeleteComment(HoUtil.ReadAllText(file));
                    Match  match = rx.Match(code);
                    while (match.Success)
                    {
                        lFunctionCalls.Add(new CallFunctionItem(match.Groups[1].Value, file));
                        match = match.NextMatch();
                    }
                }
            }


            // ignore the following function names (beginning)
            string[] ignoreList =
            {
                "Rte_Read",     "Rte_Write",     "Rte_Invalidate",
                "L2A_Rte_Read", "L2A_Rte_Write", "L2A_Rte_Invalidate",
                "L2B_Rte_Read", "L2B_Rte_Write", "L2B_Rte_Invalidate",
                "L2C_Rte_Read", "L2C_Rte_Write", "L2C_Rte_Invalidate"
            };

            // filter only function implementation
            // - not current folder/subfolder (current component, required)
            // - not to ignore according to ignore list
            var filteredFunctions = (from f in lFunctionCalls
                                     join fAll in allImplementations on f.Function equals fAll.Implementation
                                     where (!fAll.FilePath.StartsWith(folderNameOfClass)) &&
                                     ignoreList.All(l => !f.Function.StartsWith(l)) // handle ignore list
                                     orderby fAll.Implementation
                                     select new
            {
                Interface = fAll.Interface,
                Implementation = fAll.Implementation,
                FilePathImplementation = fAll.FilePath,
                FilePathCallee = f.FilePath,     // no implementation available yet
                isCalled = false,
                LineStart = fAll.LineStart,
                LineEnd = fAll.LineEnd,
                ColumnEnd = fAll.ColumnEnd
            }).Distinct();


            // check if filtered functions are implemented
            List <ImplFunctionItem> filteredImplemtedFunctions = new List <ImplFunctionItem>();

            foreach (var f in filteredFunctions)
            {
                if (!File.Exists(f.FilePathImplementation))
                {
                    MessageBox.Show($"File:\r\n'{f.FilePathImplementation}'\r\n\r\nRoot:\r\n{_folderRoot}",
                                    "Can't open implementation of required interface, skip interface!!!");
                    continue;
                }
                string[] codeLines = File.ReadAllLines(f.FilePathImplementation);
                // declaration ends with ';'
                // implementation ends with '}'
                //codeLines[f.Line - 1].Dump();
                if (f.LineEnd > 0 && f.ColumnEnd > 0)
                {
                    string line = codeLines[f.LineEnd - 1];
                    if (line.Length > 0)
                    {
                        if (line.Substring(f.ColumnEnd - 1, 1) != ";")
                        {
                            filteredImplemtedFunctions.Add(new ImplFunctionItem(
                                                               f.Interface,
                                                               f.Interface == f.Implementation ? "" : f.Implementation,
                                                               // no root path
                                                               f.FilePathImplementation.Length > _folderRoot.Length ? f.FilePathImplementation.Substring(_folderRoot.Length) : "",
                                                               f.FilePathCallee.Length > _folderRoot.Length ? f.FilePathCallee.Substring(_folderRoot.Length): "",
                                                               f.LineStart));
                        }
                    }
                }
            }
            return(filteredImplemtedFunctions.ToDataTable());
        }
예제 #8
0
        /// <summary>
        /// Import and update Requirements. You can set EA ObjectType like "Requirement" or EA Stereotype like "FunctionalRequirement"
        /// </summary>
        /// async Task
        public override bool ImportForFile(string eaObjectType = "Requirement",
                                           string eaStereotype = "",
                                           string stateNew     = "",
                                           string stateChanged = "")
        {
            bool result = true;

            Rep.BatchAppend     = true;
            Rep.EnableUIUpdates = false;

            // Read xml file
            XElement xElFile;

            try
            {
                xElFile = XElement.Parse(HoUtil.ReadAllText(ImportModuleFile));
            }
            catch (Exception e)
            {
                Rep.BatchAppend     = false;
                Rep.EnableUIUpdates = true;
                MessageBox.Show($@"File: {ImportModuleFile}{Environment.NewLine}{Environment.NewLine}{e}", @"Can't import structured *.xml");
                return(false);
            }

            InitializeXmlStructTable(xElFile);

            // Go through hierarchy and store in DataTable
            var level    = 1;
            var children = xElFile.Descendants(xmlChildrenName).FirstOrDefault(); //.Dump();

            if (OutputChildren(children, level) == false)
            {
                return(false);
            }



            ReadEaPackageRequirements();
            CreateEaPackageDeletedObjects();

            Count        = 0;
            CountChanged = 0;
            CountNew     = 0;
            List <int> parentElementIdsPerLevel = new List <int> {
                0
            };
            int parentElementId = 0;
            int lastElementId   = 0;

            int oldLevel = 0;

            string notesColumn = _settings.AttrNotes ?? "";

            foreach (DataRow row in DtRequirements.Rows)
            {
                Count += 1;



                int objectLevel = Int32.Parse(row["Object Level"].ToString()) - 1;

                // Maintain parent ids of level
                // get parent id
                if (objectLevel > oldLevel)
                {
                    if (parentElementIdsPerLevel.Count <= objectLevel)
                    {
                        parentElementIdsPerLevel.Add(lastElementId);
                    }
                    else
                    {
                        parentElementIdsPerLevel[objectLevel] = lastElementId;
                    }
                    parentElementId = lastElementId;
                }

                if (objectLevel < oldLevel)
                {
                    parentElementId = parentElementIdsPerLevel[objectLevel];
                }

                oldLevel = objectLevel;

                string objectId  = CombineAttrValues(_settings.IdList, row, ShortNameLength);
                string alias     = CombineAttrValues(_settings.AliasList, row, ShortNameLength);
                string name      = CombineAttrValues(_settings.AttrNameList, row, ShortNameLength);
                string notes     = notesColumn != "" ? row[notesColumn].ToString() : row[1].ToString();
                string nameShort = name.Length > ShortNameLength?name.Substring(0, ShortNameLength) : name;

                // Check if requirement with Doors ID already exists
                bool isExistingRequirement = DictPackageRequirements.TryGetValue(objectId, out int elId);


                EA.Element el;
                if (isExistingRequirement)
                {
                    el = Rep.GetElementByID(elId);
                    if (el.Alias != alias ||
                        el.Name != nameShort ||
                        el.Notes != notes)
                    {
                        if (stateChanged != "")
                        {
                            el.Status = stateChanged;
                        }
                        CountChanged += 1;
                    }
                }
                else
                {
                    el = (EA.Element)Pkg.Elements.AddNew(name, "Requirement");
                    if (stateNew != "")
                    {
                        el.Status = stateNew;
                    }
                    CountChanged += 1;
                }


                el.Alias        = alias;
                el.Name         = name;
                el.Multiplicity = objectId;
                el.Notes        = notes;
                el.TreePos      = Count * 10;
                el.PackageID    = Pkg.PackageID;
                el.ParentID     = parentElementId;
                el.Type         = eaObjectType;
                el.Stereotype   = eaStereotype;

                el.Update();
                Pkg.Elements.Refresh();
                lastElementId = el.ElementID;

                // handle the remaining columns/ tagged values
                var cols = from c in DtRequirements.Columns.Cast <DataColumn>()
                           where !ColumnNamesNoTaggedValues.Any(n => n == c.ColumnName)
                           select new
                {
                    Name  = c.ColumnName,
                    Value = row[c].ToString()
                }

                ;


                // Update/Create Tagged value
                foreach (var c in cols)
                {
                    if (notesColumn != c.Name)
                    {
                        TaggedValue.SetUpdate(el, c.Name, c.Value ?? "");
                    }
                }
            }

            MoveDeletedRequirements();
            UpdatePackage(xElFile);

            Rep.BatchAppend     = false;
            Rep.EnableUIUpdates = true;
            Rep.ReloadPackage(Pkg.PackageID);
            return(result);
        }