Example #1
0
 /// <summary>
 /// ChangeRule: typeof(RingConstraint), FireTime=TopLevelCommit, Priority=DiagramFixupConstants.AddConnectionRulePriority;
 /// </summary>
 private static void RingConstraintPropertyChangeRule(ElementPropertyChangedEventArgs e)
 {
     if (e.DomainProperty.Id == RingConstraint.RingTypeDomainPropertyId)
     {
         RingConstraint ringConstraint = (RingConstraint)e.ModelElement;
         if (!ringConstraint.IsDeleted)
         {
             foreach (PresentationElement pel in PresentationViewsSubject.GetPresentation(ringConstraint))
             {
                 RingConstraintShape ringConstraintShape = pel as RingConstraintShape;
                 if (ringConstraintShape != null)
                 {
                     foreach (LinkConnectsToNode connection in DomainRoleInfo.GetElementLinks <LinkConnectsToNode>(ringConstraintShape, LinkConnectsToNode.NodesDomainRoleId))
                     {
                         BinaryLinkShape binaryLink = connection.Link as BinaryLinkShape;
                         if (binaryLink != null)
                         {
                             binaryLink.RecalculateRoute();
                         }
                     }
                     SizeD oldSize = ringConstraintShape.Size;
                     ringConstraintShape.AutoResize();
                     if (oldSize == ringConstraintShape.Size)
                     {
                         ringConstraintShape.InvalidateRequired(true);
                     }
                 }
             }
         }
     }
 }
        /// <summary>
        /// Gets the embedding domain element of a specific type for a given model element.
        /// </summary>
        /// <param name="modelElement">ModelElement to get the embedding domain element for.</param>
        /// <param name="parentTypeDomainClassId">Type of the embedding domain element to find.</param>
        /// <returns>Domain element as ModelElement if found. Null otherwise</returns>
        public virtual ModelElement GetEmbeddingParent(ModelElement modelElement, System.Guid parentTypeDomainClassId)
        {
            if (!(modelElement is DomainModelElement))
            {
                return(null);
            }

            List <EmbeddingRelationshipAdvancedInfo> embeddings = (modelElement as DomainModelElement).Store.DomainDataAdvDirectory.FindDomainClassTargetEmbeddings((modelElement as DomainModelElement).GetDomainClassId());

            if (embeddings != null)
            {
                foreach (EmbeddingRelationshipAdvancedInfo emb in embeddings)
                {
                    IList <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(modelElement, emb.TargetRoleId);
                    if (links.Count == 1)
                    {
                        ModelElement m = DomainRoleInfo.GetSourceRolePlayer(links[0]);
                        if (m.GetDomainClass().IsDerivedFrom(parentTypeDomainClassId))
                        {
                            return(m);
                        }

                        return(GetEmbeddingParent(m, parentTypeDomainClassId));
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Returns all non abstract derived classes of the given elements.
        /// </summary>
        private static List <AttributedDomainElement> GetNonAbstractDerivedElements(AttributedDomainElement child)
        {
            List <AttributedDomainElement> derivedClassesCollection = new List <AttributedDomainElement>();

            if (child is DomainClass)
            {
                ReadOnlyCollection <DomainClassReferencesBaseClass> derivedClasses =
                    DomainRoleInfo.GetElementLinks <DomainClassReferencesBaseClass>(child, DomainClassReferencesBaseClass.BaseClassDomainRoleId);
                foreach (DomainClassReferencesBaseClass c in derivedClasses)
                {
                    if (c.DerivedClass.InheritanceModifier != InheritanceModifier.Abstract)
                    {
                        derivedClassesCollection.Add(c.DerivedClass);
                    }

                    derivedClassesCollection.AddRange(GetNonAbstractDerivedElements(c.DerivedClass));
                }
            }
            else if (child is DomainRelationship)
            {
                ReadOnlyCollection <DomainRelationshipReferencesBaseRelationship> derivedClasses =
                    DomainRoleInfo.GetElementLinks <DomainRelationshipReferencesBaseRelationship>(child, DomainRelationshipReferencesBaseRelationship.BaseRelationshipDomainRoleId);
                foreach (DomainRelationshipReferencesBaseRelationship c in derivedClasses)
                {
                    if (c.DerivedRelationship.InheritanceModifier != InheritanceModifier.Abstract)
                    {
                        derivedClassesCollection.Add(c.DerivedRelationship);
                    }

                    derivedClassesCollection.AddRange(GetNonAbstractDerivedElements(c.DerivedRelationship));
                }
            }

            return(derivedClassesCollection);
        }
Example #4
0
        /// <summary>
        /// ChangeRule: typeof(ORMBaseBinaryLinkShape), FireTime=TopLevelCommit, Priority=DiagramFixupConstants.AutoLayoutShapesRulePriority;
        /// Keep relative child elements a fixed distance away from the fact
        /// when the shape changes.
        /// </summary>
        private static void LinkChangeRule(ElementPropertyChangedEventArgs e)
        {
            Guid attributeId = e.DomainProperty.Id;

            if (attributeId == ORMBaseBinaryLinkShape.EdgePointsDomainPropertyId)
            {
                ORMBaseBinaryLinkShape parentShape = e.ModelElement as ORMBaseBinaryLinkShape;
                LinkedElementCollection <ShapeElement> childShapes = parentShape.RelativeChildShapes;
                int childCount = childShapes.Count;
                for (int i = 0; i < childCount; ++i)
                {
                    LinkConnectorShape linkConnector = childShapes[i] as LinkConnectorShape;
                    if (linkConnector != null)
                    {
                        RectangleD bounds = parentShape.AbsoluteBoundingBox;
                        linkConnector.Location = new PointD(bounds.Width / 2, bounds.Height / 2);
                        ReadOnlyCollection <LinkConnectsToNode> links = DomainRoleInfo.GetElementLinks <LinkConnectsToNode>(linkConnector, LinkConnectsToNode.NodesDomainRoleId);
                        int linksCount = links.Count;
                        for (int j = 0; j < linksCount; ++j)
                        {
                            LinkConnectsToNode link      = links[j];
                            BinaryLinkShape    linkShape = link.Link as BinaryLinkShape;
                            if (linkShape != null)
                            {
                                // Changing the location is not reliably reconnecting all shapes, especially
                                // during load. Force the link to reconnect with a RecalculateRoute call
                                linkShape.RecalculateRoute();
                            }
                        }
                        break;
                    }
                }
            }
        }
Example #5
0
 /// <summary>
 /// Delete element executed.
 /// </summary>
 protected virtual void DeleteElementCommand_Executed()
 {
     if (SelectedObject != null)
     {
         ReadOnlyCollection <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(this.Elements[0] as ModelElement, this.SourceRoleId);
         foreach (ElementLink link in links)
         {
             ModelElement target = DomainRoleInfo.GetRolePlayer(link, this.TargetRoleId);
             if (SelectedObject.Element == target)
             {
                 try
                 {
                     using (Transaction transaction = this.Store.TransactionManager.BeginTransaction("Delete relationship"))
                     {
                         link.Delete();
                         transaction.Commit();
                     }
                 }
                 catch (Exception ex)
                 {
                     System.Windows.MessageBox.Show("Error while deleting: " + ex.Message);
                 }
                 break;
             }
         }
     }
 }
        private static ModelElement GetCompartmentElementFirstParentElement(this ModelElement modelElement)
        {
            // Get the domain class associated with model element.
            DomainClassInfo domainClass = modelElement.GetDomainClass();

            if (domainClass != null)
            {
                // A element is only considered to be in a compartment if it participates in only 1 embedding relationship
                // This might be wrong for some models

                if (domainClass.AllEmbeddedByDomainRoles.Count == 1)
                {
                    DomainRoleInfo roleInfo = domainClass.AllEmbeddedByDomainRoles[0];

                    // Get a collection of all the links to this model element
                    // Since this is in a compartment there should be at least one
                    // There can be only one.
                    if (roleInfo != null)
                    {
                        ElementLink link = roleInfo.GetElementLinks(modelElement).FirstOrDefault();

                        // Get the model element participating in the link that isn't the current one
                        // That will be the parent
                        // Probably there is a better way to achieve the same result
                        return(link?.LinkedElements?.FirstOrDefault(linkedElement => !modelElement.Equals(linkedElement)));
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Test if null is allowed for the provided link.
        /// </summary>
        /// <param name="link">The current element link for
        /// the component associated with this role player</param>
        /// <returns></returns>
        public virtual bool CanAllowNull(ElementLink link)
        {
            if (link == null)
            {
                return(true);
            }
            DomainRoleInfo targetDomainRole = DomainRoleInfo;
            DomainRoleInfo sourceDomainRole = targetDomainRole.OppositeDomainRole;
            bool           sourceIsOptional = sourceDomainRole.IsOptional;

            if (sourceIsOptional && targetDomainRole.IsOptional)
            {
                // We previously determined that we always allow null.
                return(true);
            }
            if (sourceIsOptional)
            {
                // The source role is optional, but the target role isn't. However,
                // we need to check/ for other instances of this type of relationship
                // that satisfy that.
                if (targetDomainRole.Multiplicity == Multiplicity.OneMany)
                {
                    ModelElement targetPlayer = targetDomainRole.GetRolePlayer(link);
                    if (targetDomainRole.GetElementLinks <ElementLink>(targetPlayer).Count > 1)
                    {
                        // There is at least one other instance of this type of relationship,
                        // which means that the "mandatory" on the target role would still be
                        // satisfied even if this link were to be deleted.
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #8
0
        /*
         * /// <summary>
         * /// Tries to find a free position on parent and update the location of the shape to that location.
         * /// </summary>
         * /// <returns>
         * /// Coordinates of a free position.
         * /// </returns>
         * /// <remarks>
         * /// Needs to be called within a modeling transaction.
         * /// </remarks>
         * public virtual void SetAtFreePositionOnParent()
         * {
         *  IList<NodeShape> shapes;
         *  if (this.Parent == null)
         *  {
         *      // free position on diagram
         *      Diagram diagram = this.Diagram;
         *      shapes = diagram.Children;
         *  }
         *  else
         *  {
         *      if (this.IsRelativeChildShape)
         *      {
         *          float width = (float)this.Bounds.Width;
         *          float height = (float)this.Bounds.Height;
         *
         *          float parentWidth = (float)this.Parent.Bounds.Width;
         *          float parentHeight = (float)this.Parent.Bounds.Height;
         *
         *          Dictionary<PortPlacement, int> dict = new Dictionary<PortPlacement, int>();
         *          dict.Add(PortPlacement.Left, 0);
         *          dict.Add(PortPlacement.Top, 0);
         *          dict.Add(PortPlacement.Bottom, 0);
         *          dict.Add(PortPlacement.Right, 0);
         *          for (int i = 0; i < this.Parent.RelativeChildren.Count; i++)
         *          {
         *              if (this.Parent.RelativeChildren[i] == this)
         *                  continue;
         *
         *              dict[this.Parent.RelativeChildren[i].PlacementSide]++;
         *          }
         *          List<KeyValuePair<PortPlacement, int>> myList = new List<KeyValuePair<PortPlacement, int>>(dict);
         *          myList.Sort((firstPair, nextPair) =>
         *          {
         *              return firstPair.Value.CompareTo(nextPair.Value);
         *          });
         *
         *          foreach (KeyValuePair<PortPlacement, int> p in myList)
         *          {
         *              RectangleF rectH;
         *              switch (p.Key)
         *              {
         *                  case PortPlacement.Left:
         *                      rectH = new RectangleF(-width / 2, 0, width, parentHeight);
         *                      break;
         *
         *                  case PortPlacement.Top:
         *                      rectH = new RectangleF(0, -height / 2, parentWidth, height);
         *                      break;
         *
         *                  case PortPlacement.Right:
         *                      rectH = new RectangleF(parentWidth - width / 2, 0, width, parentHeight);
         *                      break;
         *
         *                  case PortPlacement.Bottom:
         *                      rectH = new RectangleF(0, parentHeight - height / 2, parentWidth, height);
         *                      break;
         *
         *                  default:
         *                      throw new NotSupportedException();
         *              }
         *
         *              if (SetPortAtFreePositionOnParent(p.Key, rectH))
         *              {
         *                  return;
         *              }
         *          }
         *
         *          this.SetLocation(NodeShape.CorrectPortLocation(this.Parent, this, new PointD(0, 0)));
         *          return;
         *      }
         *
         *      // free position on parent shape
         *      shapes = this.Parent.NestedChildren;
         *  }
         *
         *  // trivial algo.. TODO: find something good
         *  RectangleF rect = new RectangleF(0, 0, (float)this.Size.Width, (float)this.Size.Height);
         *
         *  // find area that is already filled
         *  RectangleF completeBounds = new RectangleF(0, 0, 0, 0);
         *  for (int i = 0; i < shapes.Count; i++)
         *  {
         *      if (shapes[i] == this)
         *          continue;
         *
         *      if (i == 0)
         *          completeBounds = shapes[i].Bounds.ToRectangleF();
         *      else
         *      {
         *          RectangleF f = shapes[i].Bounds.ToRectangleF();
         *          if (completeBounds.X > f.X)
         *              completeBounds.X = f.X;
         *          if (completeBounds.Y > f.Y)
         *              completeBounds.Y = f.Y;
         *
         *          if (completeBounds.Right < f.Right)
         *              completeBounds.Width = f.Right - completeBounds.X;
         *
         *          if (completeBounds.Bottom < f.Bottom)
         *              completeBounds.Height = f.Bottom - completeBounds.Y;
         *      }
         *  }
         *
         *  /*
         *  // see if we can insert shape somewhere in that area
         *  // if not, add shape right at the edge of that area
         *  for (int i = 0; i < shapes.Count; i++)
         *  {
         *      if (shapes[i] == this)
         *          continue;
         *
         *      // TODO ... (not necessaraly required)
         *  }
         *
         *  // could not add shape in the completeBounds are, so add it outside of it
         */
        /*
         *  if( completeBounds.Width < completeBounds.Height )
         *      this.SetLocation(new PointD(completeBounds.Right + 5, 5));
         *  else
         *      this.SetLocation(new PointD(5, completeBounds.Bottom + 5));
         *  this.UpdateAbsoluteLocation();
         * }
         *
         * private bool SetPortAtFreePositionOnParent(PortPlacement side, RectangleF freeRectangle)
         * {
         *  List<RectangleF> freeRectangles = new List<RectangleF>();
         *  freeRectangles.Add(freeRectangle);
         *
         *  for (int i = 0; i < this.Parent.RelativeChildren.Count; i++)
         *  {
         *      if (this.Parent.RelativeChildren[i] == this)
         *          continue;
         *
         *      if (this.Parent.RelativeChildren[i].PlacementSide != side)
         *          continue;
         *
         *      RectangleF s = this.Parent.RelativeChildren[i].Bounds.ToRectangleF();
         *      for (int y = freeRectangles.Count - 1; y >= 0; y--)
         *      {
         *          RectangleF r = freeRectangles[y];
         *          RectangleF t = r;
         *          r.Intersect(s);
         *
         *          if (!r.IsEmpty)
         *          {
         *              // remove r from freeRectangley[y] --> yields <=2 rects
         *              // add 2 rects to freeRectangles
         *              freeRectangles.RemoveAt(y);
         *
         *              switch (side)
         *              {
         *                  case PortPlacement.Left:
         *                  case PortPlacement.Right:
         *                      if (t.Y < r.Y)
         *                      {
         *                          // first r
         *                          RectangleF r1 = new RectangleF(t.X, t.Y, t.Width, r.Y - t.Y);
         *                          freeRectangles.Add(r1);
         *                      }
         *
         *                      if (r.Bottom < t.Bottom)
         *                      {
         *                          // second r
         *                          RectangleF r2 = new RectangleF(t.X, r.Bottom, t.Width, t.Bottom - r.Bottom);
         *                          freeRectangles.Add(r2);
         *                      }
         *                      break;
         *
         *                  case PortPlacement.Top:
         *                  case PortPlacement.Bottom:
         *                      if (t.X < r.X)
         *                      {
         *                          // first r
         *                          RectangleF r1 = new RectangleF(t.X, t.Y, r.X-t.X, t.Height);
         *                          freeRectangles.Add(r1);
         *                      }
         *
         *                      if (r.Right < t.Right)
         *                      {
         *                          // second r
         *                          RectangleF r2 = new RectangleF(r.Right, t.Y, t.Right-r.Right, t.Height);
         *                          freeRectangles.Add(r2);
         *                      }
         *                      break;
         *              }
         *
         *          }
         *      }
         *  }
         *
         *  // try to place at a fitting free rectangle
         *  foreach (RectangleF r in freeRectangles)
         *  {
         *      if (r.Width >= this.Bounds.Width && r.Height >= this.Bounds.Height)
         *      {
         *          this.Location = new PointD(r.X, r.Y);
         *          this.PlacementSide = side;
         *          this.UpdateAbsoluteLocation();
         *          return true;
         *      }
         *  }
         *
         *  return false;
         * }
         */

        /// <summary>
        /// Create missing shapes.
        /// </summary>
        public virtual void FixUpMissingShapes()
        {
            if (this.Element == null)
            {
                return;
            }

            DomainModelElement e = this.Element as DomainModelElement;

            IDomainModelServices       topMost = e.GetDomainModelServices().TopMostService;
            DiagramDomainDataDirectory data    = this.Store.DomainDataAdvDirectory.ResolveExtensionDirectory <DiagramDomainDataDirectory>();

            List <EmbeddingRelationshipAdvancedInfo> infos = this.Store.DomainDataAdvDirectory.FindDomainClassSourceEmbeddings(e.GetDomainClassId());

            if (infos != null)
            {
                foreach (EmbeddingRelationshipAdvancedInfo info in infos)
                {
                    List <Guid> shapes = data.GetShapeTypesForElement(info.TargetElementDomainClassId);
                    if (shapes == null)
                    {
                        continue;
                    }
                    if (shapes.Count == 0)
                    {
                        continue;
                    }

                    ReadOnlyCollection <ElementLink> instances = DomainRoleInfo.GetElementLinks <ElementLink>(this.Element, info.SourceRoleId);
                    foreach (ElementLink link in instances)
                    {
                        DomainModelElement child = DomainRoleInfo.GetTargetRolePlayer(link) as DomainModelElement;
                        if (child == null)
                        {
                            continue;
                        }

                        // see if we need to add shape
                        foreach (Guid elementShapeId in data.GetShapeTypesForElement(child.GetDomainClassId(), this.GetDomainClassId()))
                        {
                            if (!DiagramHelper.IsElementDisplayedOn(this, elementShapeId, child.Id))
                            {
                                NodeShape shape = topMost.ShapeProvider.CreateShapeForElement(elementShapeId, child) as NodeShape;
                                if (shape.IsRelativeChildShape)
                                {
                                    this.AddRelativeChild(shape);
                                }
                                else
                                {
                                    this.AddNestedChild(shape);
                                }

                                shape.FixUpMissingShapes();
                            }
                        }
                    }
                }
            }
        }
Example #9
0
        /// <summary>
        /// Method used to create a new element's name based on the range of available names.
        /// Excluded are names used by the child elements embedded in the given parent element.
        /// </summary>
        /// <param name="parent">Parent element, embedding the model element.</param>
        /// <param name="modelElement">ModelElement to create the name for.</param>
        /// <returns>Created name for the given ModelElement. </returns>
        public virtual string CreateName(ModelElement parent, ModelElement modelElement)
        {
            if (parent is IDomainModelOwnable && modelElement is IDomainModelOwnable)
            {
                if (!(modelElement as IDomainModelOwnable).DomainElementHasName)
                {
                    return(null);
                }

                DomainClassInfo infoParent = parent.GetDomainClass();
                DomainClassInfo infoChild  = modelElement.GetDomainClass();

                IModelElementParentProvider parentprovider = (parent as IDomainModelOwnable).GetDomainModelServices().ElementParentProvider;
                foreach (DomainRoleInfo roleInfo in infoParent.AllDomainRolesPlayed)
                {
                    if (roleInfo.IsSource)
                    {
                        //if (roleInfo.OppositeDomainRole.RolePlayer.Id == infoChild.Id)
                        if (infoChild.IsDerivedFrom(roleInfo.OppositeDomainRole.RolePlayer))
                        {
                            if ((modelElement as IDomainModelOwnable).Store.DomainDataAdvDirectory.IsEmbeddingRelationship(roleInfo.DomainRelationship.Id))
                            {
                                int    counter = 0;
                                string name    = (modelElement as IDomainModelOwnable).DomainElementTypeDisplayName;
                                while (true)
                                {
                                    bool bFound = false;
                                    IList <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(parent, roleInfo.Id);

                                    foreach (ElementLink c in links)
                                    {
                                        if ((DomainRoleInfo.GetTargetRolePlayer(c) as IDomainModelOwnable).DomainElementName == name + counter.ToString())
                                        {
                                            bFound = true;
                                            break;
                                        }
                                    }

                                    if (!bFound)
                                    {
                                        return(name + counter.ToString());
                                    }

                                    counter++;
                                }
                            }
                        }
                    }
                }
            }

            return(null);
        }
Example #10
0
        /// <summary>
        /// Called by the Action when the user releases the mouse.
        /// If we are still on the same compartment but in a different list item,
        /// move the starting item to the position of the current one.
        /// </summary>
        /// <param name="dragFrom"></param>
        /// <param name="e"></param>
        internal static void DoMouseUpForShape <TElement>(ModelElement dragFrom, DiagramMouseEventArgs e) where TElement : ModelElement
        {
            // Original or "from" item:
            TElement dragFromElement = dragFrom as TElement;
            // Current or "to" item:
            TElement dragToElement = e.HitDiagramItem.RepresentedElements.OfType <TElement>().FirstOrDefault();

            if (dragFromElement != null && dragToElement != null)
            {
                // Find the common parent model element, and the relationship links:
                ElementLink parentToLink   = GetEmbeddingLink(dragToElement);
                ElementLink parentFromLink = GetEmbeddingLink(dragFromElement);
                if (parentToLink != parentFromLink && parentFromLink != null && parentToLink != null)
                {
                    // Get the static relationship and role (= end of relationship):
                    DomainRelationshipInfo relationshipFrom = parentFromLink.GetDomainRelationship();
                    DomainRoleInfo         parentFromRole   = relationshipFrom.DomainRoles[0];
                    // Get the node in which the element is embedded, usually the element displayed in the shape:
                    ModelElement parentFrom = parentFromLink.LinkedElements[0];

                    // Same again for the target:
                    DomainRelationshipInfo relationshipTo = parentToLink.GetDomainRelationship();
                    DomainRoleInfo         parentToRole   = relationshipTo.DomainRoles[0];
                    ModelElement           parentTo       = parentToLink.LinkedElements[0];

                    // Mouse went down and up in same parent and same compartment:
                    if (parentTo == parentFrom && relationshipTo == relationshipFrom)
                    {
                        // Find index of target position:
                        int newIndex     = 0;
                        var elementLinks = parentToRole.GetElementLinks(parentTo);
                        foreach (ElementLink link in elementLinks)
                        {
                            if (link == parentToLink)
                            {
                                break;
                            }
                            newIndex++;
                        }

                        if (newIndex < elementLinks.Count)
                        {
                            using (Transaction t = parentFrom.Store.TransactionManager.BeginTransaction("Move list item"))
                            {
                                parentFromLink.MoveToIndex(parentFromRole, newIndex);
                                t.Commit();
                            }
                        }
                    }
                }
            }
        }
Example #11
0
        private void ProcessRoleForContextMenu(IModelElementParentProvider parentProvider, MenuItemViewModel menuItemAdd, DomainRoleInfo roleInfo)
        {
            bool bShouldAdd = true;

            if (this.ContextMenuProvider != null)
            {
                bShouldAdd = this.ContextMenuProvider.ShouldCreateMenuItem(ModelTreeContextMenuItemType.AddElementMenuItem,
                                                                           roleInfo.OppositeDomainRole.RolePlayer.GetType(), this.Element, null);
            }

            if (this.Store.DomainDataAdvDirectory.IsAbstractRelationship(roleInfo.DomainRelationship.Id))
            {
                bShouldAdd = false;
            }
            else if (roleInfo.Multiplicity == Multiplicity.One ||
                     roleInfo.Multiplicity == Multiplicity.ZeroOne)
            {
                global::System.Collections.Generic.IList <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(this.Element, roleInfo.Id);
                if (links.Count == 1)
                {
                    bShouldAdd = false;
                }
            }

            if (bShouldAdd)
            {
                DomainClassInfo rolePlayer = roleInfo.OppositeDomainRole.RolePlayer;
                if (!this.Store.DomainDataAdvDirectory.IsAbstractClass(rolePlayer.Id))
                {
                    MenuItemViewModel <ContextMenuCreationHelper> item = new MenuItemViewModel <ContextMenuCreationHelper>(this.ViewModelStore);
                    item.Text    = "Add new " + (this.Element as IDomainModelOwnable).GetDomainModelServices().ElementTypeProvider.GetTypeDisplayName(this.Store, rolePlayer.Id);
                    item.Command = new DelegateCommand <ContextMenuCreationHelper>(AddNewElement);
                    //item.CommandParameter = roleInfo;
                    item.CommandParameter = new ContextMenuCreationHelper(roleInfo, rolePlayer);
                    menuItemAdd.Children.Add(item);
                }

                foreach (DomainClassInfo r in rolePlayer.AllDescendants)
                {
                    if (!this.Store.DomainDataAdvDirectory.IsAbstractClass(r.Id))
                    {
                        MenuItemViewModel <ContextMenuCreationHelper> item = new MenuItemViewModel <ContextMenuCreationHelper>(this.ViewModelStore);
                        item.Text    = "Add new " + (this.Element as IDomainModelOwnable).GetDomainModelServices().ElementTypeProvider.GetTypeDisplayName(this.Store, r.Id);
                        item.Command = new DelegateCommand <ContextMenuCreationHelper>(AddNewElement);
                        //item.CommandParameter = roleInfo;
                        item.CommandParameter = new ContextMenuCreationHelper(roleInfo, r);
                        menuItemAdd.Children.Add(item);
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        ///    Called by the Action when the user releases the mouse.
        ///    If we are still on the same compartment but in a different list item,
        ///    move the starting item to the position of the current one.
        /// </summary>
        /// <param name="dragFrom"></param>
        /// <param name="e"></param>
        public void DoMouseUp(ModelElement dragFrom, DiagramMouseEventArgs e)
        {
            // Original or "from" item:
#pragma warning disable IDE0019 // Use pattern matching
            ModelAttribute dragFromElement = dragFrom as ModelAttribute;
#pragma warning restore IDE0019 // Use pattern matching

            // Current or "to" item:
            ModelAttribute dragToElement = e.HitDiagramItem.RepresentedElements.OfType <ModelAttribute>().FirstOrDefault();

            if (dragFromElement != null && dragToElement != null)
            {
                // Find the common parent model element, and the relationship links:
                ElementLink parentToLink   = GetEmbeddingLink(dragToElement);
                ElementLink parentFromLink = GetEmbeddingLink(dragFromElement);

                if (parentToLink != parentFromLink && parentFromLink != null && parentToLink != null)
                {
                    // Get the static relationship and role (= end of relationship):
                    DomainRelationshipInfo relationshipFrom = parentFromLink.GetDomainRelationship();
                    DomainRoleInfo         parentFromRole   = relationshipFrom.DomainRoles[0];

                    // Get the node in which the element is embedded, usually the element displayed in the shape:
#pragma warning disable IDE0019 // Use pattern matching
                    ModelClass parentFrom = parentFromLink.LinkedElements[0] as ModelClass;
#pragma warning restore IDE0019 // Use pattern matching

                    // Same again for the target:
                    DomainRelationshipInfo relationshipTo = parentToLink.GetDomainRelationship();
                    DomainRoleInfo         parentToRole   = relationshipTo.DomainRoles[0];

                    // Mouse went down and up in same parent and same compartment:
                    if (parentFrom != null && parentToLink.LinkedElements[0] is ModelClass parentTo && parentTo == parentFrom && relationshipTo == relationshipFrom)
                    {
                        // Find index of target position:
                        int newIndex = parentToRole.GetElementLinks(parentTo).IndexOf(parentToLink);

                        if (newIndex >= 0)
                        {
                            using (Transaction t = parentFrom.Store.TransactionManager.BeginTransaction("Move list item"))
                            {
                                parentFromLink.MoveToIndex(parentFromRole, newIndex);
                                // HACK
                                //parentTo.SetFlagValues();
                                t.Commit();
                            }
                        }
                    }
                }
            }
        }
Example #13
0
        private void RedrawAssociatedPels(bool includeFacts)
        {
            IConstraint constraint = AssociatedConstraint;

            if (null != constraint)
            {
                Diagram diagram = this.Diagram;
                switch (constraint.ConstraintStorageStyle)
                {
                case ConstraintStorageStyle.SetConstraint:
                    SetConstraint scec            = constraint as SetConstraint;
                    bool          individualRoles = 0 != (constraint.RoleSequenceStyles & RoleSequenceStyles.ConnectIndividualRoles);
                    foreach (FactSetConstraint factConstraint in DomainRoleInfo.GetElementLinks <FactSetConstraint>(scec, FactSetConstraint.SetConstraintDomainRoleId))
                    {
                        // Redraw the line
                        if (individualRoles)
                        {
                            foreach (ConstraintRoleSequenceHasRole constraintRole in factConstraint.ConstrainedRoleCollection)
                            {
                                RedrawPelsOnDiagram(constraintRole, diagram);
                            }
                        }
                        else
                        {
                            RedrawPelsOnDiagram(factConstraint, diagram);
                        }
                        if (includeFacts)
                        {
                            // Redraw the fact type
                            RedrawPelsOnDiagram(factConstraint.FactType, diagram);
                        }
                    }
                    break;

                case ConstraintStorageStyle.SetComparisonConstraint:
                    SetComparisonConstraint mcec = constraint as SetComparisonConstraint;
                    foreach (FactSetComparisonConstraint factConstraint in DomainRoleInfo.GetElementLinks <FactSetComparisonConstraint>(mcec, FactSetComparisonConstraint.SetComparisonConstraintDomainRoleId))
                    {
                        // Redraw the line
                        RedrawPelsOnDiagram(factConstraint, diagram);
                        if (includeFacts)
                        {
                            // Redraw the fact type
                            RedrawPelsOnDiagram(factConstraint.FactType, diagram);
                        }
                    }
                    break;
                }
            }
            Invalidate(true);
        }
Example #14
0
            public virtual void AddMappingRSShapesForElement(DomainModelElement modelElement)
            {
                if (modelElement == null)
                {
                    return;
                }

                DiagramDomainDataDirectory data = modelElement.Store.DomainDataAdvDirectory.ResolveExtensionDirectory <DiagramDomainDataDirectory>();

                if (data == null)
                {
                    throw new ArgumentNullException("DiagramDomainDataDirectory");
                }


                List <Guid> shapes = data.GetShapeTypesForElement(modelElement.GetDomainClassId());

                if (shapes == null)
                {
                    return;
                }
                foreach (Guid g in shapes)
                {
                    if (data.MappingRelationshipShapeInfos.ContainsKey(g))
                    {
                        MappingRelationshipShapeInfo info = data.MappingRelationshipShapeInfos[g];

                        // see if the required relationships exist
                        ReadOnlyCollection <ElementLink> colSource = DomainRoleInfo.GetElementLinks <ElementLink>(modelElement, info.SourceDomainRole);
                        if (colSource.Count != 1)
                        {
                            return;
                        }

                        ReadOnlyCollection <ElementLink> colTarget = DomainRoleInfo.GetElementLinks <ElementLink>(modelElement, info.TargetDomainRole);
                        if (colTarget.Count != 1)
                        {
                            return;
                        }

                        DomainModelElement source = DomainRoleInfo.GetTargetRolePlayer(colSource[0]) as DomainModelElement;
                        DomainModelElement target = DomainRoleInfo.GetTargetRolePlayer(colTarget[0]) as DomainModelElement;


                        AddRSShapesForElement(source, target, modelElement, g);
                    }
                }
            }
        /// <summary>
        /// Gets the embedding domain element for a given model element. The embedding domain element
        /// is the parent domain element that is embedding the given model domain element.
        /// </summary>
        /// <param name="modelElement">ModelElement to get the embedding domain element for.</param>
        /// <returns>Domain element as ModelElement if found. Null otherwise</returns>
        public virtual ModelElement GetEmbeddingParent(ModelElement modelElement)
        {
            if (!(modelElement is DomainModelElement))
            {
                return(null);
            }

            List <EmbeddingRelationshipAdvancedInfo> embeddings = (modelElement as DomainModelElement).Store.DomainDataAdvDirectory.FindDomainClassTargetEmbeddings((modelElement as DomainModelElement).GetDomainClassId());

            if (embeddings != null)
            {
                foreach (EmbeddingRelationshipAdvancedInfo emb in embeddings)
                {
                    IList <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(modelElement, emb.TargetRoleId);
                    if (links.Count == 1)
                    {
                        return(DomainRoleInfo.GetSourceRolePlayer(links[0]));
                    }
                }
            }

            /*
             * if (!(modelElement is IDomainModelOwnable))
             *  return null;
             *
             * DomainClassInfo info = modelElement.GetDomainClass();
             * foreach (DomainRoleInfo roleInfo in info.AllDomainRolesPlayed)
             * {
             *  if (!roleInfo.IsSource)
             *  {
             *      DomainRelationshipAdvancedInfo infoAdv = (modelElement as IDomainModelOwnable).Store.DomainDataAdvDirectory.FindRelationshipInfo(roleInfo.DomainRelationship.Id);
             *      if (infoAdv == null)
             *          return null;
             *
             *      if (infoAdv is EmbeddingRelationshipAdvancedInfo)
             *      {
             *          global::System.Collections.Generic.IList<ElementLink> links = DomainRoleInfo.GetElementLinks<ElementLink>(modelElement, roleInfo.Id);
             *          if (links.Count == 1)
             *          {
             *              return DomainRoleInfo.GetSourceRolePlayer(links[0]);
             *          }
             *      }
             *  }
             * }*/

            return(null);
        }
Example #16
0
        /// <summary>
        /// Decides whether the element that is represented by the proto element can be pasted or not.
        /// </summary>
        /// <param name="protoElement">Proto element representation of the element.</param>
        /// <param name="protoGroup">Proto group the proto element belongs to.</param>
        /// <returns>True if the element can be pasted. False otherwise.</returns>
        public virtual bool ModelCanMerge(ModelProtoElement protoElement, ModelProtoGroup protoGroup)
        {
            if (protoElement != null)
            {
                DomainClassInfo elementDomainInfo = this.Partition.DomainDataDirectory.GetDomainClass(protoElement.DomainClassId);
                foreach (DomainRoleInfo info in elementDomainInfo.AllDomainRolesPlayed)
                {
                    if (!info.IsSource)
                    {
                        if (info.OppositeDomainRole.RolePlayer.Id == this.GetDomainClassId())
                        {
                            if (this.Store.DomainDataAdvDirectory.IsEmbeddingRelationship(info.DomainRelationship.Id) &&
                                !this.Store.DomainDataAdvDirectory.IsAbstractRelationship(info.DomainRelationship.Id))
                            {
                                if (info.OppositeDomainRole.Multiplicity == Multiplicity.One || info.OppositeDomainRole.Multiplicity == Multiplicity.ZeroOne)
                                {
                                    // Check that creating a link with this path doesn't cause multiplicity overflow
                                    if (DomainRoleInfo.GetLinkedElement(this, info.OppositeDomainRole.Id) != null)
                                    {
                                        return(false);
                                    }

                                    return(true);
                                }
                                else
                                {
                                    if (protoGroup.Operation == ModelProtoGroupOperation.Move)
                                    {
                                        foreach (ElementLink link in DomainRoleInfo.GetElementLinks <ElementLink>(this, info.OppositeDomainRole.Id))
                                        {
                                            if (DomainRoleInfo.GetTargetRolePlayer(link).Id == protoElement.ElementId)
                                            {
                                                return(false);
                                            }
                                        }
                                    }
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
        private PropertiesOptimization CreateOptimization(string key, Dictionary <string, SortedDictionary <Guid, DomainClass> > dict, Dictionary <string, List <DomainProperty> > dictProperties, bool isInheritance)
        {
            PropertiesOptimization pO = new PropertiesOptimization(this.MetaModel, this.ModelContext);

            pO.InvolvedProperties.AddRange(dictProperties[key]);
            foreach (Guid id in dict[key].Keys)
            {
                pO.InvolvedClasses.Add(dict[key][id]);
                if (isInheritance)
                {
                    // add inheritance relationship
                    ReadOnlyCollection <DomainClassReferencesBaseClass> col = DomainRoleInfo.GetElementLinks <DomainClassReferencesBaseClass>(dict[key][id], DomainClassReferencesBaseClass.DerivedClassDomainRoleId);
                    pO.InvolvedInheritancesRelationships.Add(col[0]);
                }
            }
            if (isInheritance)
            {
                pO.Description = "Move properties from derived class to basis class:";
            }
            else
            {
                pO.Description = "Creates a new base class containing properties for derived classes:";
            }
            pO.Title         = "Properties Optimization";
            pO.IsInheritance = isInheritance;
            if (pO.IsInheritance)
            {
                // add base class
                DomainClass d = dict[key][dict[key].Keys.ElementAt(0)];
                pO.BaseClass = d.BaseClass;

                bool bCreateIntermediate = false;
                if (pO.InvolvedClasses.Count != d.DerivedClasses.Count)
                {
                    bCreateIntermediate = true;
                }
                pO.CreateIntermediate = bCreateIntermediate;

                pO.InvolvedClasses.Add(d.BaseClass);
            }

            return(pO);
        }
Example #18
0
        public override void ModelFinalize(CopyPaste.ModelProtoElement protoElement, CopyPaste.ModelProtoGroupMerger groupMerger)
        {
            base.ModelFinalize(protoElement, groupMerger);

            DomainClass domainClass = this.Store.ElementDirectory.FindElement(groupMerger.GetIdMapping(protoElement.ElementId)) as DomainClass;

            if (domainClass == null)
            {
                return;
            }

            if (domainClass.IsDomainModel)
            {
                domainClass.IsDomainModel = false;
            }

            if (domainClass.BaseClass != null)
            {
                ReadOnlyCollection <DomainClassReferencesBaseClass> col = DomainRoleInfo.GetElementLinks <DomainClassReferencesBaseClass>(domainClass, DomainClassReferencesBaseClass.DerivedClassDomainRoleId);
                if (col.Count != 1)
                {
                    throw new ArgumentNullException("Domain class can only reference one base class");
                }

                DomainClassReferencesBaseClass r = col[0];
                r.InhNodeId = Guid.Empty;     // otherwise node id of the source element would be used
            }

            if (domainClass.DomainModelTreeNodes.Count == 0)
            {
                RootNode node = new RootNode(domainClass.Store);
                node.DomainElement   = domainClass;
                node.IsElementHolder = true;

                // add to the domain model diagram tree
                domainClass.ModelContext.ViewContext.DomainModelTreeView.ModelTreeNodes.Add(node);
                domainClass.ModelContext.ViewContext.DomainModelTreeView.RootNodes.Add(node);
            }

            SerializationDomainClassAddRule.OnDomainClassAdded(domainClass);
            SerializationHelper.UpdateDerivedElementsSerializationProperties(domainClass);
        }
Example #19
0
        private static ModelElement GetCompartmentElementFirstParentElement(this ModelElement modelElement)
        {
            // Get the domain class associated with model element.

            DomainClassInfo domainClass = modelElement.GetDomainClass();

            if (domainClass?.AllEmbeddedByDomainRoles?.Count == 1)
            {
                DomainRoleInfo roleInfo = domainClass.AllEmbeddedByDomainRoles[0];

                // Get a collection of all the links to this model element
                // Since this is in a compartment there should be at least one
                // There can be only one.

                ElementLink elementLink = roleInfo.GetElementLinks(modelElement)?.FirstOrDefault();
                return(elementLink?.LinkedElements?.FirstOrDefault(e => !modelElement.Equals(e)));
            }

            return(null);
        }
Example #20
0
        /// <summary>
        /// Returns the value of the property projected from the containing link to the element.
        /// </summary>
        /// <returns></returns>
        public static TResult GetProjectedLinkProperty <TResult>(this PatternElementSchema element, Func <IContainingLinkSchema, TResult> property)
        {
            if (element is AbstractElementSchema)
            {
                var viewLink = DomainRoleInfo.GetElementLinks <ViewHasElements>(element, ViewHasElements.AbstractElementSchemaDomainRoleId).FirstOrDefault();
                if (viewLink != null)
                {
                    return(property(viewLink));
                }

                var elementLink = DomainRoleInfo.GetElementLinks <ElementHasElements>(element, ElementHasElements.ChildElementDomainRoleId).FirstOrDefault();
                if (elementLink == null)
                {
                    throw new InvalidOperationException(Resources.AutoCreate_NoParentLinkFound);
                }

                return(property(elementLink));
            }

            if (element is ExtensionPointSchema)
            {
                var viewLink = DomainRoleInfo.GetElementLinks <ViewHasExtensionPoints>(element, ViewHasExtensionPoints.ExtensionPointSchemaDomainRoleId).FirstOrDefault();
                if (viewLink != null)
                {
                    return(property(viewLink));
                }

                var elementLink = DomainRoleInfo.GetElementLinks <ElementHasExtensionPoints>(element, ElementHasExtensionPoints.ChildElementDomainRoleId).FirstOrDefault();
                if (elementLink == null)
                {
                    throw new InvalidOperationException(Resources.AutoCreate_NoParentLinkFound);
                }

                return(property(elementLink));
            }


            throw new NotImplementedException();
        }
Example #21
0
            /// <summary>
            /// Add subtype links when possible
            /// </summary>
            /// <param name="element">An ModelHasFactType instance</param>
            /// <param name="store">The context store</param>
            /// <param name="notifyAdded">The listener to notify if elements are added during fixup</param>
            protected sealed override void ProcessElement(ModelHasFactType element, Store store, INotifyElementAdded notifyAdded)
            {
                SubtypeFact subTypeFact = element.FactType as SubtypeFact;
                ORMModel    model;

                if (null != (subTypeFact = element.FactType as SubtypeFact) &&
                    !subTypeFact.IsDeleted &&
                    null != (model = subTypeFact.Model))
                {
                    ObjectType rolePlayer = subTypeFact.Subtype;
                    FactType   nestedFact = rolePlayer.NestedFactType;
                    if (FactTypeShape.ShouldDrawObjectification(nestedFact))
                    {
                        Diagram.FixUpDiagram(model, nestedFact);
                        Diagram.FixUpDiagram(nestedFact, rolePlayer);
                    }
                    else
                    {
                        Diagram.FixUpDiagram(model, rolePlayer);
                    }
                    rolePlayer = subTypeFact.Supertype;
                    nestedFact = rolePlayer.NestedFactType;
                    if (FactTypeShape.ShouldDrawObjectification(nestedFact))
                    {
                        Diagram.FixUpDiagram(model, nestedFact);
                        Diagram.FixUpDiagram(nestedFact, rolePlayer);
                    }
                    else
                    {
                        Diagram.FixUpDiagram(model, rolePlayer);
                    }

                    object AllowMultipleShapes;
                    Dictionary <object, object> topLevelContextInfo;
                    bool containedAllowMultipleShapes;
                    if (!(containedAllowMultipleShapes = (topLevelContextInfo = store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo).ContainsKey(AllowMultipleShapes = MultiShapeUtility.AllowMultipleShapes)))
                    {
                        topLevelContextInfo.Add(AllowMultipleShapes, null);
                    }

                    foreach (PresentationViewsSubject presentationViewsSubject in DomainRoleInfo.GetElementLinks <PresentationViewsSubject>(model, PresentationViewsSubject.SubjectDomainRoleId))
                    {
                        ORMDiagram diagram;
                        if ((diagram = presentationViewsSubject.Presentation as ORMDiagram) != null)
                        {
                            ObjectType subtype = subTypeFact.Subtype;
                            // add a link shape for each object type shape on the diagram for the played role
                            foreach (ObjectTypeShape shapeElement in MultiShapeUtility.FindAllShapesForElement <ObjectTypeShape>(diagram, subtype))
                            {
                                diagram.FixUpLocalDiagram(subTypeFact);
                            }
                            FactType objectifiedFactType;
                            if (null != (objectifiedFactType = subtype.NestedFactType))
                            {
                                foreach (FactTypeShape shapeElement in MultiShapeUtility.FindAllShapesForElement <FactTypeShape>(diagram, objectifiedFactType))
                                {
                                    diagram.FixUpLocalDiagram(subTypeFact);
                                }
                            }
                        }
                    }

                    if (!containedAllowMultipleShapes)
                    {
                        topLevelContextInfo.Remove(AllowMultipleShapes);
                    }
                }
            }
Example #22
0
        /// <summary>
        /// Gets the dependencies for a specific model elements.
        /// </summary>
        /// <param name="modelElements">List of model elements to get the dependencies for.</param>
        /// <param name="options">Options.</param>
        /// <param name="dependenciesData">Data to add found dependencies to.</param>
        /// <returns>List of dependencies.</returns>
        public virtual DependenciesData GetDependencies(List <ModelElement> modelElements, DependenciesRetrivalOptions options, DependenciesData dependenciesData)
        {
            foreach (ModelElement modelElement in modelElements)
            {
                IDomainModelOwnable dmo = modelElement as IDomainModelOwnable;
                if (dmo == null)
                {
                    continue;
                }

                DomainClassInfo info = modelElement.GetDomainClass();
                foreach (DomainRoleInfo roleInfo in info.AllDomainRolesPlayed)
                {
                    if (roleInfo.DomainModel.Id == CoreDomainModel.DomainModelId)
                    {
                        continue;
                    }

                    if (options.ShouldExcludeDomainRelationship(roleInfo.DomainRelationship.Id, roleInfo.DomainModel.Id))
                    {
                        continue;
                    }

                    foreach (DependencyItemCategory category in GetAllCategories())
                    {
                        if (roleInfo.IsSource && category != DependencyItemCategory.Embedding &&
                            category != DependencyItemCategory.Referencing)
                        {
                            continue;
                        }

                        if (!roleInfo.IsSource && category != DependencyItemCategory.Embedded &&
                            category != DependencyItemCategory.Referenced)
                        {
                            continue;
                        }

                        if (dmo.Store.DomainDataAdvDirectory.IsEmbeddingRelationship(roleInfo.DomainRelationship.Id))
                        {
                            if (category != DependencyItemCategory.Embedded && category != DependencyItemCategory.Embedding)
                            {
                                continue;
                            }
                        }
                        else if (category == DependencyItemCategory.Embedded || category == DependencyItemCategory.Embedding)
                        {
                            continue;
                        }

                        // add origin dependency
                        dependenciesData.OriginDependencies.Add(new DependencyOriginItem(modelElement.Id, roleInfo.DomainRelationship, roleInfo));

                        // get link instances
                        System.Collections.ObjectModel.ReadOnlyCollection <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(modelElement, roleInfo.Id);
                        if (links.Count > 0)
                        {
                            foreach (ElementLink link in links)
                            {
                                if (category == DependencyItemCategory.Embedding || category == DependencyItemCategory.Referencing)
                                {
                                    if (options.ShouldExcludeDomainClass(DomainRoleInfo.GetTargetRolePlayer(link)))
                                    {
                                        continue;
                                    }
                                }
                                else
                                if (options.ShouldExcludeDomainClass(DomainRoleInfo.GetSourceRolePlayer(link)))
                                {
                                    continue;
                                }

                                if (options.ShouldExcludeDomainRelationship(link))
                                {
                                    continue;
                                }

                                DependencyItem item = new DependencyItem(link, category, roleInfo.DomainRelationship, roleInfo);
                                dependenciesData.ActiveDependencies.Add(item);
                            }
                        }
                    }
                }
            }

            return(dependenciesData);
        }
        /// <summary>
        /// Retrieves all children of a specific parent element. This includes all model elements that are reachable
        /// from the parent element through the embedding relationship.
        /// </summary>
        /// <param name="parentElement">Parent element to retrieve children for.</param>
        /// <param name="bOnlyLocal">Specifies if children of the found children of the given element should be processed too.</param>
        /// <returns>List of model elements that are embedded under the parent element. May be empty.</returns>
        public virtual List <ModelElement> GetChildren(ModelElement parentElement, bool bOnlyLocal)
        {
            List <ModelElement> allChildren = new List <ModelElement>();

            DomainClassInfo info = parentElement.GetDomainClass();
            ReadOnlyCollection <DomainRoleInfo> roleInfoCol = info.AllDomainRolesPlayed;

            foreach (DomainRoleInfo roleInfo in roleInfoCol)
            {
                if (roleInfo.IsSource)
                {
                    if ((parentElement as IDomainModelOwnable).Store.DomainDataAdvDirectory.IsEmbeddingRelationship(roleInfo.DomainRelationship.Id))
                    {
                        global::System.Collections.Generic.IList <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(parentElement, roleInfo.Id);
                        foreach (ElementLink link in links)
                        {
                            ModelElement child = DomainRoleInfo.GetTargetRolePlayer(link);
                            allChildren.Add(child);

                            if (!bOnlyLocal)
                            {
                                allChildren.AddRange(
                                    (child as IDomainModelOwnable).GetDomainModelServices().ElementChildrenProvider.GetChildren(child, bOnlyLocal));
                            }
                        }
                    }
                }
            }

            return(allChildren);
        }
Example #24
0
        /// <summary>
        /// Search a specific model element by using the given search criteria.
        /// </summary>
        /// <param name="modelElement">Model element to be searched.</param>
        /// <param name="criteria">Search criteria to use.</param>
        /// <param name="searchText">Text to search.</param>
        /// <param name="options">Search options.</param>
        /// <returns>Search result list if any found. Empty list otherwise.</returns>
        public virtual List <SearchResult> Search(ModelElement modelElement, SearchCriteriaEnum criteria, string searchText, SearchOptions options)
        {
            List <SearchResult> results = new List <SearchResult>();
            DomainClassInfo     info    = modelElement.GetDomainClass();
            Type modelElementType       = modelElement.GetType();

            #region properties
            if (criteria == SearchCriteriaEnum.Name ||
                criteria == SearchCriteriaEnum.NameAndType ||
                criteria == SearchCriteriaEnum.All ||
                criteria == SearchCriteriaEnum.Properties ||
                criteria == SearchCriteriaEnum.PropertiesWithoutName)
            {
                foreach (DomainPropertyInfo propertyInfo in info.AllDomainProperties)
                {
                    if (propertyInfo == info.NameDomainProperty &&
                        criteria != SearchCriteriaEnum.Name &&
                        criteria != SearchCriteriaEnum.NameAndType &&
                        criteria != SearchCriteriaEnum.Properties &&
                        criteria != SearchCriteriaEnum.All)
                    {
                        continue;
                    }
                    else if (propertyInfo != info.NameDomainProperty &&
                             criteria != SearchCriteriaEnum.All &&
                             criteria != SearchCriteriaEnum.Properties &&
                             criteria != SearchCriteriaEnum.PropertiesWithoutName)
                    {
                        continue;
                    }

                    object nameValue = GetPropertyValue(modelElement, modelElementType, propertyInfo.Name);
                    if (nameValue == null && System.String.IsNullOrEmpty(searchText))
                    {
                        SearchResult searchResult = new SearchResult();
                        searchResult.IsSuccessFull = true;
                        searchResult.Source        = modelElement;
                        searchResult.Reason        = "Property " + propertyInfo.Name + " is 'null'";

                        results.Add(searchResult);
                    }
                    else if (nameValue != null && !System.String.IsNullOrEmpty(searchText))
                    {
                        if (Contains(nameValue.ToString(), searchText, options))
                        {
                            SearchResult searchResult = new SearchResult();
                            searchResult.IsSuccessFull = true;
                            searchResult.Source        = modelElement;
                            searchResult.Reason        = "Property " + propertyInfo.Name + " contains '" + searchText + "'";

                            results.Add(searchResult);
                        }
                    }
                }
            }
            #endregion

            #region roles
            if (criteria == SearchCriteriaEnum.Roles ||
                criteria == SearchCriteriaEnum.All)
            {
                foreach (DomainRoleInfo roleInfo in info.AllDomainRolesPlayed)
                {
                    if (!roleInfo.IsSource)
                    {
                        continue;
                    }

                    DomainRelationshipInfo relInfo = roleInfo.DomainRelationship;
                    if (!IsLinkIncludedInDomainTree(modelElement.Store as DomainModelStore, relInfo.Id))
                    {
                        continue;
                    }

                    ReadOnlyCollection <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(modelElement, roleInfo.Id);
                    if (links.Count == 0 && String.IsNullOrEmpty(searchText))
                    {
                        SearchResult searchResult = new SearchResult();
                        searchResult.IsSuccessFull = true;
                        searchResult.Source        = modelElement;
                        searchResult.Reason        = "Role " + roleInfo.PropertyName + " is empty";

                        results.Add(searchResult);
                    }

                    foreach (ElementLink link in links)
                    {
                        ModelElement m = DomainRoleInfo.GetTargetRolePlayer(link);
                        if (m == null && System.String.IsNullOrEmpty(searchText))
                        {
                            SearchResult searchResult = new SearchResult();
                            searchResult.IsSuccessFull = true;
                            searchResult.Source        = modelElement;
                            searchResult.Reason        = "Role " + roleInfo.PropertyName + " is null";

                            results.Add(searchResult);
                        }
                        else if (m != null && !System.String.IsNullOrEmpty(searchText))
                        {
                            if (Contains((m as IDomainModelOwnable).DomainElementFullName, searchText, options))
                            {
                                SearchResult searchResult = new SearchResult();
                                searchResult.IsSuccessFull = true;
                                searchResult.Source        = modelElement;
                                searchResult.Reason        = "Role " + roleInfo.PropertyName + " contains '" + searchText + "' in the Full Name property on referenced element " + (m as IDomainModelOwnable).DomainElementFullName;

                                results.Add(searchResult);
                            }
                        }
                    }
                }
            }
            #endregion

            #region type
            if (criteria == SearchCriteriaEnum.Type ||
                criteria == SearchCriteriaEnum.NameAndType ||
                criteria == SearchCriteriaEnum.All)
            {
                if (Contains((modelElement as IDomainModelOwnable).DomainElementType, searchText, options) ||
                    Contains((modelElement as IDomainModelOwnable).DomainElementTypeDisplayName, searchText, options))
                {
                    SearchResult searchResult = new SearchResult();
                    searchResult.IsSuccessFull = true;
                    searchResult.Source        = modelElement;
                    searchResult.Reason        = "Type '" + searchText + "' found";

                    results.Add(searchResult);
                }
            }
            #endregion

            return(results);
        }
Example #25
0
        private void CustomWriteElements(SerializationContext serializationContext, ModelElement element, XmlWriter writer)
        {
            //DefaultWriteElements(context, element, writer);

            if (!serializationContext.Result.Failed)
            {
                writer.WriteAttributeString("modelVersion", ModelApp.ApplicationVersion.ToString());
            }


            // EntityModelHasDomainTypes
            // Non-public getter, use DomainRoleInfo methods.
            System.Collections.ObjectModel.ReadOnlyCollection <EntityModelHasDomainTypes> allEntityModelHasDomainTypesInstances = DomainRoleInfo.GetElementLinks <EntityModelHasDomainTypes>(element, EntityModelHasDomainTypes.EntityModelDomainRoleId);
            if (!serializationContext.Result.Failed && allEntityModelHasDomainTypesInstances.Count > 0)
            {
                writer.WriteStartElement("domainTypes");
                System.Type typeofEntityModelHasDomainTypes = typeof(EntityModelHasDomainTypes);
                foreach (EntityModelHasDomainTypes eachEntityModelHasDomainTypesInstance in allEntityModelHasDomainTypesInstances)
                {
                    if (serializationContext.Result.Failed)
                    {
                        break;
                    }

                    if (eachEntityModelHasDomainTypesInstance.GetType() != typeofEntityModelHasDomainTypes)
                    {   // Derived relationships will be serialized in full-form.
                        DomainClassXmlSerializer derivedRelSerializer = serializationContext.Directory.GetSerializer(eachEntityModelHasDomainTypesInstance.GetDomainClass().Id);
                        System.Diagnostics.Debug.Assert(derivedRelSerializer != null, "Cannot find serializer for " + eachEntityModelHasDomainTypesInstance.GetDomainClass().Name + "!");
                        derivedRelSerializer.Write(serializationContext, eachEntityModelHasDomainTypesInstance, writer);
                    }
                    else
                    {   // No need to serialize the relationship itself, just serialize the role-player directly.
                        ModelElement             targetElement    = eachEntityModelHasDomainTypesInstance.DomainType;
                        DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer(targetElement.GetDomainClass().Id);
                        System.Diagnostics.Debug.Assert(targetSerializer != null, "Cannot find serializer for " + targetElement.GetDomainClass().Name + "!");
                        targetSerializer.Write(serializationContext, targetElement, writer);
                    }
                }
                writer.WriteEndElement();
            }

            // EntityModelHasPersistentTypes
            // Non-public getter, use DomainRoleInfo methods.
            System.Collections.ObjectModel.ReadOnlyCollection <EntityModelHasPersistentTypes> allEntityModelHasPersistentTypesInstances = DomainRoleInfo.GetElementLinks <EntityModelHasPersistentTypes>(element, EntityModelHasPersistentTypes.EntityModelDomainRoleId);
            if (!serializationContext.Result.Failed && allEntityModelHasPersistentTypesInstances.Count > 0)
            {
                writer.WriteStartElement("persistentTypes");
                Type typeofEntityModelHasPersistentTypes = typeof(EntityModelHasPersistentTypes);
                foreach (EntityModelHasPersistentTypes eachEntityModelHasPersistentTypesInstance in allEntityModelHasPersistentTypesInstances)
                {
                    if (serializationContext.Result.Failed)
                    {
                        break;
                    }

                    if (eachEntityModelHasPersistentTypesInstance.GetType() != typeofEntityModelHasPersistentTypes)
                    {   // Derived relationships will be serialized in full-form.
                        DomainClassXmlSerializer derivedRelSerializer = serializationContext.Directory.GetSerializer(eachEntityModelHasPersistentTypesInstance.GetDomainClass().Id);
                        System.Diagnostics.Debug.Assert(derivedRelSerializer != null, "Cannot find serializer for " + eachEntityModelHasPersistentTypesInstance.GetDomainClass().Name + "!");
                        derivedRelSerializer.Write(serializationContext, eachEntityModelHasPersistentTypesInstance, writer);
                    }
                    else
                    {   // No need to serialize the relationship itself, just serialize the role-player directly.
                        ModelElement             targetElement    = eachEntityModelHasPersistentTypesInstance.Element;
                        DomainClassXmlSerializer targetSerializer = serializationContext.Directory.GetSerializer(targetElement.GetDomainClass().Id);
                        System.Diagnostics.Debug.Assert(targetSerializer != null, "Cannot find serializer for " + targetElement.GetDomainClass().Name + "!");
                        targetSerializer.Write(serializationContext, targetElement, writer);
                    }
                }
                writer.WriteEndElement();
            }
        }
Example #26
0
        public override bool ModelCanMerge(CopyPaste.ModelProtoElement protoElement, CopyPaste.ModelProtoGroup protoGroup)
        {
            if (protoElement != null)
            {
                DomainClassInfo elementDomainInfo = this.Partition.DomainDataDirectory.GetDomainClass(protoElement.DomainClassId);
                if (elementDomainInfo.IsDerivedFrom(global::Tum.PDE.LanguageDSL.DomainClass.DomainClassId))
                {
                    if (protoGroup.Operation == ModelProtoGroupOperation.Move)
                    {
                        foreach (global::Tum.PDE.LanguageDSL.LibraryModelContextHasClasses link in DomainRoleInfo.GetElementLinks <global::Tum.PDE.LanguageDSL.LibraryModelContextHasClasses>(this, global::Tum.PDE.LanguageDSL.LibraryModelContextHasClasses.LibraryModelContextDomainRoleId))
                        {
                            if (link.DomainClass.Id == protoElement.ElementId)
                            {
                                return(false);
                            }
                        }
                    }
                    return(true);
                }
                else if (elementDomainInfo.IsDerivedFrom(global::Tum.PDE.LanguageDSL.DomainRelationship.DomainClassId))
                {
                    if (protoGroup.Operation == ModelProtoGroupOperation.Move)
                    {
                        foreach (global::Tum.PDE.LanguageDSL.LibraryModelContextHasRelationships link in DomainRoleInfo.GetElementLinks <global::Tum.PDE.LanguageDSL.LibraryModelContextHasRelationships>(this, global::Tum.PDE.LanguageDSL.LibraryModelContextHasRelationships.LibraryModelContextDomainRoleId))
                        {
                            if (link.DomainRelationship.Id == protoElement.ElementId)
                            {
                                return(false);
                            }
                        }
                    }

                    // see if source and target domain classes are copied here
                    List <ModelProtoElement> elements = protoGroup.GetEmbeddedElements(this.Partition, protoElement);
                    for (int i = 0; i < elements.Count; i++)
                    {
                        if (elements[i].Name == "DomainRole")
                        {
                            List <ModelProtoLink> links = protoGroup.GetReferenceLinks(this.Partition, elements[i]);
                            foreach (ModelProtoLink link in links)
                            {
                                if (link.Name == "DomainRoleReferencesRolePlayer")
                                {
                                    ModelProtoRolePlayer rP = link.GetTargetRolePlayer(this.Partition);
                                    // see if the target element is beeing copied or is already in the model
                                    if (!protoGroup.HasProtoElementFor(rP.RolePlayerId, this.Partition))
                                    {
                                        ModelElement m = this.Store.ElementDirectory.FindElement(rP.RolePlayerId);
                                        if (m == null)
                                        {
                                            if (!this.MetaModel.HasElement(rP.ElementName))
                                            {
                                                return(false);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    return(true);
                }
            }
            return(false);
        }
Example #27
0
        /// <summary>
        /// Creates missing links for the added shape.
        /// </summary>
        /// <param name="shapeAdded">Shape added.</param>
        public virtual void FixUpMissingLinkShapes(NodeShape shapeAdded)
        {
            DiagramDomainDataDirectory data = this.Store.DomainDataAdvDirectory.ResolveExtensionDirectory <DiagramDomainDataDirectory>();

            if (data == null)
            {
                throw new ArgumentNullException("DiagramDomainDataDirectory can not be null");
            }

            ShapeClassInfo info;

            data.ShapeClassInfos.TryGetValue(shapeAdded.GetDomainClass().Id, out info);
            if (info == null)
            {
                return;
            }

            ModelLinkAddRuleForRSShapes.RSShapesFactoryHelper        factory        = this.GetRSShapesFactoryHelper();
            ModelLinkAddRuleForMappingRSShapes.RSShapesFactoryHelper factoryMapping = this.GetMappingRSShapesFactoryHelper();

            if (factory != null)
            {
                if (info.RelationshipSourceRoleTypes.Count > 0)
                {
                    foreach (Guid rel in info.RelationshipSourceRoleTypes)
                    {
                        ReadOnlyCollection <DomainModelLink> links = DomainRoleInfo.GetElementLinks <DomainModelLink>(shapeAdded.Element, rel);
                        foreach (DomainModelLink link in links)
                        {
                            factory.AddRSShapesForElement(link);
                        }
                    }
                }

                if (info.RelationshipTargetRoleTypes.Count > 0)
                {
                    foreach (Guid rel in info.RelationshipTargetRoleTypes)
                    {
                        ReadOnlyCollection <DomainModelLink> links = DomainRoleInfo.GetElementLinks <DomainModelLink>(shapeAdded.Element, rel);
                        foreach (DomainModelLink link in links)
                        {
                            factory.AddRSShapesForElement(link);
                        }
                    }
                }
            }

            if (factoryMapping != null)
            {
                if (info.MappingRelationshipSourceRoleTypes.Count > 0)
                {
                    foreach (Guid rel in info.MappingRelationshipSourceRoleTypes)
                    {
                        ReadOnlyCollection <DomainModelLink> links = DomainRoleInfo.GetElementLinks <DomainModelLink>(shapeAdded.Element, rel);
                        foreach (DomainModelLink link in links)
                        {
                            factoryMapping.AddRSShapesForElement(link);
                        }
                    }
                }

                if (info.MappingRelationshipTargetRoleTypes.Count > 0)
                {
                    foreach (Guid rel in info.MappingRelationshipTargetRoleTypes)
                    {
                        ReadOnlyCollection <DomainModelLink> links = DomainRoleInfo.GetElementLinks <DomainModelLink>(shapeAdded.Element, rel);
                        foreach (DomainModelLink link in links)
                        {
                            factoryMapping.AddRSShapesForElement(link);
                        }
                    }
                }
            }

            foreach (Diagram d in this.IncludedDiagrams)
            {
                d.FixUpMissingLinkShapes(shapeAdded);
            }

            foreach (NodeShape s in shapeAdded.Children)
            {
                s.FixUpMissingLinkShapes();
            }
        }
Example #28
0
        protected override void Initialize()
        {
            base.Initialize();

            List <Guid> relationshipOrder;

            ParentChildrenMapping[this.ModelData.CurrentModelContext.ModelContextId].TryGetValue(this.ElementInfo.Id, out relationshipOrder);

            if (relationshipOrder != null)
            {
                foreach (Guid relationshipDCId in relationshipOrder)
                {
                    DomainRelationshipInfo relationshipInfo = this.Store.DomainDataDirectory.GetDomainRelationship(relationshipDCId);
                    if (DoHookUpEvents)
                    {
                        DomainRelationshipAdvancedInfo advancedInfo = this.Store.DomainDataAdvDirectory.GetRelationshipInfo(relationshipDCId);
                        //if (!advancedInfo.TargetRoleIsUIBrowsable || !advancedInfo.TargetRoleIsGenerated)
                        //if (!advancedInfo.SourceRoleIsUIBrowsable || !advancedInfo.SourceRoleIsGenerated)
                        if (!advancedInfo.SourceRoleIsUIBrowsable)
                        {
                            continue;
                        }

                        // Subscribe to add and delete element events
                        this.EventManager.GetEvent <ModelElementLinkAddedEvent>().Subscribe(
                            this.Store.DomainDataDirectory.GetDomainRelationship(relationshipInfo.Id), true,
                            this.Element.Id, new System.Action <ElementAddedEventArgs>(OnChildElementAdded));

                        this.EventManager.GetEvent <ModelElementLinkDeletedEvent>().Subscribe(
                            this.Store.DomainDataDirectory.GetDomainRelationship(relationshipInfo.Id), true,
                            this.Element.Id, new System.Action <ElementDeletedEventArgs>(OnChildElementDeleted));

                        // Subscribe to role player change events
                        this.EventManager.GetEvent <ModelRolePlayerChangedEvent>().Subscribe(
                            this.Store.DomainDataDirectory.GetDomainRelationship(relationshipInfo.Id), true,
                            this.Element.Id, new System.Action <RolePlayerChangedEventArgs>(OnRolePlayerChanged));

                        this.EventManager.GetEvent <ModelRolePlayerMovedEvent>().Subscribe(
                            this.Store.DomainDataDirectory.GetDomainRelationship(relationshipInfo.Id),
                            this.Element.Id, new System.Action <RolePlayerOrderChangedEventArgs>(OnRolePlayerMoved));
                    }

                    // element link order
                    this.ElementLinkOrder.Add(relationshipInfo.Id);

                    System.Collections.ObjectModel.ReadOnlyCollection <ElementLink> links = DomainRoleInfo.GetElementLinks <ElementLink>(this.Element, GetSourceDomainRole(relationshipInfo).Id);
                    foreach (ElementLink link in links)
                    {
                        BaseModelElementTreeViewModel vm = AddChildElement(link, DomainRoleInfo.GetTargetRolePlayer(link), true);
                        vm.RelationshipInfo = relationshipInfo;
                        vm.ElementInfo      = GetTargetDomainRole(relationshipInfo).RolePlayer;
                    }
                }
            }
        }