/// <summary>
 /// Return true if Element is an Embedded Element Type. With the parameter
 /// 'alsoEmbeddedInterfaces' you can decide whether to use Required/Provide -Interface as embedded element
 /// - Port
 /// - Activity Parameter
 /// - Parameter
 /// - ExpansionNode
 /// - Pin
 /// - RequiredInterface Only if alsoEmbeddedInterfaces=true
 /// - ProvidedInterface Only if alsoEmbeddedInterfaces=true
 /// </summary>
 /// <param name="el"></param>
 /// <param name="rep"></param>
 /// <param name="alsoEmbeddedInterfaces">Handle Provided, Required Interface as Embedded</param>
 /// <returns>EA Version</returns>
 // ReSharper disable once UnusedMember.Global
 public static bool IsEmbeddedElement(this EA.Element el, Repository rep, bool alsoEmbeddedInterfaces = false)
 {
     if (el.ParentID == 0)
     {
         return(false);
     }
     if (alsoEmbeddedInterfaces)
     {
         return(el.Type == "Port" ||
                el.Type == "ActivityParameter" ||
                el.Type == "Parameter" ||
                el.Type == "ExpansionNode" ||
                el.Type == "ActionPin" ||
                el.Type == "RequiredInterface" ||
                el.Type == "ProvidedInterface");
     }
     else
     {
         if (el.Type == "ExpansionNode" && rep != null)
         {
             EA.Element elAction = rep.GetElementByID(el.ParentID);
             if (elAction.Type == "Action")
             {
                 return(false);
             }
         }
         return(el.Type == "Port" ||
                el.Type == "ActivityParameter" ||
                el.Type == "Parameter" ||
                el.Type == "ExpansionNode" ||
                el.Type == "ActionPin");
     }
 }
        /// <summary>
        /// Copy port to target element
        /// </summary>
        /// <param name="srcPort"></param>
        /// <param name="trgEl"></param>
        private void CopyPort(Element srcPort, Element trgEl)
        {
            bool    isUpdate = false;
            Element trgPort  = null;

            if (srcPort.Type != "Port")
            {
                return;
            }
            // check if port already exits

            foreach (Element p in trgEl.EmbeddedElements)
            {
                if (p.Name == srcPort.Name && p.Stereotype == srcPort.Stereotype)
                {
                    isUpdate = true;
                    trgPort  = p;
                    break;
                }
            }

            if (isUpdate == false)
            {
                string name       = srcPort.Name;
                string stereotype = srcPort.Stereotype;
                if (isUpdate == false)
                {
                    trgPort = (Element)trgEl.EmbeddedElements.AddNew(name, "Port");
                    trgEl.EmbeddedElements.Refresh();
                }
                trgPort.Stereotype = stereotype;
                trgPort.Update();
            }
        }
        /// <summary>
        /// Copy port to target element. It port exists it don't copy it. The Ports are locked against changes.
        /// Note: hoTools don't copy tagged values
        /// </summary>
        /// <param name="rep"></param>
        /// <param name="srcPort"></param>
        /// <param name="trgEl"></param>
        public static void CopyPort(EA.Repository rep, Element srcPort, Element trgEl)
        {
            bool isUpdated = false;

            if (srcPort.Type != "Port")
            {
                return;
            }
            // check if port already exits

            foreach (Element trgtPort in trgEl.EmbeddedElements)
            {
                // the target port already exists in source (Target Port PDATA3 contains ea_guid of source port the port is dependant from)
                if (srcPort.ElementGUID == trgtPort.MiscData[2])
                {
                    isUpdated = true;

                    break;
                }
            }
            // Source port isn't available in target Part
            if (isUpdated == false)
            {
                // Create new Port and set the properties according to source port
                var newPort = (Element)trgEl.EmbeddedElements.AddNew(srcPort.Name, "Port");
                trgEl.EmbeddedElements.Refresh();
                newPort.Stereotype   = srcPort.Stereotype;
                newPort.Notes        = srcPort.Notes;
                newPort.PropertyType = srcPort.PropertyType;
                newPort.Update();
                // Link Port to the source Port of property type
                HoUtil.SetElementPdata3(rep, newPort, srcPort.ElementGUID);
                //newPort.Locked = true;
            }
        }
        /// <summary>
        /// UpdateReqIf for an element. Handle for TV: Values or Macros like '=EA.GUID' and updating naming to Module prefix
        /// </summary>
        /// <param name="el"></param>
        /// <returns></returns>
        public bool RoundtripUpdateReqIfForElement(EA.Element el)
        {
            string     id = el.Multiplicity; //TaggedValue.GetTaggedValue(el, GetPrefixedTagValueName("Id"));
            SpecObject specObj;

            try
            {
                specObj = ReqIfDeserialized.CoreContent[0].SpecObjects.SingleOrDefault(x => x.Identifier == id);
            }
            catch (Exception e)
            {
                MessageBox.Show($@"File: '{ImportModuleFile}'
Module in ReqIF: '{_subModuleIndex}'

{e}", @"Error getting identifier from ReqIF");
                return(false);
            }

            if (specObj == null)
            {
                MessageBox.Show($@"File: '{ImportModuleFile}'
Module in ReqIF: '{_subModuleIndex}'", @"Error getting identifier from ReqIF");
                return(false);
            }

            return(ExportUpdateRoundTripAttributes(el, specObj));
        }
        /// <summary>
        /// Recursive update an element
        /// </summary>
        /// <param name="el"></param>
        /// <returns></returns>
        public bool RoundtripUpdateReqIfForElementRecursive(EA.Element el)
        {
            _count    += 1;
            _countAll += 1;
            // Check type and stereotype
            if (el.Type != Settings.ObjectType || el.Stereotype != Settings.Stereotype)
            {
                return(true);
            }
            if (!RoundtripUpdateReqIfForElement(el))
            {
                return(false);
            }


            if (el.Elements.Count > 0)
            {
                _level += 1;
                foreach (EA.Element childEl in el.Elements)
                {
                    if (!RoundtripUpdateReqIfForElementRecursive(childEl))
                    {
                        return(false);
                    }
                }

                _level -= 1;
            }

            return(true);
        }
        string _properties = ""; // the properties
        public Param(Repository rep, EA.Element parTrgt)
        {
            _rep     = rep;
            _parTrgt = parTrgt;

            // check if t_xref element is already present
            string query = @"SELECT XrefID As XREF_ID, description As DESCR
                            FROM  t_object  o inner JOIN t_xref x on (o.ea_guid = x.client)
                            where x.Name = 'CustomProperties' AND
                                  x.Type = 'element property' AND
                                  o.object_ID = " + _parTrgt.ElementID;


            string      str    = _rep.SQLQuery(query);
            XmlDocument XmlDoc = new XmlDocument();

            XmlDoc.LoadXml(str);

            // get existing t_xref and remember GUID/XrefID
            XmlNode xrefGUID = XmlDoc.SelectSingleNode("//XREF_ID");

            if (xrefGUID != null)
            {
                _xrefid = xrefGUID.InnerText;// GUID of xref

                // get description
                XmlNode xrefDESC    = XmlDoc.SelectSingleNode("//DESCR");
                string  _properties = null;
                if (xrefDESC != null)
                {
                    _properties = xrefDESC.InnerText;
                }
            }
        }
        private void ExecuteAddSingleRequirementToSpecIF()
        {
            object selectedItem;

            EAAPI.ObjectType objectType = _repository.GetTreeSelectedItem(out selectedItem);

            EAAPI.Element element = selectedItem as EAAPI.Element;

            ProjectDescriptor project = ExecuteSelectProject();

            if (project != null)
            {
                logger.Info("Integrating requirement " + element.Name + "...");
                Resource repositoryResource = _projectIntegrator.AddRequirementToSpecIF(_requirementMasterDataWriter, element, project.ID);

                if (repositoryResource == null)
                {
                    logger.Error("Error integrating requirement.");
                }
                else
                {
                    logger.Info("Finished.");
                }
            }
        }
Exemple #8
0
        public bool EA_OnContextItemDoubleClicked(EAAPI.Repository repository, string guid, EAAPI.ObjectType objectType)
        {
            bool result = false;

            if (objectType == EAAPI.ObjectType.otElement)
            {
                EAAPI.Element element = repository.GetElementByGuid(guid);

                ViewModelBase viewModel = null;

                viewModel = GetEditorViewModel(repository, element);

                if (viewModel != null)
                {
                    FMCElementPropertyWindow newAgentWindow = new FMCElementPropertyWindow();
                    newAgentWindow.DataContext = viewModel;
                    newAgentWindow.ShowDialog();
                    repository.AdviseElementChange(element.ElementID);
                    result = true;
                }
            }
            else if (objectType == EAAPI.ObjectType.otConnector)
            {
                EAAPI.Connector connector = repository.GetConnectorByGuid(guid) as EAAPI.Connector;
                if (connector != null && connector.Stereotype == "access type" && _mainViewModel != null)
                {
                    _mainViewModel.ShowConnectorDirectionDialogCommand.Execute(connector);
                    repository.AdviseConnectorChange(connector.ConnectorID);
                    result = true;
                }
            }
            return(result);
        }
Exemple #9
0
        public static string CreatePortStateID(EAAPI.Element port1, EAAPI.Element port2)
        {
            string result = "";

            string idString = "";

            if (port1.ElementID < port2.ElementID)
            {
                idString = port1.ElementGUID + port2.ElementGUID;
            }
            else
            {
                idString = port2.ElementGUID + port1.ElementGUID;
            }

            SHA1Managed sha1 = new SHA1Managed();

            byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(idString));

            result = string.Concat(hash.Select(b => b.ToString("x2")));

            result = "_" + result;

            return(result);
        }
        public SpecIfMetadata CreateMetaDataForDiagramObject(EAAPI.DiagramObject diagramObject,
                                                             EAAPI.Element element)
        {
            SpecIfMetadata result = new SpecIfMetadata();

            Shape shape = new Shape
            {
                Bounds            = new Bounds(),
                ResourceReference = new ResourceReference
                {
                    IdReference       = EaSpecIfGuidConverter.ConvertEaGuidToSpecIfGuid(element.ElementGUID),
                    RevisionReference = EaDateToRevisionConverter.ConvertDateToRevision(element.Modified)
                }
            };

            int recatangleWidth = (diagramObject.right - diagramObject.left);
            int rectangleHeight = (-diagramObject.bottom) - (-diagramObject.top);

            shape.Bounds.X      = diagramObject.left;
            shape.Bounds.Y      = (diagramObject.top * -1);
            shape.Bounds.Width  = recatangleWidth;
            shape.Bounds.Height = rectangleHeight;

            result.Shape = shape;

            return(result);
        }
Exemple #11
0
        private void DeleteWrongPortReferenceOfConnections(int originalElementID)
        {
            for (short connectorCount = 0; connectorCount < _referenceElement.EmbeddedElements.Count; connectorCount++)
            {
                EAAPI.Element embeddedElement = _referenceElement.EmbeddedElements.GetAt(connectorCount) as EAAPI.Element;
                if (embeddedElement.Type == "Port")
                {
                    for (short portCounter = 0; portCounter < embeddedElement.Connectors.Count; portCounter++)
                    {
                        EAAPI.Connector referencePortConnector = (EAAPI.Connector)embeddedElement.Connectors.GetAt(portCounter);

                        if (referencePortConnector.ClientID == embeddedElement.ElementID &&
                            referencePortConnector.SupplierID != embeddedElement.ElementID &&
                            referencePortConnector.Type == "Dependency" &&
                            referencePortConnector.Stereotype == "referenceOf")
                        {
                            EAAPI.Element referencedElement = _repository.GetElementByID(referencePortConnector.SupplierID);

                            if (referencedElement.Type == "Port" &&
                                referencedElement.ParentID == originalElementID)
                            {
                                // correct reference
                            }
                            else
                            {
                                logger.Info("Deleting wrong referenceOf connector.");
                                _repository.DeleteConnector(referencePortConnector);
                            }
                        }
                    }
                }
            }
        }
Exemple #12
0
        private ViewModelBase GetEditorViewModel(EAAPI.Repository repository, EAAPI.Element element)
        {
            ViewModelBase result = null;

            if (element.Stereotype == "agent")
            {
                result = new AgentPropertyViewModel(repository, element);
            }
            else if (element.Stereotype == "channel")
            {
                result = new ChannelPropertyViewModel(repository, element);
            }
            else if (element.Stereotype == "storage")
            {
                result = new StoragePropertyViewModel(repository, element);
            }
            else if (element.Stereotype == "human agent")
            {
                result = new HumanAgentPropertyViewModel(repository, element);
            }
            else if (element.Stereotype == "cloud")
            {
                result = new CloudPropertyViewModel(repository, element);
            }
            else if (element.Stereotype == "tool")
            {
                result = new ToolPropertyViewModel(repository, element);
            }
            else if (element.Stereotype == "explicitChannel")
            {
                result = new ChannelPropertyViewModel(repository, element);
            }

            return(result);
        }
Exemple #13
0
        private void SynchronizePortReferenceOfConnector(EAAPI.Element originalPort, EAAPI.Element referencePort)
        {
            for (short i = 0; i < referencePort.Connectors.Count; i++)
            {
                EAAPI.Connector con = (EA.Connector)referencePort.Connectors.GetAt(i);

                if (con.Type == "Dependency" &&
                    con.Stereotype == "referenceOf" &&
                    con.ClientID == referencePort.ElementID &&
                    con.SupplierID == originalPort.ElementID)
                {
                    return;
                }
            }

            // no match
            logger.Info("Adding referenceOf connector to port.");

            EAAPI.Connector newConnector = referencePort.AddConnector(originalPort, "Dependency");

            newConnector.Stereotype = "referenceOf";
            newConnector.Update();
            originalPort.Connectors.Refresh();
            referencePort.Connectors.Refresh();
        }
        public static void SynchronizeTaggedValues(EA.Repository rep)
        {
            // over all selected elements
            EaDiagram curDiagram = new EaDiagram(rep);

            if (curDiagram.Dia == null)
            {
                return;
            }
            int indexLast = curDiagram.SelElements.Count - 1;

            if (indexLast < 0)
            {
                return;
            }

            EA.Element elLast   = curDiagram.SelElements[0];
            string     stereoEx = "";



            // over all elements, skip first element because that is the property template
            for (int i = 1; i <= indexLast; i++)
            {
                // synchronize all stereotypes
                if (stereoEx != curDiagram.SelElements[i].StereotypeEx)
                {
                    stereoEx = curDiagram.SelElements[i].StereotypeEx;
                    TaggedValue.ElTagValue elTagValues = new TaggedValue.ElTagValue(elLast, stereoEx);
                    elTagValues.SyncTaggedValues(rep, curDiagram.SelElements[i]);
                }
            }
        }
 /// <summary>
 /// Set Tagged Value with 'Name' to a value. If tagged value doesn't exists a new one is created.
 /// </summary>
 /// <param name="el"></param>
 /// <param name="name"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static EA.TaggedValue SetTaggedValue(EA.Element el, string name, string value)
 {
     EA.TaggedValue tg = AddTaggedValue(el, name);
     tg.Value = value;
     tg.Update();
     return(tg);
 }
        private static void getElementContentFromEAObject(EA.Element eaElementObj, ElementVO elemvo)
        {
            List <AttributeVO>   retAttrList   = new List <AttributeVO>();
            List <MethodVO>      retMethList   = new List <MethodVO>();
            List <TaggedValueVO> retTagValList = new List <TaggedValueVO>();

            // attributesの読み込み
            foreach (EA.Attribute attrObj in eaElementObj.Attributes)
            {
                retAttrList.Add(getAttributeFromEAObject(attrObj));
            }

            foreach (EA.Method mthObj in eaElementObj.Methods)
            {
                retMethList.Add(getMethodFromEAObject(mthObj));
            }

            foreach (EA.TaggedValue tagvObj in eaElementObj.TaggedValues)
            {
                retTagValList.Add(getTaggedValueFromEAObject(tagvObj));
            }

            elemvo.attributes = retAttrList;
            elemvo.attributes.Sort();

            elemvo.methods = retMethList;
            elemvo.methods.Sort();

            elemvo.taggedValues = retTagValList;
            elemvo.taggedValues.Sort();
        }
        //DIAGRAM CONTENT
        public void Generate_otDiagram_content(EA.Repository m_Repository, string TOI_GUID, string SP_BaseURL,
                                               out List <string> listOfElements,
                                               out List <string> listOfElementsNames,
                                               out List <string> listOfLinks,
                                               out List <string> listOfLinkNames,
                                               out Dictionary <string, string> DiagramDictionary)
        {
            listOfElements      = new List <string>();
            listOfElementsNames = new List <string>();
            listOfLinks         = new List <string>();
            listOfLinkNames     = new List <string>();

            EA.Diagram DiagramToShow = (EA.Diagram)m_Repository.GetDiagramByGuid(TOI_GUID);



            //STORE DIAGRAM ELEMENTS
            for (short iDO = 0; iDO < DiagramToShow.DiagramObjects.Count; iDO++)
            {
                EA.DiagramObject MyDO = (EA.DiagramObject)DiagramToShow.DiagramObjects.GetAt(iDO);
                int        ID         = m_Repository.GetElementByID(MyDO.ElementID).ElementID;
                EA.Element MyEle      = (EA.Element)m_Repository.GetElementByID(ID);
                listOfElements.Add(MyEle.Name + "|" + MyEle.ObjectType + "|" + MyEle.ElementGUID);
                listOfElementsNames.Add(MyEle.Name);
            }



            //STORE DIAGRAM LINKS
            for (short iDO = 0; iDO < DiagramToShow.DiagramLinks.Count; iDO++)
            {
                EA.DiagramLink MyLink = (EA.DiagramLink)DiagramToShow.DiagramLinks.GetAt(iDO);
                int            ID     = m_Repository.GetConnectorByID(MyLink.ConnectorID).ConnectorID;

                EA.Connector con;

                try //Try and get the connector object from the repository
                {
                    con = (EA.Connector)m_Repository.GetConnectorByID(ID);
                    listOfLinks.Add(con.Name + "|" + con.ObjectType + "|" + con.ConnectorGUID);
                    listOfLinkNames.Add(con.Name);
                }
                catch { }
            }



            //JSON Content
            string DiagramURL = SP_BaseURL + "/" + DiagramToShow.Name + "|otDiagram|" + TOI_GUID;


            DiagramDictionary = new Dictionary <string, string>();
            DiagramDictionary.Add("Diagram Name", DiagramToShow.Name);
            DiagramDictionary.Add("Created Data", DiagramToShow.CreatedDate.ToString());
            DiagramDictionary.Add("Meta Type", DiagramToShow.MetaType);
            DiagramDictionary.Add("Notes", DiagramToShow.Notes);
            DiagramDictionary.Add("Package ID", DiagramToShow.PackageID.ToString());
            DiagramDictionary.Add("Big Preview", DiagramURL + "/BigPreview");
            DiagramDictionary.Add("Small Preview", DiagramURL + "/SmallPreview");
        }
Exemple #18
0
        void getElementFromEA( )
        {
            EA.Repository repo  = ProjectSetting.getEARepo();
            EA.ObjectType otype = repo.GetContextItemType();

            if (otype == EA.ObjectType.otElement)
            {
                // Code for when an element is selected
                EA.Element eaElemObj = (EA.Element)repo.GetContextObject();

                if (eaElemObj != null && (eaElemObj.Type == "Class" || eaElemObj.Type == "Enumeration"))
                {
                    ElementVO eaElement = ObjectEAConverter.getElementFromEAObject(eaElemObj);
                    textBoxElementName.Text = eaElement.name;
                    targetElement           = eaElement;
                }
                else
                {
                    textBoxElementName.Text = "(EA上でクラスを選択してください)";
                    targetElement           = null;
                }
            }
            else
            {
                textBoxElementName.Text = "(EA上でクラスを選択してください)";
                targetElement           = null;
            }
        }
        public static EA.Diagram CreateActivityCompositeDiagram(Repository rep, EA.Element act)
        {
            // create activity diagram beneath Activity
            var actDia = (EA.Diagram)act.Diagrams.AddNew(act.Name, "Activity");

            // update diagram properties
            actDia.ShowDetails = 0; // hide details
            // scale page to din A4

            actDia.StyleEx = actDia
                             .StyleEx
                             .Length > 0 ? actDia.StyleEx.Replace("HideQuals=0", "HideQuals=1") : "HideQuals=1;";
            // Hide Qualifier
            actDia.ExtendedStyle = actDia.ExtendedStyle.Length > 0 ? actDia.ExtendedStyle.Replace("ScalePI=0", "ScalePI=1") : "ScalePI=1;";
            actDia.Update();
            act.Diagrams.Refresh();

            // put the activity on the diagram
            Util.AddSequenceNumber(rep, actDia);
            var actObj = (EA.DiagramObject)actDia.DiagramObjects.AddNew("l=30;r=780;t=30;b=1120", "");

            actObj.ElementID = act.ElementID;
            actObj.Update();
            actDia.DiagramObjects.Refresh();

            // add default nodes (init/final)
            CreateDefaultElementsForActivity(rep, actDia, act);
            act.Elements.Refresh();
            actDia.DiagramObjects.Refresh();
            return(actDia);
        }
Exemple #20
0
        // ReSharper disable once UnusedMethodReturnValue.Global
        public static bool CreateCallAction(Repository rep, EA.Element action, Method method)
        {
            // add ClassifierGUID to target action
            string updateStr = @"update t_object set classifier_GUID = '" + method.MethodGUID +
                               "' where ea_guid = '" + action.ElementGUID + "' ";

            rep.Execute(updateStr);

            // set CallOperation
            string callOperationProperty = "@PROP=@NAME=kind@ENDNAME;@TYPE=ActionKind@ENDTYPE;@VALU=CallOperation@ENDVALU;@PRMT=@ENDPRMT;@ENDPROP;";
            Guid   g               = Guid.NewGuid();
            string xrefid          = "{" + g + "}";
            string insertIntoTXref = @"insert into t_xref 
                (XrefID,            Name,               Type,              Visibility, Namespace, Requirement, [Constraint], Behavior, Partition, Description, Client, Supplier, Link)
                VALUES('" + xrefid + "', 'CustomProperties', 'element property','Public', '','','', '',0, '" + callOperationProperty + "', '" + action.ElementGUID + "', null,'')";

            rep.Execute(insertIntoTXref);

            // Link Call Operation to operation
            g               = Guid.NewGuid();
            xrefid          = "{" + g + "}";
            insertIntoTXref = @"insert into t_xref 
                (XrefID,            Name,               Type,              Visibility, Namespace, Requirement, [Constraint], Behavior, Partition, Description, Client, Supplier, Link)
                VALUES('" + xrefid + "', 'MOFProps', 'element property','Public', '','','', 'target',0, '  null ', '" + method.MethodGUID + "', null,'')";
            //rep.Execute(insertIntoT_xref);

            return(true);
        }
        /// <summary>
        /// Run the delegates for Element and Diagram for the current element.
        /// - changeScope.Item   Only Element itself and Diagrams of element, not beneath element
        /// - changeScope...     Element and all beneath Element
        /// </summary>
        /// <param name="rep"></param>
        /// <param name="el"></param>
        /// <param name="setEl"></param>
        /// <param name="setDia"></param>
        /// <param name="parameterStrings"></param>
        /// <param name="changeScope"></param>
        public static void DoRecursiveEl(Repository rep, EA.Element el, SetElement setEl, SetDiagram setDia,
                                         string[] parameterStrings, ChangeScope changeScope)
        {
            // perform change for element
            setEl?.Invoke(rep, el, parameterStrings);

            // perform changes for diagrams beneath element
            foreach (EA.Diagram dia in el.Diagrams)
            {
                if (dia != null)
                {
                    setDia?.Invoke(rep, dia, parameterStrings);
                }
            }
            // only the item itself, no recursion
            if (changeScope == ChangeScope.Item)
            {
                return;
            }

            //run all elements
            foreach (EA.Element elTrgt in el.Elements)
            {
                DoRecursiveEl(rep, elTrgt, setEl, setDia, parameterStrings, changeScope);
            }
        }
        /// <summary>
        /// Create Tagged Value with 'Name'. It return the TaggedValue
        /// </summary>
        /// <param name="el"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static EA.TaggedValue CreateTaggedValue(EA.Element el, string name)
        {
            EA.TaggedValue tg = Add(el, name);
            tg.Update();

            return(tg);
        }
        //public static bool updateActionPin(EA.Repository rep, EA.Element el) {
        //    // get classifier (operation)
        //    EA.Method m = Util.getOperationFromCallAction(rep, el);

        //    // update action pins
        //    if (m != null)
        //    {
        //        foreach (EA.Parameter par in m.Parameters)
        //        {
        //            updateActionPinParameter(rep, m, el, par);
        //        }
        //    }
        //    return true;
        //}

        // ReSharper disable once UnusedMethodReturnValue.Global
        public static bool UpdateActionPinForElement(Repository rep, EA.Element el1)
        {
            if (el1.Type == "Action")
            {
                UpdateActionPinParameter(rep, el1);
                return(true);
            }
            if (el1.Type == "Class" | el1.Type == "Interface")
            {
                return(true);
            }
            foreach (EA.Element el in el1.Elements)
            {   // update parameter
                if (el.Type == "Action")
                {
                    UpdateActionPinParameter(rep, el);
                }
                if (el.Type == "Activity")
                {
                    UpdateActionPinForElement(rep, el);
                }
            }

            return(true);
        }
Exemple #24
0
        public List <Node> GetAllHierarchies()
        {
            List <Node> result = new List <Node>();

            EAAPI.Collection searchResult = _repository.GetElementsByQuery("SpecificationPackages", "");

            if (searchResult.Count > 0)
            {
                for (short counter = 0; counter < searchResult.Count; counter++)
                {
                    EAAPI.Element packageElement = searchResult.GetAt(counter) as EAAPI.Element;

                    EAAPI.Package package = _repository.GetPackageByGuid(packageElement.ElementGUID);

                    CachedDataProvider eaCacheDataProvider = new CachedDataProvider(_repository);

                    EADM.Element specificationPackageElement = eaCacheDataProvider.GetCachedSpecification(package);

                    Node rootNode = new Node();

                    ConvertEaDataToSpecifNodeRecursively(specificationPackageElement, rootNode);

                    result = rootNode.Nodes;
                }
            }

            return(result);
        }
Exemple #25
0
        private bool SynchronizeUmlItemTags(UML.Classes.Interfaces.Interface interfaceItem, ref string TagName, ref string TagValue, ref string TagNotes)
        {
            if (HasSterotype(C_ExtStereotypes.funptr, interfaceItem.stereotypes))
            {
                FunptrInterface funptr = new FunptrInterface(interfaceItem);
                string          defaultTypeSynonymsTag = interfaceItem.name;
                EA.Element      eaElem         = (interfaceItem as UTF_EA.ElementWrapper).WrappedElement;
                bool            changedElement = false;

                // Synchronize tagged values
                for (short i = 0; i < eaElem.TaggedValues.Count; ++i)
                {
                    EA.TaggedValue currentTag = eaElem.TaggedValues.GetAt(i) as EA.TaggedValue;
                    bool           changedTag = false;
                    switch (currentTag.Name)
                    {
                    case C_ExtTags.typeSynonyms:
                        if (currentTag.Value != defaultTypeSynonymsTag)
                        {
                            currentTag.Value = defaultTypeSynonymsTag;
                            changedTag       = true;
                        }
                        break;

                    case C_ExtTags.static_:
                        if ((currentTag.Value == "false") &&
                            !((interfaceItem.owner is UML.Classes.Kernel.Class) ||
                              (interfaceItem.owner is UML.Classes.Interfaces.Interface)))
                        {
                            TagValue   = "true";
                            changedTag = true;
                        }
                        break;
                    }
                    if (changedTag)
                    {
                        currentTag.Update();
                        eaElem.TaggedValues.Refresh();
                        changedElement = true;
                    }
                }

                // Synchronize element Alias
                string alias = funptr.GetAliasFromTags(TagName, TagValue);
                if (eaElem.Alias != alias)
                {
                    eaElem.Alias   = alias;
                    changedElement = true;
                }

                if (changedElement)
                {
                    eaElem.Update();
                }
                return(changedElement);
            }

            return(false);
        }
 public AutoCpp(EA.Repository rep, EA.Element component)
 {
     Rep        = rep;
     _component = component;
     // inventory from VC Code Database
     _files       = new Files(rep);
     _designFiles = new Files(rep);
 }
 public EAElementWrapper(EA.Connector con, Repository repository)
 {
     EA.Element client   = repository.GetElementByID(con.ClientID);
     EA.Element supplier = repository.GetElementByID(con.SupplierID);
     this.name       = con.Name + "(from: " + client.Name + " to: " + supplier.Name + ")";
     this.stereotype = con.Stereotype;
     this.type       = con.Type;
 }
 private void GetItemEl(EA.Element el)
 {
     _lElId.Add(el.ElementID);
     foreach (EA.Element elSub in el.Elements)
     {
         GetItemEl(elSub);
     }
 }
Exemple #29
0
        public static bool SetClassifierId(Repository rep, EA.Element el, string guid)
        {
            // add ClassifierGUID to target action
            string updateStr = @"update t_object set classifier_GUID = '" + guid +
                               "' where ea_guid = '" + el.ElementGUID + "' ";

            rep.Execute(updateStr);
            return(true);
        }
Exemple #30
0
        private void SynchronizeTaggedValues(EAAPI.Element originalElement, EAAPI.Element referenceElement)
        {
            for (short tagCount = 0; tagCount < originalElement.TaggedValues.Count; tagCount++)
            {
                EAAPI.TaggedValue taggedValue = originalElement.TaggedValues.GetAt(tagCount) as EAAPI.TaggedValue;

                referenceElement.SetTaggedValueString(taggedValue.Name, taggedValue.Value, false);
            }
        }
        static void CreateTypeDefStructFromText(Repository rep, Diagram dia, Package pkg, Element el, string txt)
        {
            Element elTypedef = null;


            // delete comment
            txt = DeleteComment(txt);

            bool update = false;
            bool isStruct = true;
            string elType = "Class";

            // find start
            string regex = @"[\s]*typedef[\s]+(struct|enum)[\s]*([^{]*){";
            Match match = Regex.Match(txt, regex);
            if (!match.Success) return;
            if (txt.Contains(" enum"))
            {
                elType = "Enumeration";
                isStruct = false;
            }
            txt = txt.Replace(match.Value, "");

            // find name
            regex = @"}[\s]*([^;]*);";
            match = Regex.Match(txt, regex);
            if (!match.Success) return;
            string name = match.Groups[1].Value.Trim();
            if (name == "") return;
            txt = txt.Remove(match.Index, match.Length);

            // check if typedef already exists
            int targetId = Util.GetTypeId(rep, name);
            if (targetId != 0)
            {
                elTypedef = rep.GetElementByID(targetId);
                update = true;
                for (int i = elTypedef.Attributes.Count - 1; i > -1; i = i - 1)
                {
                    elTypedef.Attributes.DeleteAt((short) i, true);
                }
            }


            // create typedef
            if (update == false)
            {
                if (el != null)
                {
                    // create class below element
                    if ("Interface Class Component".Contains(el.Type))
                    {
                        elTypedef = (Element) el.Elements.AddNew(name, elType);
                        el.Elements.Refresh();
                    }
                    else
                    {
                        MessageBox.Show(@"Can't create element below selected Element");
                    }
                }
                else // create class in package
                {
                    elTypedef = (Element) pkg.Elements.AddNew(name, elType);
                    pkg.Elements.Refresh();
                }
            }
            if (isStruct)
            {
                elTypedef.Stereotype = @"struct";
                EA.TaggedValue tag = TaggedValue.AddTaggedValue(elTypedef, "typedef");
                tag.Value = "true";
                tag.Update();
            }
            if (update == false)
            {
                elTypedef.Name = name;
                elTypedef.Update();
            }

            // add elements
            if (isStruct) CreateClassAttributesFromText(rep, elTypedef, txt);
            else CreateEnumerationAttributesFromText(rep, elTypedef, txt);

            if (update)
            {
                rep.RefreshModelView(elTypedef.PackageID);
                rep.ShowInProjectView(elTypedef);
            }
            else
            {
                // put diagram object on diagram
                int left = 0;
                int right = left + 200;
                int top = 0;
                int bottom = top + 100;
                //int right = diaObj.right + 2 * (diaObj.right - diaObj.left);
                rep.SaveDiagram(dia.DiagramID);
                string position = "l=" + left + ";r=" + right + ";t=" + top + ";b=" + bottom + ";";
                var diaObj = (DiagramObject) dia.DiagramObjects.AddNew(position, "");
                dia.DiagramObjects.Refresh();
                diaObj.ElementID = elTypedef.ElementID;
                diaObj.Update();
            }
            rep.ReloadDiagram(dia.DiagramID);
            dia.SelectedObjects.AddNew(elTypedef.ElementID.ToString(), elTypedef.ObjectType.ToString());
            dia.SelectedObjects.Refresh();
        }
        public static void CreateOperationFromText(Repository rep, Element el,
            string txt)
        {
            Method m = null;
            string functionName;
            string parameters = "";
            string functionType = "";
            int typeClassifier = 0;
            bool isStatic = false;
            // delete comment
            var leftover = DeleteComment(txt);


            // get function name
            string regex = @"[\s]+([a-zA-Z0-9_*]*)[\s]*\(";
            Match match = Regex.Match(leftover, regex, RegexOptions.Multiline);
            if (match.Success)
            {
                functionName = match.Groups[1].Value;
                leftover = leftover.Remove(match.Groups[1].Index, match.Groups[1].Length); // delete name
            }
            else
            {
                MessageBox.Show(txt, @"No function definition");
                return;
            }
            // get parameters
            regex = @"\(([^\)]*)\)";
            match = Regex.Match(leftover, regex, RegexOptions.Multiline);
            if (match.Success)
            {
                parameters = match.Groups[1].Value;
                leftover = leftover.Remove(match.Index, match.Length); // delete name
                //leftover = leftover.Replace(match.Value, "").Trim();
            }
            if (leftover.ToLower().Contains("static "))
            {
                isStatic = true;
                leftover = leftover.Replace("static ", "").Trim();
                leftover = leftover.Replace("STATIC ", "").Trim();
            }

            // get type
            string pointer = "";
            if (leftover.Contains("*"))
            {
                pointer = "*";
                leftover = leftover.Replace("*", "").Trim();
            }
            leftover = leftover.Trim();
            regex = @"[a-zA-Z_0-9*]*$";
            match = Regex.Match(leftover, regex, RegexOptions.Multiline);
            if (match.Success)
            {
                functionType = match.Value + pointer;
                // get classifierID of type
                typeClassifier = Util.GetTypeFromName(rep, ref functionName, ref functionType);
                if (typeClassifier == 0 & functionType.Contains("*"))
                {
                    functionType = functionType.Remove(functionName.IndexOf("*", StringComparison.Ordinal), 1);
                    functionName = "*" + functionName;
                    typeClassifier = Util.GetTypeId(rep, functionType);
                    if (typeClassifier == 0 & functionType.Contains("*"))
                    {
                        functionType = functionType.Replace("*", "");
                        functionName = "*" + functionName;
                        typeClassifier = Util.GetTypeId(rep, functionType);
                    }
                }
            }
            // create function if not exists, else update function
            bool isNewFunctions = true;
            foreach (Method m1 in el.Methods)
            {
                if (m1.Name == functionName)
                {
                    isNewFunctions = false;
                    m = m1;
                    // delete all parameters
                    for (short i = (short) (m.Parameters.Count - 1); i >= 0; i--)
                    {
                        m.Parameters.Delete(i);
                        m.Parameters.Refresh();
                    }
                }
            }

            if (isNewFunctions)
            {
                m = (Method) el.Methods.AddNew(functionName, "");
                m.Pos = el.Methods.Count + 1;
                el.Methods.Refresh();
            }
            m.ReturnType = functionType;
            m.ClassifierID = typeClassifier.ToString();
            // static
            m.IsStatic = isStatic;
            m.Visibility = el.Type.Equals("Interface") ? "public" : "private";
            m.Update();


            el.Methods.Refresh();
            string[] lpar = parameters.Split(',');


            int pos = 1;
            foreach (string para in lpar)
            {
                string par = para.Trim();
                if (par == "void" | par == "") continue;
                bool isConst = false;
                if (par.Contains(@"const"))
                {
                    isConst = true;
                    par = par.Replace(@"const", "");
                }
                pointer = "";
                if (par.IndexOf("*", StringComparison.Ordinal) > -1)
                {
                    pointer = "*";
                    par = par.Remove(par.IndexOf("*", StringComparison.Ordinal), 1);
                    if (par.IndexOf("*", StringComparison.Ordinal) > -1)
                    {
                        pointer = "**";
                        par = par.Remove(par.IndexOf("*", StringComparison.Ordinal), 1);
                    }
                }
                par = Regex.Replace(par.Trim(), @"[\s]+", " ");
                string[] lparElements = par.Split(' ');
                if (lparElements.Length != 2)
                {
                    MessageBox.Show(txt, @"Can't evaluate parameters");
                    return;
                }
                string name = lparElements[lparElements.Length - 1];
                string type = lparElements[lparElements.Length - 2] + pointer;

                // get classifier ID
                var classifierId = Util.GetTypeFromName(rep, ref name, ref type);

                var elPar = (Parameter) m.Parameters.AddNew(name, "");
                m.Parameters.Refresh();
                elPar.IsConst = isConst;

                elPar.Type = type;
                elPar.Kind = "in";
                elPar.Position = pos;
                elPar.ClassifierID = classifierId.ToString();

                try
                {
                    elPar.Update();
                }
                catch (Exception e)
                {
                    MessageBox.Show($"{e}\n\n {elPar.GetLastError()}", $"Error creating parameter: {type} {name}");
                }
                pos = pos + 1;
            }
        }
 private static void CreateActivityForOperationsInElement(Repository rep, Element el)
 {
     if (el.Locked) return;
     Package pkg = rep.GetPackageByID(el.PackageID);
     int treePos = pkg.Packages.Count + 1;
     foreach (Method m1 in el.Methods)
     {
         // Create Activity
         ActivityPar.CreateActivityForOperation(rep, m1, treePos);
         treePos = treePos + 1;
     }
 }
        static void CreateClassAttributesFromText(Repository rep, Element el, string txt)
        {
            // delete comment
            txt = DeleteComment(txt);

            // delete macro's like #if, #else, #end,..
            txt = Regex.Replace(txt, @"^[\s]*(#[\s]*if|#[\s]*else|#[\s]*end)[^\n]*\n", "", RegexOptions.Multiline);


            // get all lines
            string[] lines = Regex.Split(txt, "\r\n");
            //string[] lines = Regex.Split(txt, ";");
            string stereotype = "";
            string part1 = "";
            foreach (string s in lines)
            {
                string sRaw = part1 + " " + s.Trim();
                if (sRaw == "") continue;
                //sRaw = sRaw + ";";
                bool isConst = false;
                bool isStatic = false;
                string pointerValue = "";
                // remove everything behind ";"
                var pos = sRaw.IndexOf(";", StringComparison.Ordinal);
                if (pos >= 0 & pos >= sRaw.Length) sRaw = sRaw.Substring(pos + 1);


                // remove everything behind "//"
                sRaw = Regex.Replace(sRaw, @"//.*", "");
                // remove everything behind "/*"
                sRaw = Regex.Replace(sRaw, @"/\*.*", "");
                sRaw = sRaw.Trim();
                if (sRaw == "") continue;
                sRaw = CallOperationAction.RemoveCasts(sRaw);


                if (sRaw.Equals("")) continue;
                if (sRaw.Contains("#") && sRaw.Contains("define"))
                {
                    CreateMacro(rep, el, sRaw, stereotype);
                    continue;
                }

                //-----------------------------------------------------------------------------
                // attributes
                // remove macros
                sRaw = Regex.Replace(sRaw, @"[\s]*#[^$]*", "");

                string name;
                string prefix = "";
                string defaultValue = "";
                string collectionValue = "";
                EA.Attribute a = null;
                // Attributes over more than one line
                if (sRaw.Contains(";") || sRaw.Contains("MODULE_NAME("))
                {
                    part1 = "";
                }
                else
                {
                    part1 = part1 + " " + sRaw;
                    continue;
                }

                // Module-Name
                string regexModuleName = @"(MODULE_NAME)(\([^)]*\))";
                Match match = Regex.Match(sRaw, regexModuleName);
                if (match.Success)
                {
                    name = match.Groups[1].Value;
                    defaultValue = match.Groups[2].Value;
                    a = (EA.Attribute) el.Attributes.AddNew(name + defaultValue, "");
                    a.IsConst = isConst;
                    if (el.Type.Equals("Class")) a.Visibility = "Private";
                    else a.Visibility = "Public";

                    a.Pos = el.Attributes.Count + 1;
                    if (!stereotype.Contains("")) a.Stereotype = stereotype;
                    a.IsStatic |= prefix.ToLower().Contains("static");
                    a.Update();
                    continue;
                }

                pos = sRaw.IndexOf("*", StringComparison.Ordinal);
                if (pos > -1)
                {
                    sRaw = sRaw.Remove(pos, 1);
                    pointerValue = "*";
                }
                pos = sRaw.IndexOf("*", StringComparison.Ordinal);
                if (pos > -1)
                {
                    sRaw = sRaw.Remove(pos, 1);
                    pointerValue = "**";
                }

                isConst |= sRaw.Contains(@"const");
                isStatic |= sRaw.ToLower().Contains("static");


                string sCompact = sRaw.Replace("*", "");
                sCompact = sCompact.Replace(@"const", "");
                sCompact = sCompact.Replace(@"static ", "");
                sCompact = sCompact.Replace("STATIC ", "");

                // get name


                // get default value
                string regexDefault = @"=[\s]*([\(\)a-zA-Z0-9_ *+-{}\%]*)";
                match = Regex.Match(sCompact, regexDefault);
                if (match.Success)
                {
                    defaultValue = match.Groups[1].Value.Trim();
                    sCompact = sCompact.Remove(match.Groups[1].Index, match.Groups[1].Length);
                    sCompact = sCompact.Replace("=", "");
                    if (!sCompact.EndsWith(";", StringComparison.Ordinal)) sCompact = sCompact + ";";
                }


                // get array
                //string regexArray = @"(\[[^;]*);";
                string regexArray = @"(\[[()A-Za-z0-9\]\[_ +-]*)";
                match = Regex.Match(sCompact, regexArray);
                if (match.Success)
                {
                    collectionValue = match.Groups[1].Value.Trim();
                    sCompact = sCompact.Remove(match.Groups[1].Index, match.Groups[1].Length);
                    if (!sCompact.EndsWith(";", StringComparison.Ordinal)) sCompact = sCompact + ";";
                }


                string regexName = @"[\s]*([a-zA-Z_0-9]+)[\s]+([a-zA-Z_0-9:]+)[\s]*[\[;]";
                match = Regex.Match(sCompact, regexName);
                if (match.Success)
                {
                    name = match.Groups[2].Value.Trim();
                    var type = match.Groups[1].Value.Trim();
                    sCompact = sCompact.Remove(match.Groups[2].Index, match.Groups[2].Length); // delete name
                    sCompact = sCompact.Remove(match.Groups[1].Index, match.Groups[1].Length); // delete type
                    sCompact = sCompact.Replace(";", ""); // ;
                    prefix = sCompact.Trim();


                    // add attribute
                    string aName = prefix + " " + pointerValue + name;
                    aName = aName.Trim();
                    bool isNewAttribute = true;
                    foreach (EA.Attribute attr in el.Attributes)
                    {
                        if (attr.Name == aName)
                        {
                            a = attr;
                            isNewAttribute = false;
                            break;
                        }
                    }

                    if (isNewAttribute)
                    {
                        a = (EA.Attribute) el.Attributes.AddNew(aName, "");
                        if (a.Name.Length > 255)
                        {
                            MessageBox.Show($"{a.Name} has {a.Name.Length}", @"Name longer than 255");
                            continue;
                        }
                        a.Pos = el.Attributes.Count + 1;
                        el.Attributes.Refresh();
                    }

                    a.Type = type;
                    a.IsConst = isConst;
                    a.Default = defaultValue;
                    a.ClassifierID = Util.GetTypeId(rep, type);
                    if (el.Type.Equals("Class")) a.Visibility = "Private";
                    else a.Visibility = "Public";
                    if (!collectionValue.Equals(""))
                    {
                        a.IsCollection = true;
                        a.Container = collectionValue;
                        if (collectionValue.Length > 50)
                        {
                            MessageBox.Show(
                                $"Collection '{collectionValue}' has {collectionValue.Length}  characters.",
                                @"Break! Collection length need to be <=50 characters");
                            continue;
                        }
                    }
                    if (!stereotype.Contains("")) a.Stereotype = stereotype;
                    a.IsStatic = isStatic;
                    try
                    {
                        a.Update();
                        el.Attributes.Refresh();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.ToString(), @"Error updating attribute");
                    }
                }
                else
                {
                    MessageBox.Show($"{s}\n\n+{sCompact}", @"Couldn't understand attribute syntax");
                }
            }
        }
        static void AddInterfaceToElement(Repository rep, int pos, Element elSource, Element elTarget, Diagram dia,
            DiagramObject diaObjSource)
        {
            // check if interface already exists on diagram

            var diaObjTarget = Util.GetDiagramObjectById(rep, dia, elTarget.ElementID);
            //diaObjTarget = dia.GetDiagramObjectByID(elTarget.ElementID, "");
            if (diaObjTarget == null)
            {
                int length = 250;
                //if (elTarget.Type != "Interface") length = 250;
                // calculate target position
                // int left = diaObjSource.right - 75;
                int left = diaObjSource.right;
                int right = left + length;
                int top = diaObjSource.bottom - 25;

                top = top - 20 - pos*70;
                var bottom = top - 50;
                string position = "l=" + left + ";r=" + right + ";t=" + top + ";b=" + bottom + ";";


                // create target diagram object
                diaObjTarget = (DiagramObject) dia.DiagramObjects.AddNew(position, "");

                diaObjTarget.ElementID = elTarget.ElementID;
                diaObjTarget.Sequence = 1;
                // suppress attributes/operations
                diaObjTarget.Style =
                    "DUID=1263D775;AttPro=0;AttPri=0;AttPub=0;AttPkg=0;AttCustom=0;OpCustom=0;PType=0;RzO=1;OpPro=0;OpPri=0;OpPub=0;OpPkg=0;";
                diaObjTarget.Update();
            }
            // connect source to target by Usage

            // make a connector/ or link if notes
            // check if connector already exists
            Connector con;
            foreach (Connector c in elSource.Connectors)
            {
                if (c.SupplierID == elTarget.ElementID &
                    (c.Type == "Usage" | c.Stereotype == "use" |
                     c.Type == "Realisation")) return;
            }


            if (elTarget.Type.Equals("Interface"))
            {
                con = (Connector) elSource.Connectors.AddNew("", "Usage");
            }
            else
            {
                con = (Connector) elSource.Connectors.AddNew("", "NoteLink");
            }
            con.SupplierID = elTarget.ElementID;
            try
            {
                con.Update();
                elSource.Connectors.Refresh();
                elTarget.Connectors.Refresh();
                // set line style
                dia.DiagramLinks.Refresh();
                //rep.ReloadDiagram(dia.DiagramID);
                foreach (DiagramLink link in dia.DiagramLinks)
                {
                    if (link.ConnectorID == con.ConnectorID)
                    {
                        Util.SetLineStyleForDiagramLink("LV", link);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), $"Error create connector between '{elSource.Name}  and '{elTarget.Name}' ");
            }
        }
 static void LocateOperationFromBehavior(Repository repository, Element el, DisplayMode showBehavior)
 {
     Method method = Util.GetOperationFromBrehavior(repository, el);
     if (method != null)
     {
         if (showBehavior.Equals(DisplayMode.Behavior))
         {
             Appl.DisplayBehaviorForOperation(repository, method);
         }
         else
         {
             repository.ShowInProjectView(method);
         }
     }
 }
 private void DelPort(Element port)
 {
     Element el = _rep.GetElementByID(port.ParentID);
     for (int i = 0; i < el.EmbeddedElements.Count; i++)
     {
         var p1 = (Element)el.EmbeddedElements.GetAt((short)i);
         if (p1.ElementID == port.ElementID)
         {
             el.EmbeddedElements.Delete((short)i);
             el.EmbeddedElements.Refresh();
         }
     }
 }
 static void ChangeAuthorElement(Repository rep, Element el, string[] args)
 {
     el.Author = args[0];
     el.Update();
 }
        // ReSharper disable once UnusedParameter.Local
        static void CreateEnumerationAttributesFromText(Repository rep, Element el, string txt)
        {
            // delete comment
            txt = DeleteComment(txt);


            // check for (with or without comma):
            // abc = 5 ,           or
            // abc  ,
            string regexEnum = @"([a-zA-Z_0-9]+)[\s]*(=[\s]*([a-zA-Z_0-9| ]+)|,|$)";
            Match match = Regex.Match(txt, regexEnum, RegexOptions.Multiline);
            int pos = 0;
            while (match.Success)
            {
                var a = (EA.Attribute) el.Attributes.AddNew(match.Groups[1].Value, "");
                // with/without default value
                if (match.Groups[2].Value != ",") a.Default = match.Groups[3].Value;
                a.Stereotype = "enum";
                a.Pos = pos;
                a.Update();
                el.Attributes.Refresh();
                pos = pos + 1;
                match = match.NextMatch();
            }
        }
        /// <summary>
        /// Copy port to target element
        /// </summary>
        /// <param name="srcPort"></param>
        /// <param name="trgEl"></param>
        private void CopyPort(Element srcPort, Element trgEl)
        {
            bool isUpdate = false;
            Element trgPort = null;
            if (srcPort.Type != "Port") return;
            // check if port already exits
            
            foreach (Element p in trgEl.EmbeddedElements)
            {
                if (p.Name == srcPort.Name && p.Stereotype == srcPort.Stereotype)
                {
                    isUpdate = true;
                    trgPort = p;
                    break;
                }
            }

            if (isUpdate == false)
            {
                string name = srcPort.Name;
                string stereotype = srcPort.Stereotype;
                if (isUpdate == false)
                {
                    trgPort = (Element)trgEl.EmbeddedElements.AddNew(name, "Port");
                    trgEl.EmbeddedElements.Refresh();
                }
                trgPort.Stereotype = stereotype;
                trgPort.Update();
            }

        }
 private static bool IsTaggedValuesComplete(Element el)
 {
     bool isRevision = false;
     bool isDate = false;
     foreach (EA.TaggedValue tag in el.TaggedValues)
     {
         isRevision |= tag.Name == "svnRevision";
         isDate |= tag.Name == "svnDate";
     }
     if (isRevision & isDate) return true;
     return false;
 }
 /// <summary>
 /// Split / delete the connection of two elements
 /// </summary>
 /// <param name="srcEl">Source element of the connector</param>
 /// <param name="trgEl">Target element of the connector</param>
 /// <param name="connectorType">Connector type or default "All"</param>
 /// <param name="direction">Direction of connection ("in","out","all" or default "All"</param>
 static void SplitElementsByConnectorType(Element srcEl, Element trgEl, string connectorType = "all",
     string direction = "all")
 {
     for (int i = srcEl.Connectors.Count - 1; i >= 0; i = i - 1)
     {
         var con = (Connector) srcEl.Connectors.GetAt((short) i);
         if (con.SupplierID == trgEl.ElementID &&
             (con.Type == connectorType | connectorType == "all" | direction == "all" | direction == "in"))
         {
             srcEl.Connectors.DeleteAt((short) i, true);
         }
         if (con.ClientID == trgEl.ElementID &&
             (con.Type == connectorType | connectorType == "all" | direction == "all" | direction == "out"))
         {
             srcEl.Connectors.DeleteAt((short) i, true);
         }
     }
 }
 static string AddReleaseInformation(Repository rep, Element el)
 {
     string txt;
     string path = Util.GetGenFilePath(rep, el);
     if (path == "")
     {
         MessageBox.Show($"No file defined in property for: '{el.Name}': {el.Type}");
         return "";
     }
     try
     {
         txt = System.IO.File.ReadAllText(path);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString(), @"Error Reading file '" + el.Name + @"':" + el.Type);
         return "";
     }
     string extension = ".c";
     if (el.Type == "Interface") extension = ".h";
     string name = el.Name + extension;
     if (name.Length > 58) name = name + "   ";
     else name = name.PadRight(60);
     return name + GetReleaseInformationFromText(txt);
 }
 static void UpdateActivityParameterForElement(Repository rep, Element el)
 {
     foreach (Method m in el.Methods)
     {
         Element act = Appl.GetBehaviorForOperation(rep, m);
         if (act == null) continue;
         if (act.Locked) continue;
         ActivityPar.UpdateParameterFromOperation(rep, act, m); // get parameters from Operation for Activity
     }
     foreach (Element elSub in el.Elements)
     {
         UpdateActivityParameterForElement(rep, elSub);
     }
 }
 private void RemovePortFromDiagram(Diagram dia, Element port)
 {
     for (int i= dia.DiagramObjects.Count-1; i>=0;i-=1)
     {
         var obj = (DiagramObject)dia.DiagramObjects.GetAt((short) i);
         if (obj.ElementID == port.ElementID)
         {
             dia.DiagramObjects.Delete((short)i);
             dia.DiagramObjects.Refresh();
             break;
         } 
     }
    
 }
 private static DiagramObject GetDiagramObjectFromElement(Element el, Diagram dia)
 {
     // get the position of the Element
     DiagramObject diaObj = null;
     foreach (DiagramObject dObj in dia.DiagramObjects)
     {
         if (dObj.ElementID == el.ElementID)
         {
             diaObj = dObj;
             break;
         }
     }
     return diaObj;
 }
        public void ConnectPortsOf2Classes(Element srcEl, Element trgtEl)
        {
            foreach (Element srcPort in srcEl.EmbeddedElements)
            {
                foreach (Element trgtPort in trgtEl.EmbeddedElements)
                {
                    // don't connect to itself
                    if (srcPort.Name == trgtPort.Name && srcPort.ElementID != trgtPort.ElementID)
                    {
                        //if (srcPort.Stereotype != trgtEl.Stereotype)
                        //{
                        //    // only connect:
                        //    // sender to receiver
                        //    // client to server
                        //    // check if connection already exists
                        //    if (srcPort.Stereotype == "Sender")
                        //        if (trgtPort.Stereotype != "Receiver") continue;
                        //    if (srcPort.Stereotype == "Receiver")
                        //        if (trgtPort.Stereotype != "Sender") continue;
                        //    if (srcPort.Stereotype == "Client")
                        //        if (trgtPort.Stereotype != "Server") continue;
                        //    if (srcPort.Stereotype == "Server")
                        //        if (trgtPort.Stereotype != "Client") continue;

                            var sql = new UtilSql(_rep);
                            if (sql.IsConnectionAvailable(srcPort, trgtPort) == false)
                            {
                                // direction of connector
                                if (srcPort.Stereotype == "Sender" | srcPort.Stereotype == "Client")
                                {
                                    var con = (Connector)srcPort.Connectors.AddNew("", "Connector");
                                    srcPort.Connectors.Refresh();
                                    con.SupplierID = trgtPort.ElementID;
                                    con.Update();
                                    _count += 1;
                                }
                                else
                                {
                                    var con = (Connector)trgtPort.Connectors.AddNew("", "Connector");
                                    trgtPort.Connectors.Refresh();
                                    con.SupplierID = srcPort.ElementID;
                                    con.Update();
                                    _count += 1;
                                }
                            }
                        //}
                    }
                }
            }
        }
        static void AddPortToComponent(Element elSource, Element elInterface)
        {
            if (elInterface.Type != "Interface") return;

            // check if port with interface already exists
            foreach (Element p in elSource.EmbeddedElements)
            {
                if (p.Name == elInterface.Name) return;
            }
            // create a port
            var port = (Element) elSource.EmbeddedElements.AddNew(elInterface.Name, "Port");
            elSource.EmbeddedElements.Refresh();
            // add interface
            var interf = (Element) port.EmbeddedElements.AddNew(elInterface.Name, "RequiredInterface");
            // set classifier
            interf.ClassfierID = elInterface.ElementID;
            interf.Update();
        }
 private void SetElementConnectorDirectionUnspecified(Element el) {
     foreach (Connector con in el.Connectors)
     {
         if (con.Type == "Connector")
         {
             con.Direction = "Unspecified";
             con.Update();
         }
     }
 }
        //----------------------------------------------------------------------------------------
        // type:      "Action", "Activity","Decision", "MergeNode","StateNode"
        // extension: "CallOperation" ,"101"=StateNode, Final, "no"= else/no Merge
        //             comp=yes:  Activity with composite Diagram
        //----------------------------------------------------------------------------------------
        private static DiagramObject CreateDiagramObjectFromContext(Repository rep, string name, string type,
            string extension, int offsetHorizental = 0, int offsetVertical = 0, string guardString = "",
            Element srcEl = null)
        {
            int widthPerCharacter = 60;
            // filter out linefeed, tab
            name = Regex.Replace(name, @"(\n|\r|\t)", "", RegexOptions.Singleline);

            if (name.Length > 255)
            {
                MessageBox.Show($"{type}: '{name}' has more than 255 characters.", @"Name is to long");
                return null;
            }
            Element elSource;
            Element elParent = null;
            Element elTarget;

            string basicType = type;
            if (type == "CallOperation") basicType = "Action";

            Diagram dia = rep.GetCurrentDiagram();
            if (dia == null) return null;

            rep.SaveDiagram(dia.DiagramID);

            // only one diagram object selected as source
            if (srcEl == null) elSource = Util.GetElementFromContextObject(rep);
            else elSource = srcEl;
            if (elSource == null) return null;
            var diaObjSource = Util.GetDiagramObjectById(rep, dia, elSource.ElementID);
            //diaObjSource = dia.GetDiagramObjectByID(elSource.ElementID, "");

            string noValifTypes = "Note, Constraint, Boundary, Text, UMLDiagram, DiagramFrame";
            if (noValifTypes.Contains(elSource.Type)) return null;


            if (elSource.ParentID != 0)
            {
                Util.GetDiagramObjectById(rep, dia, elSource.ParentID);
                //diaObjParent = dia.GetDiagramObjectByID(elSource.ParentID, "");
            }

            try
            {
                if (elSource.ParentID > 0)
                {
                    elParent = rep.GetElementByID(elSource.ParentID);
                    elTarget = (Element) elParent.Elements.AddNew(name, basicType);
                    if (basicType == "StateNode") elTarget.Subtype = Convert.ToInt32(extension);
                    elParent.Elements.Refresh();
                }
                else
                {
                    var pkg = rep.GetPackageByID(elSource.PackageID);
                    elTarget = (Element) pkg.Elements.AddNew(name, basicType);
                    if (basicType == "StateNode") elTarget.Subtype = Convert.ToInt32(extension);
                    pkg.Elements.Refresh();
                }
                elTarget.ParentID = elSource.ParentID;
                elTarget.Update();
                if (basicType == "Activity" & extension.ToLower() == "comp=yes")
                {
                    Diagram actDia = ActivityPar.CreateActivityCompositeDiagram(rep, elTarget);
                    Util.SetActivityCompositeDiagram(rep, elTarget, actDia.DiagramID.ToString());
                    //elTarget.
                }
            }
            catch
            {
                return null;
            }

            int left = diaObjSource.left + offsetHorizental;
            int right = diaObjSource.right + offsetHorizental;
            int top = diaObjSource.top + offsetVertical;
            int bottom = diaObjSource.bottom + offsetVertical;
            int length;

            if (basicType == "StateNode")
            {
                left = left - 10 + (right - left)/2;
                right = left + 20;
                top = bottom - 20;
                bottom = top - 20;
            }
            if ((basicType == "Decision") | (basicType == "MergeNode"))
            {
                if (guardString == "no")
                {
                    if (elSource.Type == "Decision") left = left + (right - left) + 200;
                    else left = left + (right - left) + 50;
                    bottom = bottom - 5;
                }
                left = left - 15 + (right - left)/2;
                right = left + 30;
                top = bottom - 20;
                bottom = top - 40;
            }
            if (basicType == "Action" | basicType == "Activity")
            {
                length = name.Length*widthPerCharacter/10;

                if (extension.ToLower() == "comp=no")
                {
                    /* Activity ind diagram */
                    if (length < 500) length = 500;
                    left = left + ((right - left)/2) - (length/2);
                    right = left + length;
                    top = bottom - 20;
                    bottom = top - 200;
                    if (basicType == "Activity") bottom = top - 400;
                }
                else if (extension.ToLower() == "comp=yes")
                {
                    if (length < 220) length = 220;
                    left = left + ((right - left)/2) - (length/2);
                    right = left + length;
                    top = bottom - 40;
                    bottom = top - 40;
                }
                else
                {
                    if (length < 220) length = 220;
                    left = left + ((right - left)/2) - (length/2);
                    right = left + length;
                    top = bottom - 20;
                    bottom = top - 20;
                }
            }
            // limit values
            if (left < 5) left = 5;
            string position = "l=" + left + ";r=" + right + ";t=" + top + ";b=" + bottom + ";";
            // end note
            if (elParent != null && elParent.Type == "Activity" && extension == "101")
            {
                DiagramObject diaObj = Util.GetDiagramObjectById(rep, dia, elParent.ElementID);
                //EA.DiagramObject diaObj = dia.GetDiagramObjectByID(elParent.ElementID,"");
                if (diaObj != null)
                {
                    diaObj.bottom = bottom - 40;
                    diaObj.Update();
                }
            }


            Util.AddSequenceNumber(rep, dia);
            var diaObjTarget = (DiagramObject) dia.DiagramObjects.AddNew(position, "");
            diaObjTarget.ElementID = elTarget.ElementID;
            diaObjTarget.Sequence = 1;
            diaObjTarget.Update();
            Util.SetSequenceNumber(rep, dia, diaObjTarget, "1");

            // position the label:
            // LBL=CX=180:  length of label
            // CY=13:       hight of label
            // OX=26:       x-position of label (relative object)
            // CY=13:       y-position of label (relative object)
            if (basicType == "Decision" & name.Length > 0)
            {
                if (name.Length > 25) length = 25*widthPerCharacter/10;
                else length = name.Length*widthPerCharacter/10;
                // string s = "DUID=E2352ABC;LBL=CX=180:CY=13:OX=29:OY=-4:HDN=0:BLD=0:ITA=0:UND=0:CLR=-1:ALN=0:ALT=0:ROT=0;;"; 
                string s = "DUID=E2352ABC;LBL=CX=180:CY=13:OX=-" + length +
                           ":OY=-4:HDN=0:BLD=0:ITA=0:UND=0:CLR=-1:ALN=0:ALT=0:ROT=0;;";
                Util.SetDiagramObjectLabel(rep,
                    diaObjTarget.ElementID, diaObjTarget.DiagramID, diaObjTarget.InstanceID, s);
            }

            if (extension == "Comp=no")
            {
                /* Activity ind diagram */
                // place an init
                int initLeft = left + ((right - left)/2) - 10;
                int initRight = initLeft + 20;
                int initTop = top - 25;
                int initBottom = initTop - 20;
                string initPosition = "l=" + initLeft + ";r=" + initRight + ";t=" + initTop + ";b=" + initBottom + ";";
                ActivityPar.CreateInitFinalNode(rep, dia,
                    elTarget, 100, initPosition);
            }

            // draw a Control Flow
            var con = (Connector) elSource.Connectors.AddNew("", "ControlFlow");
            con.SupplierID = elTarget.ElementID;
            con.Update();
            elSource.Connectors.Refresh();
            // set line style LV
            foreach (DiagramLink link in dia.DiagramLinks)
            {
                if (link.ConnectorID == con.ConnectorID)
                {
                    if (guardString != "no")
                    {
                        link.Geometry =
                            "EDGE=3;$LLB=;LLT=;LMT=;LMB=CX=21:CY=13:OX=-20:OY=-19:HDN=0:BLD=0:ITA=0:UND=0:CLR=-1:ALN=0:DIR=0:ROT=0;LRT=;LRB=;IRHS=;ILHS=;";
                    }
                    // in case of switch case line style = LH
                    string style = "LV";
                    if ((elSource.Type == "Action" | elSource.Type == "Activity") & guardString == "no") style = "LH";
                    if (Regex.IsMatch(elSource.Name, @"switch[\s]*\(")) style = "OS";
                    Util.SetLineStyleForDiagramLink(style, link);

                    break;
                }
            }


            // set Guard
            if (guardString != "")
            {
                if (guardString == "no" && elSource.Type != "Decision")
                {
                    // mo GUARD
                }
                else
                {
                    // GUARD
                    Util.SetConnectorGuard(rep, con.ConnectorID, guardString);
                }
            }
            else if (elSource.Type.Equals("Decision") & !elSource.Name.Trim().Equals(""))
            {
                if (guardString == "no")
                {
                    Util.SetConnectorGuard(rep, con.ConnectorID, "no");
                }
                else
                {
                    Util.SetConnectorGuard(rep, con.ConnectorID, "yes");
                }
            }

            // handle subtypes of action
            if (type == "CallOperation")
            {
                Method method = CallOperationAction.GetMethodFromMethodName(rep, extension);
                if (method != null)
                {
                    CallOperationAction.CreateCallAction(rep, elTarget, method);
                }
            }

            rep.ReloadDiagram(dia.DiagramID);

            // set selected object
            dia.SelectedObjects.AddNew(diaObjTarget.ElementID.ToString(), diaObjTarget.ObjectType.ToString());
            dia.SelectedObjects.Refresh();
            return diaObjTarget;
        }
        static void CreateMacro(Repository rep, Element el, string s, string stereotype)
        {
            string name = "";
            string value = "";
            EA.Attribute a = null;
            bool isNewAttribute = true;

            // delete spaces between parameters
            s = Regex.Replace(s, @",[\s]+", ",");
            s = Regex.Replace(s, @"[\s]+,", ",");

            string regexDefine = @"#[\s]*define[\s]*([a-zA-Z0-9_(),]*)[\s]*(.*)";
            Match match = Regex.Match(s, regexDefine);
            if (match.Success)
            {
                name = match.Groups[1].Value.Trim();
                value = match.Groups[2].Value.Trim();
            }

            if (!name.Equals(""))
            {
                value = CallOperationAction.RemoveCasts(value);
                foreach (EA.Attribute attr in el.Attributes)
                {
                    if (attr.Name == name)
                    {
                        a = attr;
                        isNewAttribute = false;
                        break;
                    }
                }
                if (isNewAttribute)
                {
                    a = (EA.Attribute) el.Attributes.AddNew(name, "");
                    a.Pos = el.Attributes.Count;
                    el.Attributes.Refresh();
                }
                a.Default = value;
                if (el.Type.Equals("Interface")) a.Visibility = "public";
                else a.Visibility = "private";

                a.IsConst = true;
                if (!stereotype.Equals("")) a.Stereotype = stereotype;
                else a.Stereotype = "define";
                a.ClassifierID = 0;
                a.Type = "";
                a.Update();
            }
            else
            {
                MessageBox.Show(s, @"Can't identify macro");
            }
        }
        static List<Element> GetIncludedHeaderFiles(Repository rep, Element el)
        {
            var lEl = new List<Element>();
            string path = Util.GetGenFilePath(rep, el);
            if (path == "")
            {
                MessageBox.Show($"No file defined in property for: '{el.Name}':{el.Type}");
                return lEl;
            }
            string text;
            try
            {
                text = System.IO.File.ReadAllText(path);
            }
            catch (Exception e)
            {
                Clipboard.SetText(e.ToString());
                MessageBox.Show($"{e}\n\nsee Clipboard!", $"Error Reading file '{el.Name}':{el.Type}");
                return lEl;
            }
            lEl = GetInterfacesFromText(rep, null, text, createWarningNote: false);

            return lEl;
        }
 static bool LocateTextOrFrame(Repository rep, Element el)
 {
     if (el.Type == "Text")
     {
         string s = el.MiscData[0];
         int id = Convert.ToInt32(s);
         Diagram dia = rep.GetDiagramByID(id);
         rep.ShowInProjectView(dia);
         return true;
     }
     // display the original diagram on what the frame is based
     if (el.Type == "UMLDiagram")
     {
         int id = Convert.ToInt32(el.MiscData[0]);
         Diagram dia = rep.GetDiagramByID(id);
         rep.ShowInProjectView(dia);
         return true;
     }
     return false;
 }