示例#1
0
 internal static int GetDefaultMemberCount(LinkedElementCollection<ModelProperty> properties)
 {
     return properties.FindAll(
         delegate(ModelProperty property)
         {
             return (property.DefaultMember);
         }
         ).Count;
 }
示例#2
0
 internal static int GetPrimaryKeyCount(LinkedElementCollection<ModelProperty> properties)
 {
     return properties.FindAll(
         delegate(ModelProperty property)
         {
             return (property.KeyType == KeyType.PrimaryKey);
         }
         ).Count;
 }
示例#3
0
 internal static int GetDebuggerDisplayCount(LinkedElementCollection<ModelProperty> properties)
 {
     return properties.FindAll(
         delegate(ModelProperty property)
         {
             return (property.DebuggerDisplay);
         }
         ).Count;
 }
 public void BuildConstructorProperties(LinkedElementCollection<Property> properties)
 {
     this.PushIndent("\t\t\t");
     foreach (Property prop in properties)
     {
         this.WriteLine(prop.Name + " = " + prop.Name.Substring(0, 1).ToLower() + prop.Name.Substring(1, prop.Name.Length - 1) + ";");
     }
     this.PopIndent();
 }
示例#5
0
 internal static List<ModelProperty> GetCompositeKeys(LinkedElementCollection<ModelProperty> properties)
 {
     return properties.FindAll(
         delegate(ModelProperty property)
         {
             return (property.KeyType == KeyType.CompositeKey);
         }
         );
 }
		private void RemoveDataElement(Store store, LinkedElementCollection<DataMember> dataElements, DataMember dataElement)
		{
			if(dataElement != null)
			{
				using(Transaction transaction = store.TransactionManager.BeginTransaction())
				{
					dataElements.Remove(dataElement);
					transaction.Commit();
				}
			}		
		}
 public void BuildProperties(LinkedElementCollection<Property> properties)
 {
     int count = 0;
     foreach (Property prop in properties.ToArray().AsQueryable().OrderBy(prp=>prp.Order))
     {
         if (count == 0)
             this.Write(prop.Type + " " + prop.Name.Substring(0, 1).ToLower() + prop.Name.Substring(1, prop.Name.Length-1));
         else
             this.Write(", " + prop.Type + " " + prop.Name.Substring(0, 1).ToLower() + prop.Name.Substring(1, prop.Name.Length - 1));
         count++;
     }
 }
		private ModelElementReference GetDataElement(LinkedElementCollection<DataMember> dataElements, Guid linkId)
		{
			ModelElementReference dataElementFound = null;

			foreach(DataMember dataElement in dataElements)
		    {
				ModelElementReference dataContractDataElement = dataElement as ModelElementReference;

		        if(dataContractDataElement != null && dataContractDataElement.ModelElementGuid == linkId)
		        {
		            dataElementFound = dataContractDataElement;
		            break;
		        }
		    }

		    return dataElementFound;
		}
 public string BuildPropertiesToString(LinkedElementCollection<Property> properties)
 {
     StringBuilder sb = new StringBuilder();
     int count = 1;
     sb.Append("string.Format(\"Type: {0}");
     foreach (Property prop in properties)
     {
         sb.Append(", " + prop.Name + " {"+count+"}");
         count++;
     }
     sb.Append("\",GetType().Name");
     foreach (Property prop in properties)
     {
         sb.Append(", " + prop.Name);
         count++;
     }
     sb.Append(")");
     return sb.ToString();
 }
示例#10
0
			public static Role GetImplicitBooleanRole(LinkedElementCollection<RoleBase> roleCollection)
			{
				int roleCount = roleCollection.Count;
				if (roleCount == 2)
				{
					// We set up the boolean role as the second role, although there
					// is nothing to stop it from being first. Walk backwards to hit the
					// most likely case.
					for (int i = 1; i >= 0; --i)
					{
						Role implicitBooleanRole;
						ObjectType rolePlayer;
						if (null != (implicitBooleanRole = (roleCollection[i] as Role)) &&
							null != (rolePlayer = implicitBooleanRole.RolePlayer) &&
							rolePlayer.IsImplicitBooleanValue)
						{
							return implicitBooleanRole;
						}
					}
				}
				return null;
			}
示例#11
0
        private void MapClrAttributesToAttributes(LinkedElementCollection <ClrAttribute> clrAttributes, LinkedElementCollection <Attribute> attributes, Store store)
        {
            attributes.Clear();

            foreach (var clrAttribute in clrAttributes)
            {
                var attribute = new Attribute(store);
                attribute.Name = clrAttribute.Name;

                foreach (var clrAttributeParameter in clrAttribute.Parameters)
                {
                    var attributeParameter = new AttributeParameter(store);
                    attributeParameter.Name  = clrAttributeParameter.Name;
                    attributeParameter.Value = clrAttributeParameter.Value;

                    attribute.Parameters.Add(attributeParameter);
                }

                attributes.Add(attribute);
            }
        }
示例#12
0
		private static IList FilterElementsFromElementSchemaForAutomation(LinkedElementCollection<AutomationSettingsSchema> result)
		{
			return ShapeExtensions.FilterElementsFromCompartment<AutomationSettingsSchema, string>(result,
				item => (item.Classification == Runtime.AutomationSettingsClassification.General),
				item => string.Concat(item.AutomationType, item.Name));
		}
示例#13
0
        /// <summary>
        /// This guarantees that we have an instance for every possible Name Generator type.
        /// </summary>
        private void FullyPopulateRefinements()
        {
            LinkedElementCollection <NameGenerator> currentChildren = RefinedByGeneratorCollection;
            DomainClassInfo contextDomainClass = GetDomainClass();
            ReadOnlyCollection <DomainClassInfo> requiredDescendantsCollection = contextDomainClass.LocalDescendants;
            int requiredDescendantsCount = requiredDescendantsCollection.Count;

            Type[] requiredUsageTypes = GetSupportedNameUsageTypes();
            int    requiredUsageCount = requiredUsageTypes.Length;

            if (requiredDescendantsCount != 0 || requiredUsageCount != 0)
            {
                DomainClassInfo[] requiredDescendants = new DomainClassInfo[requiredDescendantsCount];
                requiredDescendantsCollection.CopyTo(requiredDescendants, 0);
                int missingDescendantsCount = requiredDescendantsCount;
                int missingUsageCount       = requiredUsageCount;
                foreach (NameGenerator currentChild in currentChildren)
                {
                    if (missingDescendantsCount != 0)
                    {
                        int index = Array.IndexOf <DomainClassInfo>(requiredDescendants, currentChild.GetDomainClass());
                        if (index != -1)
                        {
                            requiredDescendants[index] = null;
                        }
                    }
                    Type nameUsage = currentChild.NameUsageType;
                    if (nameUsage == null)
                    {
                        currentChild.FullyPopulateRefinements();
                    }
                    else if (missingUsageCount != 0)
                    {
                        int index = Array.IndexOf <Type>(requiredUsageTypes, nameUsage);
                        if (index != -1)
                        {
                            requiredUsageTypes[index] = null;
                        }
                    }
                }
                if (missingDescendantsCount != 0)
                {
                    for (int i = 0; i < requiredDescendantsCount; ++i)
                    {
                        DomainClassInfo classInfo = requiredDescendants[i];
                        if (classInfo != null)
                        {
                            CreateRefinement(classInfo, null).FullyPopulateRefinements();;
                        }
                    }
                }
                if (missingUsageCount != 0)
                {
                    for (int i = 0; i < requiredUsageCount; ++i)
                    {
                        Type usageType = requiredUsageTypes[i];
                        if (usageType != null)
                        {
                            CreateRefinement(contextDomainClass, usageType);
                        }
                    }
                }
            }
        }
示例#14
0
		/// <summary>
		/// Verify that all <see cref="ReadingOrder"/>s have unique <see cref="ReadingOrder.RoleCollection">role collections</see>
		/// </summary>
		/// <param name="element">A <see cref="FactType"/></param>
		private static void DelayValidateReadingOrderCollation(ModelElement element)
		{
			if (element.IsDeleted)
			{
				return;
			}
			FactType factType = (FactType)element;
			LinkedElementCollection<ReadingOrder> ordersCollection = factType.ReadingOrderCollection;
			int orderCount = ordersCollection.Count;
			if (orderCount > 1)
			{
				// Get all orders in a collatable form, starting by caching information locally
				// so it is easily accessed. Note that this will also change the collection we're
				// iterating so we need to be careful about changes.
				ReadingOrder[] orders = new ReadingOrder[orderCount];
				ordersCollection.CopyTo(orders, 0);
				LinkedElementCollection<RoleBase>[] roleCollections = new LinkedElementCollection<RoleBase>[orderCount];
				for (int i = 0; i < orderCount; ++i)
				{
					roleCollections[i] = orders[i].RoleCollection;
				}

				// Priority is top down, so we move later readings into a higher reading order
				for (int i = 0; i < orderCount; ++i)
				{
					ReadingOrder currentOrder = orders[i];
					for (int j = i + 1; j < orderCount; ++j)
					{
						ReadingOrder compareToOrder = orders[j];
						if (compareToOrder != null) // Will be null if it has already been recognized as a duplicate
						{
							// These should all have the same count, but it doesn't hurt to be defensive
							LinkedElementCollection<RoleBase> currentRoles = roleCollections[i];
							LinkedElementCollection<RoleBase> compareToRoles = roleCollections[j];
							int roleCount = currentRoles.Count;
							if (roleCount == compareToRoles.Count)
							{
								int k = 0;
								for (; k < roleCount; ++k)
								{
									if (currentRoles[k] != compareToRoles[k])
									{
										break;
									}
								}
								if (k == roleCount)
								{
									// Order is the same, collate the later readings up to the current order
									ReadOnlyCollection<ReadingOrderHasReading> readingLinks = ReadingOrderHasReading.GetLinksToReadingCollection(compareToOrder);
									int readingCount = readingLinks.Count;
									for (int l = 0; l < readingCount; ++l)
									{
										readingLinks[l].ReadingOrder = currentOrder;
									}
									orders[j] = null;
								}
							}
						}
					}
				}
			}
		}
        /// <summary>
        /// Implements <see cref="IModelErrorActivation.ActivateModelError"/> for
        /// the <see cref="ValueComparisonConstraintOperatorNotSpecifiedError"/>
        /// </summary>
        protected new bool ActivateModelError(ModelError error)
        {
            ValueComparisonConstraintOperatorNotSpecifiedError operatorError;
            ValueComparisonRolesNotComparableError             comparabilityError;
            ValueComparisonConstraint constraint;
            Store store;
            bool  retVal = true;

            if (null != (operatorError = error as ValueComparisonConstraintOperatorNotSpecifiedError))
            {
                store      = Store;
                constraint = operatorError.ValueComparisonConstraint;
                EditorUtility.ActivatePropertyEditor(
                    (store as IORMToolServices).ServiceProvider,
                    DomainTypeDescriptor.CreatePropertyDescriptor(constraint, ValueComparisonConstraint.OperatorDomainPropertyId),
                    true);
            }
            else if (null != (comparabilityError = error as ValueComparisonRolesNotComparableError))
            {
                constraint = comparabilityError.ValueComparisonConstraint;
                LinkedElementCollection <Role> constraintRoles = constraint.RoleCollection;
                Role role1;
                Role role2;
                ObjectTypePlaysRole rolePlayerLink1;
                ObjectTypePlaysRole rolePlayerLink2;
                ObjectType          rolePlayer1 = null;
                ObjectType          rolePlayer2 = null;
                Role[] valueRoles1 = null;
                Role[] valueRoles2 = null;
                // The default behavior is to activate the role sequence
                // for editing. However, if the problem is with a single
                // resolved value type, and the units are correct, then
                // we need to select the first directly detached object.
                if (constraintRoles.Count == 2 &&
                    null != (rolePlayerLink1 = ObjectTypePlaysRole.GetLinkToRolePlayer(role1 = constraintRoles[0])) &&
                    null != (rolePlayerLink2 = ObjectTypePlaysRole.GetLinkToRolePlayer(role2 = constraintRoles[1])) &&
                    (rolePlayerLink1.RolePlayer == rolePlayerLink2.RolePlayer ||
                     (null != (valueRoles1 = role1.GetValueRoles()) &&
                      null != (valueRoles2 = role2.GetValueRoles()) &&
                      DataType.IsComparableValueType(rolePlayer1 = valueRoles1[0].RolePlayer, rolePlayer2 = valueRoles2[0].RolePlayer, !constraint.IsDirectional))))
                {
                    bool verifiedReferenceMode = true;
                    if (valueRoles1 != null)
                    {
                        ORMModel      model          = null;
                        ReferenceMode referenceMode1 = (valueRoles1.Length > 1) ?
                                                       ReferenceMode.FindReferenceModeFromEntityNameAndValueName(rolePlayer1.Name, valueRoles1[1].RolePlayer.Name, model = constraint.ResolvedModel) :
                                                       null;
                        ReferenceMode referenceMode2 = (valueRoles2.Length > 1) ?
                                                       ReferenceMode.FindReferenceModeFromEntityNameAndValueName(rolePlayer2.Name, valueRoles2[1].RolePlayer.Name, model ?? constraint.ResolvedModel) :
                                                       null;
                        bool referenceMode1IsUnit = referenceMode1 != null && referenceMode1.Kind.ReferenceModeType == ReferenceModeType.UnitBased;
                        bool referenceMode2IsUnit = referenceMode2 != null && referenceMode2.Kind.ReferenceModeType == ReferenceModeType.UnitBased;
                        verifiedReferenceMode = referenceMode1IsUnit ? (referenceMode2IsUnit && referenceMode1 == referenceMode2) : !referenceMode2IsUnit;
                    }
                    if (verifiedReferenceMode)
                    {
                        // Find a connected role player
                        foreach (ExternalConstraintLink constraintLink in MultiShapeUtility.GetEffectiveAttachedLinkShapes <ExternalConstraintLink>(this))
                        {
                            FactTypeShape factTypeShape;
                            if (constraintLink.AssociatedConstraintRole.Role == role1 &&
                                null != (factTypeShape = constraintLink.FromShape as FactTypeShape))
                            {
                                foreach (RolePlayerLink rolePlayerLinkShape in MultiShapeUtility.GetEffectiveAttachedLinkShapes <RolePlayerLink>(factTypeShape))
                                {
                                    if (rolePlayerLinkShape.AssociatedRolePlayerLink == rolePlayerLink1)
                                    {
                                        Diagram.ActiveDiagramView.Selection.Set(new DiagramItem(rolePlayerLinkShape.ToShape));
                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                }
                ActivateNewRoleSequenceConnectAction(null);
            }
            else
            {
                retVal = base.ActivateModelError(error);
            }
            return(retVal);
        }
            /// <summary>
            /// Binarizes the unary <see cref="FactType"/> specified by <paramref name="unaryFactType"/>, defaulting
            /// to using open-world assumption. The caller is responsible for making sure <paramref name="unaryFactType"/>
            /// is in fact a unary fact type.
            /// </summary>
            public static void BinarizeUnary(FactType unaryFactType, INotifyElementAdded notifyAdded)
            {
                Partition partition = unaryFactType.Partition;
                Store     store     = partition.Store;
                IHasAlternateOwner <FactType>      toAlternateOwner;
                IAlternateElementOwner <FactType>  alternateFactTypeOwner = (null == (toAlternateOwner = unaryFactType as IHasAlternateOwner <FactType>)) ? null : toAlternateOwner.AlternateOwner;
                LinkedElementCollection <RoleBase> roleCollection         = unaryFactType.RoleCollection;

                Debug.Assert(roleCollection.Count == 1, "Unaries should only have one role.");

                Role   unaryRole = (Role)roleCollection[0];
                string implicitBooleanValueTypeName = GetImplicitBooleanValueTypeName(unaryRole);

                // UNDONE: We are using open-world assumption now
                // Setup the mandatory constraint (for closed-world assumption)
                //MandatoryConstraint mandatoryConstraint = MandatoryConstraint.CreateSimpleMandatoryConstraint(unaryRole);
                //mandatoryConstraint.Model = unaryFactType.Model;
                //if (notifyAdded != null)
                //{
                //    notifyAdded.ElementAdded(mandatoryConstraint, true);
                //}

                // Setup the uniqueness constraint (to make the newly binarized FactType valid)
                if (unaryRole.SingleRoleAlethicUniquenessConstraint == null)
                {
                    UniquenessConstraint uniquenessConstraint = UniquenessConstraint.CreateInternalUniquenessConstraint(unaryFactType);
                    uniquenessConstraint.RoleCollection.Add(unaryRole);
                    if (notifyAdded != null)
                    {
                        notifyAdded.ElementAdded(uniquenessConstraint, true);
                    }
                }

                // Setup the boolean role (to make the FactType a binary)
                Role implicitBooleanRole = new Role(partition, null);

                implicitBooleanRole.Name = unaryRole.Name;

                // Setup the boolean value type (because the boolean role needs a role player)

                IAlternateElementOwner <ObjectType> alternateObjectTypeOwner = null;
                DomainClassInfo alternateCtor =
                    (null != alternateFactTypeOwner &&
                     null != (alternateObjectTypeOwner = alternateFactTypeOwner as IAlternateElementOwner <ObjectType>)) ?
                    alternateObjectTypeOwner.GetOwnedElementClassInfo(typeof(ObjectType)) :
                    null;
                PropertyAssignment implicitBooleanProperty  = new PropertyAssignment(ObjectType.IsImplicitBooleanValueDomainPropertyId, true);
                ObjectType         implicitBooleanValueType = (alternateCtor != null) ?
                                                              (ObjectType)partition.ElementFactory.CreateElement(alternateCtor, implicitBooleanProperty) :
                                                              new ObjectType(partition, implicitBooleanProperty);
                Dictionary <object, object> contextInfo = store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo;
                object duplicateNamesKey         = ORMModel.AllowDuplicateNamesKey;
                bool   removeDuplicateNamesKey   = false;
                object duplicateSignaturesKey    = ORMModel.BlockDuplicateReadingSignaturesKey;
                bool   addDuplicateSignaturesKey = false;

                try
                {
                    if (!contextInfo.ContainsKey(duplicateNamesKey))
                    {
                        contextInfo[duplicateNamesKey] = null;
                        removeDuplicateNamesKey        = true;
                    }
                    if (contextInfo.ContainsKey(duplicateSignaturesKey))
                    {
                        contextInfo[duplicateSignaturesKey] = null;
                        addDuplicateSignaturesKey           = true;
                    }
                    implicitBooleanValueType.Name = implicitBooleanValueTypeName;
                    if (alternateCtor != null)
                    {
                        ((IHasAlternateOwner <ObjectType>)implicitBooleanValueType).AlternateOwner = alternateObjectTypeOwner;
                    }
                    else
                    {
                        implicitBooleanValueType.Model = unaryFactType.ResolvedModel;
                    }
                    if (notifyAdded != null)
                    {
                        notifyAdded.ElementAdded(implicitBooleanValueType, true);
                    }
                }
                finally
                {
                    if (removeDuplicateNamesKey)
                    {
                        contextInfo.Remove(duplicateNamesKey);
                    }
                    if (addDuplicateSignaturesKey)
                    {
                        contextInfo[duplicateSignaturesKey] = null;
                    }
                }
                implicitBooleanValueType.DataType = store.ElementDirectory.FindElements <TrueOrFalseLogicalDataType>(false)[0];

                // Set value constraint on implicit boolean ValueType for open-world assumption
                ValueTypeValueConstraint implicitBooleanValueConstraint = implicitBooleanValueType.ValueConstraint
                                                                              = new ValueTypeValueConstraint(partition, null);

                // Add the true-only ValueRange to the value constraint for open-world assumption
                implicitBooleanValueConstraint.ValueRangeCollection.Add(new ValueRange(partition,
                                                                                       new PropertyAssignment(ValueRange.MinValueDomainPropertyId, bool.TrueString),
                                                                                       new PropertyAssignment(ValueRange.MaxValueDomainPropertyId, bool.TrueString)));

                // Make the boolean value type the role player for the implicit boolean role
                implicitBooleanRole.RolePlayer = implicitBooleanValueType;

                // Add the boolean role to the FactType
                roleCollection.Add(implicitBooleanRole);
                if (notifyAdded != null)
                {
                    notifyAdded.ElementAdded(implicitBooleanRole, true);
                }
            }
            public static void ProcessFactType(FactType factType, INotifyElementAdded notifyAdded)
            {
                LinkedElementCollection <RoleBase> roleCollection = factType.RoleCollection;
                int roleCollectionCount = roleCollection.Count;

                if (roleCollectionCount == 1)
                {
                    // If we have a unary, binarize it
                    BinarizeUnary(factType, notifyAdded);
                    return;
                }
                else if (roleCollectionCount == 2)
                {
                    // If we have a binary that has an implicit boolean role in it, make sure it matches the pattern
                    Role implicitBooleanRole = GetImplicitBooleanRole(roleCollection);
                    if (implicitBooleanRole != null)
                    {
                        Role unaryRole = implicitBooleanRole.OppositeRole.Role;
                        Debug.Assert(unaryRole != null);
                        // Make sure the implicit boolean role has the same name as the unary role
                        implicitBooleanRole.Name = unaryRole.Name;
                        string implicitBooleanValueTypeName = GetImplicitBooleanValueTypeName(unaryRole);
                        if (implicitBooleanRole.RolePlayer.Name != implicitBooleanValueTypeName)
                        {
                            Dictionary <object, object> contextInfo = factType.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo;
                            object duplicateNamesKey         = ORMModel.AllowDuplicateNamesKey;
                            bool   removeDuplicateNamesKey   = false;
                            object duplicateSignaturesKey    = ORMModel.BlockDuplicateReadingSignaturesKey;
                            bool   addDuplicateSignaturesKey = false;
                            try
                            {
                                if (!contextInfo.ContainsKey(duplicateNamesKey))
                                {
                                    contextInfo[duplicateNamesKey] = null;
                                    removeDuplicateNamesKey        = true;
                                }
                                if (contextInfo.ContainsKey(duplicateSignaturesKey))
                                {
                                    contextInfo.Remove(duplicateSignaturesKey);
                                    addDuplicateSignaturesKey = true;
                                }
                                implicitBooleanRole.RolePlayer.Name = implicitBooleanValueTypeName;
                            }
                            finally
                            {
                                if (removeDuplicateNamesKey)
                                {
                                    contextInfo.Remove(duplicateNamesKey);
                                }
                                if (addDuplicateSignaturesKey)
                                {
                                    contextInfo[duplicateSignaturesKey] = null;
                                }
                            }
                        }
                        if (!ValidateConstraints(unaryRole, implicitBooleanRole) || !ValidateImplicitBooleanValueType(implicitBooleanRole.RolePlayer))
                        {
                            LinkedElementCollection <RoleBase> roles = factType.RoleCollection;
                            DebinarizeUnary(roles, false, notifyAdded);
                            // Append to the reading orders
                            LinkedElementCollection <ReadingOrder> readingOrders = factType.ReadingOrderCollection;
                            int readingOrderCount = readingOrders.Count;
                            for (int i = 0; i < readingOrderCount; ++i)
                            {
                                ReadingOrder order = readingOrders[i];
                                LinkedElementCollection <RoleBase> readingRoles = order.RoleCollection;
                                if (!readingRoles.Contains(implicitBooleanRole))
                                {
                                    readingRoles.Add(implicitBooleanRole);
                                    LinkedElementCollection <Reading> readings = order.ReadingCollection;
                                    int readingCount = readings.Count;
                                    for (int j = 0; j < readingCount; ++j)
                                    {
                                        readings[j].SetAutoText(readings[j].Text + " {1}");
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    // If we have an n-ary, remove any implicit boolean roles in it
                    for (int i = roleCollectionCount - 1; i >= 0; --i)
                    {
                        Role implicitBooleanRole = roleCollection[i].Role;
                        if (implicitBooleanRole != null && implicitBooleanRole.RolePlayer != null && implicitBooleanRole.RolePlayer.IsImplicitBooleanValue)
                        {
                            DebinarizeUnary(factType.RoleCollection, true, notifyAdded);
                            break;
                        }
                    }
                }
            }
示例#18
0
 private static IList FilterElementsFromCollectionSchemaForAutomation(LinkedElementCollection <AutomationSettingsSchema> result)
 {
     return(ShapeExtensions.FilterElementsFromCompartment <AutomationSettingsSchema, string>(result,
                                                                                             item => (item.Classification == Runtime.AutomationSettingsClassification.General),
                                                                                             item => string.Concat(item.AutomationType, item.Name)));
 }
示例#19
0
 private static IList FilterElementsFromCollectionSchemaForProperties(LinkedElementCollection <PropertySchema> result)
 {
     return(ShapeExtensions.FilterElementsFromCompartment <PropertySchema, string>(result,
                                                                                   (item => true), item => item.Name));
 }
示例#20
0
        /// <summary>
        /// Helper function to keep all relative shapes equidistant from
        /// a shape when the shape bounds change.
        /// </summary>
        /// <param name="e">ElementPropertyChangedEventArgs</param>
        protected static void MaintainRelativeShapeOffsetsForBoundsChange(ElementPropertyChangedEventArgs e)
        {
            Guid attributeId = e.DomainProperty.Id;

            if (attributeId == ORMBaseShape.AbsoluteBoundsDomainPropertyId)
            {
                ORMBaseShape parentShape = e.ModelElement as ORMBaseShape;
                RectangleD   oldBounds   = (RectangleD)e.OldValue;
                if (oldBounds.IsEmpty ||
                    oldBounds.Size == parentShape.DefaultSize ||
                    e.ModelElement.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.ContainsKey(ORMBaseShape.PlaceAllChildShapes))
                {
                    // Initializing, let normal placement win
                    return;
                }
                RectangleD newBounds = (RectangleD)e.NewValue;
                SizeD      oldSize   = oldBounds.Size;
                SizeD      newSize   = newBounds.Size;
                double     xChange   = newSize.Width - oldSize.Width;
                double     yChange   = newSize.Height - oldSize.Height;
                bool       checkX    = !VGConstants.FuzzZero(xChange, VGConstants.FuzzDistance);
                bool       checkY    = !VGConstants.FuzzZero(yChange, VGConstants.FuzzDistance);
                if (checkX || checkY)
                {
                    LinkedElementCollection <ShapeElement> childShapes = parentShape.RelativeChildShapes;
                    int childCount = childShapes.Count;
                    if (childCount != 0)
                    {
                        for (int i = 0; i < childCount; ++i)
                        {
                            bool      changeBounds = false;
                            PointD    change       = default(PointD);
                            NodeShape childShape   = childShapes[i] as NodeShape;
                            if (childShape != null)
                            {
                                RectangleD childBounds = childShape.AbsoluteBounds;
                                if (checkX)
                                {
                                    double newRight  = newBounds.Right - xChange;
                                    double childLeft = childBounds.Left;
                                    if (childLeft > newRight ||                                       // Completely to the right
                                        (childBounds.Right > newRight && childLeft > newBounds.Left)) // Straddles right edge
                                    {
                                        change.X     = xChange;
                                        changeBounds = true;
                                    }
                                }
                                if (checkY)
                                {
                                    double newBottom = newBounds.Bottom - yChange;
                                    double childTop  = childBounds.Top;
                                    if (childTop > newBottom ||                                       // Completely below
                                        (childBounds.Bottom > newBottom && childTop > newBounds.Top)) // Straddles bottom edge
                                    {
                                        change.Y     = yChange;
                                        changeBounds = true;
                                    }
                                }
                                if (changeBounds)
                                {
                                    childBounds.Offset(change);
                                    childShape.AbsoluteBounds = childBounds;
                                }
                            }
                        }
                    }
                }
            }
        }
示例#21
0
        private static void InvalidateIndirectErrorOwnerDisplay(ModelElement element, DomainDataDirectory domainDataDirectory, Predicate <ModelElement> filter)
        {
            IHasIndirectModelErrorOwner indirectOwner = element as IHasIndirectModelErrorOwner;

            if (indirectOwner != null)
            {
                Guid[] metaRoles = indirectOwner.GetIndirectModelErrorOwnerLinkRoles();
                int    roleCount;
                if (metaRoles != null &&
                    0 != (roleCount = metaRoles.Length))
                {
                    if (domainDataDirectory == null)
                    {
                        domainDataDirectory = element.Store.DomainDataDirectory;
                    }
                    for (int i = 0; i < roleCount; ++i)
                    {
                        Debug.Assert(metaRoles[i] != Guid.Empty);
                        DomainRoleInfo metaRole = domainDataDirectory.FindDomainRole(metaRoles[i]);
                        if (metaRole != null)
                        {
                            LinkedElementCollection <ModelElement> counterparts = metaRole.GetLinkedElements(element);
                            int counterpartCount = counterparts.Count;
                            for (int j = 0; j < counterpartCount; ++j)
                            {
                                ModelElement counterpart = counterparts[j];
                                if (filter != null && filter(counterpart))
                                {
                                    continue;
                                }
                                if (counterpart is IModelErrorOwner)
                                {
                                    InvalidateErrorOwnerDisplay(counterpart);
                                }
                                InvalidateIndirectErrorOwnerDisplay(
                                    counterpart,
                                    domainDataDirectory,
                                    delegate(ModelElement testElement)
                                {
                                    return(testElement == element ||
                                           (filter != null && filter(testElement)));
                                });
                            }
                        }
                    }
                }
            }
            ElementLink elementLink;
            IElementLinkRoleHasIndirectModelErrorOwner indirectLinkRoleOwner;

            if (null != (indirectLinkRoleOwner = element as IElementLinkRoleHasIndirectModelErrorOwner) &&
                null != (elementLink = element as ElementLink))
            {
                Guid[] metaRoles = indirectLinkRoleOwner.GetIndirectModelErrorOwnerElementLinkRoles();
                int    roleCount;
                if (metaRoles != null &&
                    0 != (roleCount = metaRoles.Length))
                {
                    if (domainDataDirectory == null)
                    {
                        domainDataDirectory = element.Store.DomainDataDirectory;
                    }
                    for (int i = 0; i < roleCount; ++i)
                    {
                        Debug.Assert(metaRoles[i] != Guid.Empty);
                        DomainRoleInfo metaRole = domainDataDirectory.FindDomainRole(metaRoles[i]);
                        if (metaRole != null)
                        {
                            ModelElement rolePlayer = metaRole.GetRolePlayer(elementLink);
                            if (filter != null && filter(rolePlayer))
                            {
                                continue;
                            }
                            if (rolePlayer is IModelErrorOwner)
                            {
                                InvalidateErrorOwnerDisplay(rolePlayer);
                            }
                            InvalidateIndirectErrorOwnerDisplay(
                                rolePlayer,
                                domainDataDirectory,
                                delegate(ModelElement testElement)
                            {
                                return(testElement == element ||
                                       (filter != null && filter(testElement)));
                            });
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Places each external constraint shape at the point corresponding to the average of all of its referenced shapes.
        /// Frequency constraints are handled differently, since they apply to only one fact type (but 1 or more roles in that
        /// fact type) at any time.
        /// </summary>
        /// <param name="minimumPoint">The minimum location for new element placement</param>
        public override void PostLayout(PointD minimumPoint)
        {
            ResolveReferences(myConstraintShapes);

            foreach (LayoutShape shape in myConstraintShapes)
            {
                if (!shape.Pinned)
                {
                    PointD    avg       = new PointD(0, 0);
                    NodeShape nodeShape = shape.Shape;
                    FrequencyConstraintShape           freqShape;
                    FrequencyConstraint                constraint;
                    LinkedElementCollection <FactType> relatedFactTypes;
                    int count;

                    if (null != (freqShape = nodeShape as FrequencyConstraintShape) &&
                        null != (constraint = freqShape.ModelElement as FrequencyConstraint) &&
                        1 == (relatedFactTypes = constraint.FactTypeCollection).Count)
                    {
                        Diagram       diagram             = myDiagram;
                        FactType      factType            = relatedFactTypes[0];
                        FactTypeShape factTypeShape       = null;
                        LayoutShape   factTypeLayoutShape = null;
                        foreach (PresentationElement pel in PresentationViewsSubject.GetPresentation(factType))
                        {
                            FactTypeShape testShape = pel as FactTypeShape;
                            if (testShape != null && testShape.Diagram == diagram)
                            {
                                if (factTypeShape == null)
                                {
                                    factTypeShape = testShape;
                                }
                                if (myLayoutShapes.TryGetValue(testShape, out factTypeLayoutShape))
                                {
                                    factTypeShape = testShape;
                                    break;
                                }
                            }
                        }

                        LinkedElementCollection <Role>     constraintRoles = constraint.RoleCollection;
                        LinkedElementCollection <RoleBase> displayOrder    = factTypeShape.DisplayedRoleOrder;
                        DisplayOrientation orientation = factTypeShape.DisplayOrientation;
                        RectangleD         shapeBounds = factTypeShape.AbsoluteBounds;
                        SizeD  shapeSize = factTypeShape.Size;
                        PointD location  = (factTypeLayoutShape != null) ? factTypeLayoutShape.TargetLocation : shapeBounds.Location;
                        count = constraintRoles.Count;
                        double width  = shapeSize.Width;
                        double height = shapeSize.Height;

                        for (int i = 0; i < count; i++)
                        {
                            int targetIndex = displayOrder.IndexOf(constraintRoles[i]);
                            switch (orientation)
                            {
                            case DisplayOrientation.Horizontal:
                                avg.Offset((width / (targetIndex + 1)) + location.X, location.Y - height);
                                break;

                            case DisplayOrientation.VerticalRotatedRight:
                                avg.Offset(location.X + width, (height / (targetIndex + 1)) + location.Y);
                                break;

                            case DisplayOrientation.VerticalRotatedLeft:
                                avg.Offset(location.X + width, height - (height / (targetIndex + 1)) + location.Y);
                                break;
                            }
                        }
                        avg.X /= count;
                        avg.Y /= count;
                    }
                    else if (0 != (count = shape.Count))
                    {
                        double          minX = double.MaxValue;
                        double          minY = double.MaxValue;
                        double          maxX = 0;
                        double          maxY = 0;
                        SizeD           size;
                        LayoutShapeList relatedShapes = shape.RelatedShapes;
                        // Take the center of farthest bounds as the location.
                        // This is the same as the average for two elements, but
                        // balances more than two elements much better.
                        for (int i = 0; i < count; ++i)
                        {
                            LayoutShape relatedShape = relatedShapes[i];
                            PointD      location     = relatedShape.TargetLocation;
                            size = relatedShape.Shape.Size;
                            double x = location.X + size.Width / 2;
                            double y = location.Y + size.Height / 2;
                            minX = Math.Min(minX, x);
                            minY = Math.Min(minY, y);
                            maxX = Math.Max(maxX, x);
                            maxY = Math.Max(maxY, y);
                        }
                        size  = nodeShape.Size;
                        avg.X = (maxX + minX) / 2 - size.Width / 2;
                        avg.Y = (maxY + minY) / 2 - size.Height / 2;
                        // Constraints are frequently ending up directly on top of
                        // an ObjectTypeShape, bump them up a bit
                        double bumpAdjust = size.Height * 2;
                        avg.Y -= bumpAdjust;
                        if (avg.Y < minimumPoint.Y)
                        {
                            avg.Y += bumpAdjust + bumpAdjust;
                        }
                    }

                    shape.TargetLocation = avg;
                }
                shape.Placed = true;
            }

            // Now add the shapes back into the main myLayoutShape list for reflow
            foreach (LayoutShape shape in myConstraintShapes)
            {
                myLayoutShapes.Add(shape);
            }
            myConstraintShapes.Clear();
        }
        /// <summary>
        /// Attempts to fix a PopulationMandatoryError
        /// </summary>
        /// <param name="error">Error to be corrected</param>
        /// <param name="autoCorrectRole">The <see cref="Role"/> to correct the error for.</param>
        /// <param name="autoCorrectFactType">If the <paramref name="autoCorrectRole"/> is not specified, select
        /// a unique constrained role from this <see cref="FactType"/></param>
        /// <returns><see langword="true"/> if the error was automatically corrected.</returns>
        public bool AutoCorrectMandatoryError(PopulationMandatoryError error, Role autoCorrectRole, FactType autoCorrectFactType)
        {
            bool retVal = false;
            ObjectTypeInstance             objectInstance  = error.ObjectTypeInstance;
            LinkedElementCollection <Role> constraintRoles = error.MandatoryConstraint.RoleCollection;

            // If the constraint has multiple roles, then we need to pick
            // a role to activate. This is trivial for a simple mandatory
            // constraint, or if a role in the constraint is selected. However,
            // if we have only a FactType selection, then there may be multiple
            // potential roles in the constraint for ring situations.
            if (constraintRoles.Count == 1)
            {
                autoCorrectRole     = constraintRoles[0];
                autoCorrectFactType = autoCorrectRole.FactType;
            }
            else
            {
                // We're only interested in one selected item, this code
                // path should not be running with multiple items selected.
                if (autoCorrectRole == null)
                {
                    if (autoCorrectFactType != null)
                    {
                        foreach (Role testRole in constraintRoles)
                        {
                            if (testRole.FactType == autoCorrectFactType)
                            {
                                if (autoCorrectRole == null)
                                {
                                    autoCorrectRole = testRole;
                                }
                                else
                                {
                                    // Ambiguous selection, there is nothing further we can do
                                    autoCorrectRole = null;
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (autoCorrectFactType == null)
                {
                    autoCorrectFactType = autoCorrectRole.FactType;
                }
            }
            if (autoCorrectFactType != null)
            {
                // Verify the selection, which needs to be set before this method is called
                SubtypeFact subtypeFact;
                bool        correctSelection;
                if (CurrentFrameVisibility != FrameVisibility.Visible)
                {
                    // If the window is not active then it does not have a selection
                    this.ShowNoActivate();
                }
                if (null != (subtypeFact = autoCorrectFactType as SubtypeFact) &&
                    subtypeFact.ProvidesPreferredIdentifier)
                {
                    ObjectType subtype = subtypeFact.Subtype;
                    ObjectType selectedEntityType;
                    FactType   objectifiedFactType;
                    correctSelection = (null != (selectedEntityType = SelectedEntityType) && selectedEntityType == subtype) ||
                                       (null != (objectifiedFactType = subtype.NestedFactType) && objectifiedFactType == SelectedFactType);
                }
                else if (!(correctSelection = SelectedFactType == autoCorrectFactType))
                {
                    FactTypeInstanceImplication implication = new FactTypeInstanceImplication(autoCorrectFactType);
                    correctSelection = implication.IsImplied && implication.ImpliedProxyRole == null && implication.IdentifyingSupertype != null && implication.ImpliedByEntityType == SelectedEntityType;
                }
                if (correctSelection)
                {
                    this.Show();
                    if (autoCorrectRole != null)
                    {
                        retVal = myEditor.AutoCorrectMandatoryError(error, autoCorrectRole);
                    }
                }
            }
            return(retVal);
        }
示例#24
0
        public static bool IsDataValid(this LinkedElementCollection <StaticData> dataList, Entity entity)
        {
            //Some of these are not fool-proof but they are close enough!!
            var retval = true;

            foreach (var data in dataList)
            {
                //var column = entity.Store.ElementDirectory.AllElements.FirstOrDefault(x => x.Id == data.Id) as Field;
                var column = entity.Fields.FirstOrDefault(x => x.Id == data.ColumnKey);
                if (column == null)
                {
                    return(true);                                //No Verification
                }
                long     vlong;
                int      vint;
                bool     vbool;
                decimal  vdecimal;
                DateTime vdate;
                short    vshort;
                byte     vbyte;

                if (column.Nullable && data.Value.ToLower() == "(null)")
                {
                    //Do nothing. This is a nullable field so set to NULL
                }
                else
                {
                    switch (column.DataType)
                    {
                    case DataTypeConstants.BigInt:
                        retval &= long.TryParse(data.Value, out vlong);
                        break;

                    case DataTypeConstants.Binary:
                        retval &= true;                                 //no validation
                        break;

                    case DataTypeConstants.Bit:
                        var v2 = data.Value + string.Empty;
                        if (v2 == "0")
                        {
                            v2 = "false";
                        }
                        if (v2 == "1")
                        {
                            v2 = "true";
                        }
                        retval &= bool.TryParse(v2.ToLower(), out vbool);
                        break;

                    case DataTypeConstants.Char:
                        retval &= true;
                        break;

                    case DataTypeConstants.Date:
                        retval &= DateTime.TryParse(data.Value, out vdate);
                        break;

                    case DataTypeConstants.DateTime:
                        retval &= DateTime.TryParse(data.Value, out vdate);
                        break;

                    case DataTypeConstants.DateTime2:
                        retval &= DateTime.TryParse(data.Value, out vdate);
                        break;

                    case DataTypeConstants.DateTimeOffset:
                        retval &= true;                                 //no validation
                        break;

                    case DataTypeConstants.Decimal:
                        retval &= decimal.TryParse(data.Value, out vdecimal);
                        break;

                    case DataTypeConstants.Float:
                        retval &= decimal.TryParse(data.Value, out vdecimal);
                        break;

                    case DataTypeConstants.Image:
                        retval &= true;
                        break;

                    case DataTypeConstants.Int:
                        retval &= int.TryParse(data.Value, out vint);
                        break;

                    case DataTypeConstants.Money:
                        retval &= decimal.TryParse(data.Value, out vdecimal);
                        break;

                    case DataTypeConstants.NChar:
                        retval &= true;
                        break;

                    case DataTypeConstants.NText:
                        retval &= true;
                        break;

                    case DataTypeConstants.NVarChar:
                        retval &= true;
                        break;

                    case DataTypeConstants.Real:
                        retval &= decimal.TryParse(data.Value, out vdecimal);
                        break;

                    case DataTypeConstants.SmallDateTime:
                        retval &= DateTime.TryParse(data.Value, out vdate);
                        break;

                    case DataTypeConstants.SmallInt:
                        retval &= short.TryParse(data.Value, out vshort);
                        break;

                    case DataTypeConstants.SmallMoney:
                        retval &= decimal.TryParse(data.Value, out vdecimal);
                        break;

                    case DataTypeConstants.Structured:
                        retval &= true;
                        break;

                    case DataTypeConstants.Text:
                        retval &= true;
                        break;

                    case DataTypeConstants.Time:
                        retval &= DateTime.TryParse(data.Value, out vdate);
                        break;

                    case DataTypeConstants.Timestamp:
                        retval &= true;                                 //no validation
                        break;

                    case DataTypeConstants.TinyInt:
                        retval &= byte.TryParse(data.Value, out vbyte);
                        break;

                    case DataTypeConstants.Udt:
                        retval &= true;                                 //no validation
                        break;

                    case DataTypeConstants.UniqueIdentifier:
                        try { var g = new Guid(data.Value); retval &= true; }
                        catch { retval &= false; }
                        break;

                    case DataTypeConstants.VarBinary:
                        retval &= true;                                 //no validation
                        break;

                    case DataTypeConstants.VarChar:
                        retval &= true;
                        break;

                    case DataTypeConstants.Variant:
                        retval &= true;                                 //no validation
                        break;

                    case DataTypeConstants.Xml:
                        retval &= true;
                        break;

                    default:
                        retval &= true;
                        break;
                    }
                }
            }
            return(retval);
        }
            /// <summary>
            /// Reverses the binarization process performed by <see cref="BinarizeUnary"/>. Typically used when
            /// <paramref name="binarizedUnaryFactRoleCollection"/> no longer qualifies as the roles for a
            /// binarized unary <see cref="FactType"/>.
            /// </summary>
            private static void DebinarizeUnary(LinkedElementCollection <RoleBase> binarizedUnaryFactRoleCollection, bool deleteImplicitBooleanRole, INotifyElementAdded notifyAdded)
            {
                // UNDONE: We need to make sure the debinarization happens BEFORE the implied Objectification rules run on the binarized unary FactType.

                // The default implied role is the second one, walk the collection backwards
                int roleCount = binarizedUnaryFactRoleCollection.Count;

                for (int i = roleCount - 1; i >= 0; --i)
                {
                    Role       implicitBooleanRole;
                    ObjectType implicitBooleanValueType;
                    if (null != (implicitBooleanRole = binarizedUnaryFactRoleCollection[i].Role) &&
                        null != (implicitBooleanValueType = implicitBooleanRole.RolePlayer) &&
                        implicitBooleanValueType.IsImplicitBooleanValue)
                    {
                        // Delete the implicit boolean value type (which will also remove any value constraints on it)
                        // Note that changes to IsImplicitBooleanValue are intentionally blocked so that the
                        // deleted implied ValueType can be identified as such by events as well as rules.
                        // implicitBooleanValueType.IsImplicitBooleanValue = false;
                        bool        ruleDisabled = false;
                        RuleManager ruleManager  = null;
                        try
                        {
                            if (notifyAdded == null)
                            {
                                ruleManager = implicitBooleanRole.Store.RuleManager;
                                ruleManager.DisableRule(typeof(ObjectTypePlaysRoleDeletedRuleClass));
                                ruleDisabled = true;
                            }
                            if (deleteImplicitBooleanRole)
                            {
                                // We delete the role first so that rules do not
                                // try to recreate and implied fact type for this rule
                                // if it is part of an objectified FactType.
                                implicitBooleanRole.Delete();
                                --roleCount;
                                if (!implicitBooleanValueType.IsDeleted)
                                {
                                    // The Objectification.RolePlayerDeletingRule rule will delet this automatically
                                    implicitBooleanValueType.Delete();
                                }
                            }
                            else
                            {
                                implicitBooleanValueType.Delete();
                            }
                        }
                        finally
                        {
                            if (ruleDisabled)
                            {
                                ruleManager.EnableRule(typeof(ObjectTypePlaysRoleDeletedRuleClass));
                            }
                        }

                        // Clear implied constraints
                        for (int j = 0; j < roleCount; ++j)
                        {
                            Role role = binarizedUnaryFactRoleCollection[j] as Role;
                            if (role != null)
                            {
                                if (role != implicitBooleanRole)
                                {
                                    role.Name = "";
                                    // Role cardinality is for unary fact types only, eliminate
                                    // it if we switch away.
                                    role.Cardinality = null;
                                }

                                UniquenessConstraint singleRoleAlethicUniquenessConstraint = role.SingleRoleAlethicUniquenessConstraint;
                                if (singleRoleAlethicUniquenessConstraint != null)
                                {
                                    // Delete the uniqueness constraint
                                    singleRoleAlethicUniquenessConstraint.Delete();
                                }

                                // UNDONE: We are using open-world assumption now
                                //MandatoryConstraint simpleMandatoryConstraint = role.SimpleMandatoryConstraint;
                                //if (simpleMandatoryConstraint != null && simpleMandatoryConstraint.Modality == ConstraintModality.Alethic)
                                //{
                                //    // Delete the simple mandatory constraint (for closed-world assumption), if present
                                //    simpleMandatoryConstraint.Delete();
                                //}
                            }
                        }
                        break;
                    }
                }
            }
 public string BuildPropertyEqualitiesToString(LinkedElementCollection<Property> properties,List<string> ignorePropertyNames)
 {
     //(AccountNumber == p.AccountNumber) && (AccountName == p.AccountName)
     StringBuilder sb = new StringBuilder();
     int count = 0;
     foreach (Property prop in properties)
     {
         if (!ignorePropertyNames.Contains(prop.Name))
         {
             if (count == 0)
             {
                 sb.Append("(" + prop.Name + " == p." + prop.Name + ")");
             }
             else
             {
                 sb.Append(" && (" + prop.Name + " == p." + prop.Name + ")");
             }
             count++;
         }
     }
     return sb.ToString();
 }
        private static string GetDataElementName(
            string sourceName, 
            string targetName, 
            LinkedElementCollection<DataMember> dataElements)
        {
            // First check if we have duplicates in target DataElements
            string name = sourceName;
 
            for (int suffix = 1; dataElements.Find(m => { return m.Name.Equals(name, StringComparison.OrdinalIgnoreCase); }) != null; suffix++)
            {
                name = string.Concat(sourceName, suffix);
            } 

            // Second check if this is a self reference and therefore we need to get a new name (!= element name)
            for(int sfx = 1; name == targetName; sfx++)
            {
                name = string.Concat(sourceName, sfx);
            }

            return name; 
        }
        private static void ProcessNodeShape(NodeShape shapeElement, LinkedElementCollection<NodeShapeInfo> infos)
        {
            // try to find NodeShapeInfo for shape element
            NodeShapeInfo info = null;
            foreach (NodeShapeInfo i in infos)
            {
                if (i.ElementId == shapeElement.Element.Id)
                {
                    info = i;
                    break;
                }
            }

            if (info == null)
            {
                shapeElement.UpdateAbsoluteLocation();
                return;
            }

            shapeElement.Size = info.Size;
            shapeElement.SetLocation(info.RelativeLocation);

            // children
            foreach (NodeShape shape in shapeElement.Children)
            {
                ProcessNodeShape(shape, info.ChildrenInfos);
            }
        }
示例#29
0
        /// <summary>
        /// Update the diagram display order
        /// </summary>
        /// <param name="store">The current <see cref="Store"/></param>
        /// <param name="orderedDiagrams">An ordered list of diagrams</param>
        public static void UpdateDiagramDisplayOrder(Store store, IList <Diagram> orderedDiagrams)
        {
            DiagramDisplay         container  = null;
            IList <DiagramDisplay> containers = store.ElementDirectory.FindElements <DiagramDisplay>(false);

            if (containers.Count != 0)
            {
                container = containers[0];
            }
            using (Transaction t = store.TransactionManager.BeginTransaction(FrameworkResourceStrings.DiagramDisplayReorderDiagramsTransactionName))
            {
                int orderCount = orderedDiagrams.Count;
                if (orderCount == 0)
                {
                    if (container != null)
                    {
                        container.OrderedDiagramCollection.Clear();
                    }
                    return;
                }
                else if (container == null)
                {
                    container = new DiagramDisplay(store);
                }
                LinkedElementCollection <Diagram> existingDiagrams = container.OrderedDiagramCollection;
                int existingDiagramCount = existingDiagrams.Count;
                for (int i = existingDiagramCount - 1; i >= 0; --i)
                {
                    Diagram testDiagram = existingDiagrams[i];
                    if (!orderedDiagrams.Contains(testDiagram))
                    {
                        existingDiagrams.RemoveAt(i);
                        --existingDiagramCount;
                    }
                }
                for (int i = 0; i < orderCount; ++i)
                {
                    Diagram orderedDiagram = orderedDiagrams[i];
                    int     existingIndex  = existingDiagrams.IndexOf(orderedDiagram);
                    if (existingIndex == -1)
                    {
                        if (i < existingDiagramCount)
                        {
                            existingDiagrams.Insert(i, orderedDiagram);
                        }
                        else if (!existingDiagrams.Contains(orderedDiagram))
                        {
                            existingDiagrams.Add(orderedDiagram);
                        }
                        ++existingDiagramCount;
                    }
                    else if (existingIndex != i)
                    {
                        existingDiagrams.Move(existingIndex, i);
                    }
                }
                if (t.HasPendingChanges)
                {
                    t.Commit();
                }
            }
        }
示例#30
0
            private static void EnsureSingleColumnUniqueAndMandatory(SubtypeFact subtypeFact, Role role, bool requireMandatory, INotifyElementAdded notifyAdded)
            {
                LinkedElementCollection <ConstraintRoleSequence> sequences = role.ConstraintRoleSequenceCollection;
                int           sequenceCount  = sequences.Count;
                bool          haveUniqueness = false;
                bool          haveMandatory  = !requireMandatory;
                SetConstraint ic;

                for (int i = sequenceCount - 1; i >= 0; --i)
                {
                    ic = sequences[i] as SetConstraint;
                    if (ic != null && ic.Constraint.ConstraintIsInternal)
                    {
                        if (ic.RoleCollection.Count == 1 && ic.Modality == ConstraintModality.Alethic)
                        {
                            switch (ic.Constraint.ConstraintType)
                            {
                            case ConstraintType.InternalUniqueness:
                                if (haveUniqueness)
                                {
                                    ic.Delete();
                                }
                                else
                                {
                                    haveUniqueness = true;
                                }
                                break;

                            case ConstraintType.SimpleMandatory:
                                if (haveMandatory)
                                {
                                    ic.Delete();
                                }
                                else
                                {
                                    haveMandatory = true;
                                }
                                break;
                            }
                        }
                        else
                        {
                            ic.Delete();
                        }
                    }
                }
                if (!haveUniqueness || !haveMandatory)
                {
                    IHasAlternateOwner <FactType>          toAlternateOwner;
                    IAlternateElementOwner <SetConstraint> alternateConstraintOwner;
                    if (null != (toAlternateOwner = subtypeFact as IHasAlternateOwner <FactType>) &&
                        null != (alternateConstraintOwner = toAlternateOwner.AlternateOwner as IAlternateElementOwner <SetConstraint>))
                    {
                        if (!haveUniqueness)
                        {
                            ic = UniquenessConstraint.CreateInternalUniquenessConstraint(subtypeFact);
                            ic.RoleCollection.Add(role);
                            notifyAdded.ElementAdded(ic, true);
                        }
                    }
                    if (!haveMandatory)
                    {
                        ic = MandatoryConstraint.CreateSimpleMandatoryConstraint(role);
                        notifyAdded.ElementAdded(ic, true);
                    }
                }
            }
示例#31
0
		/// <summary>
		/// Determines the obvious fact type mappings, and all other potential mappings.
		/// </summary>
		/// <param name="modelFactTypes">The <see cref="FactType"/> objects of the model</param>
		/// <param name="decidedManyToOneFactTypeMappings">The decided many-to-one <see cref="FactTypeMapping"/> objects.</param>
		/// <param name="decidedOneToOneFactTypeMappings">The decided one-to-one <see cref="FactTypeMapping"/> objects.</param>
		/// <param name="undecidedOneToOneFactTypeMappings">The undecided <see cref="FactTypeMapping"/> possibilities.</param>
		private void PerformInitialFactTypeMappings(LinkedElementCollection<FactType> modelFactTypes, FactTypeMappingDictionary decidedManyToOneFactTypeMappings, FactTypeMappingDictionary decidedOneToOneFactTypeMappings, FactTypeMappingListDictionary undecidedOneToOneFactTypeMappings)
		{
			// For each fact type in the model...
			foreach (FactType factType in modelFactTypes)
			{
				if (ShouldIgnoreFactType(factType))
				{
					continue;
				}
				SubtypeFact subtypeFact = factType as SubtypeFact;

				// If it's a subtype relation...
				MandatoryConstraint mandatory;
				if (subtypeFact != null)
				{
					Role subtypeRole = subtypeFact.SubtypeRole;
					Role supertypeRole = subtypeFact.SupertypeRole;
					mandatory = supertypeRole.SingleRoleAlethicMandatoryConstraint; // Note that the only way to get a mandatory on the supertype role is with an implied mandatory, verified explicitly below

					// Map deeply toward the supertype.
					FactTypeMapping factTypeMapping = new FactTypeMapping(
						subtypeFact,
						subtypeRole,
						supertypeRole,
						FactTypeMappingFlags.Subtype | FactTypeMappingFlags.DeepMapping | FactTypeMappingFlags.FromRoleMandatory | ((mandatory != null && mandatory.IsImplied) ? FactTypeMappingFlags.TowardsRoleMandatory | FactTypeMappingFlags.TowardsRoleImpliedMandatory : FactTypeMappingFlags.None) | (subtypeRole.RolePlayer.IsValueType ? FactTypeMappingFlags.FromValueType | FactTypeMappingFlags.TowardsValueType : FactTypeMappingFlags.None));
					decidedOneToOneFactTypeMappings.Add(subtypeFact, factTypeMapping);
				}
				else
				{
					LinkedElementCollection<RoleBase> roles = factType.RoleCollection;

					Debug.Assert(roles.Count == 2 && (factType.Objectification == null || factType.UnaryRole != null), "Non-binarized fact types should have been filtered out already.");

					Role firstRole = roles[0].Role;
					Role secondRole = roles[1].Role;
					ObjectType firstRolePlayer = firstRole.RolePlayer;
					ObjectType secondRolePlayer = secondRole.RolePlayer;

					UniquenessConstraint firstRoleUniquenessConstraint = (UniquenessConstraint)firstRole.SingleRoleAlethicUniquenessConstraint;
					UniquenessConstraint secondRoleUniquenessConstraint = (UniquenessConstraint)secondRole.SingleRoleAlethicUniquenessConstraint;
					
					bool firstRolePlayerIsValueType = firstRolePlayer.IsValueType;
					bool secondRolePlayerIsValueType = secondRolePlayer.IsValueType;
					
					bool firstRoleIsUnique = (firstRoleUniquenessConstraint != null);
					bool secondRoleIsUnique = (secondRoleUniquenessConstraint != null);
					
					bool firstRoleIsMandatory = null != (mandatory = firstRole.SingleRoleAlethicMandatoryConstraint);
					bool firstRoleIsImplicitlyMandatory = firstRoleIsMandatory && mandatory.IsImplied;
					bool firstRoleIsExplicitlyMandatory = firstRoleIsMandatory && !firstRoleIsImplicitlyMandatory;
					bool secondRoleIsMandatory = null != (mandatory = secondRole.SingleRoleAlethicMandatoryConstraint);
					bool secondRoleIsImplicitlyMandatory = secondRoleIsMandatory && mandatory.IsImplied;
					bool secondRoleIsExplicitlyMandatory = secondRoleIsMandatory && !secondRoleIsImplicitlyMandatory;

					// We don't need to worry about shallow mappings towards preferred identifiers on many-to-ones, since the preferred
					// identifier pattern ensures that these cases will always map towards the object type being identified anyway.

					const int FIRST_SECOND_SHALLOW = 1;
					const int FIRST_SECOND_DEEP = 2;
					const int SECOND_FIRST_SHALLOW = 4;
					const int SECOND_FIRST_DEEP = 8;
					int possibilityBits = 0;
					bool manyToOne = false;

					// If only firstRole is unique...
					if (firstRoleIsUnique && !secondRoleIsUnique)
					{
						// Shallow map toward firstRolePlayer.
						possibilityBits |= SECOND_FIRST_SHALLOW;
						manyToOne = true;
					}
					else if (!firstRoleIsUnique && secondRoleIsUnique) // ...only secondRole is unique...
					{
						// Shallow map toward secondRolePlayer.
						possibilityBits |= FIRST_SECOND_SHALLOW;
						manyToOne = true;
					}
					else if (firstRoleIsUnique && secondRoleIsUnique) // ...both roles are unique...
					{
						// If this is a ring fact type...
						if (firstRolePlayer == secondRolePlayer)
						{
							// If only firstRole is mandatory...
							if (firstRoleIsExplicitlyMandatory && !secondRoleIsExplicitlyMandatory)
							{
								// Shallow map toward firstRolePlayer (mandatory role player).
								possibilityBits |= FIRST_SECOND_SHALLOW;
							}
							else if (!firstRoleIsExplicitlyMandatory && secondRoleIsExplicitlyMandatory) // ...only secondRole is mandatory...
							{
								// Shallow map toward secondRolePlayer (mandatory role player).
								possibilityBits |= SECOND_FIRST_SHALLOW;
							}
							else // ...otherwise...
							{
								// Shallow map toward firstRolePlayer.
								possibilityBits |= FIRST_SECOND_SHALLOW;
							}
						}
						else // ...not a ring fact type...
						{
							// These are used to make sure that we never shallowly map towards a preferred identifier.
							bool firstRoleIsUniqueAndPreferred = firstRoleIsUnique && firstRoleUniquenessConstraint.IsPreferred;
							bool secondRoleIsUniqueAndPreferred = secondRoleIsUnique && secondRoleUniquenessConstraint.IsPreferred;

							// If neither role is mandatory...
							if (!firstRoleIsExplicitlyMandatory && !secondRoleIsExplicitlyMandatory)
							{
								// If firstRole is not preferred...
								if (!firstRoleIsUniqueAndPreferred)
								{
									// Shallow map toward firstRolePlayer.
									possibilityBits |= SECOND_FIRST_SHALLOW;
								}

								// If secondRole is not preferred...
								if (!secondRoleIsUniqueAndPreferred)
								{
									// Shallow map toward secondRolePlayer.
									possibilityBits |= FIRST_SECOND_SHALLOW;
								}
							}
							else if (firstRoleIsExplicitlyMandatory && !secondRoleIsExplicitlyMandatory) // ...only firstRole is mandatory...
							{
								// Note that the first role cannot be be preferred if the second role is not mandatory
								// Shallow map toward firstRolePlayer.
								possibilityBits |= SECOND_FIRST_SHALLOW;
#if FALSE
								// UNDONE: This is a much deeper check for 1-1 patterns off of mandatory constraints. Both this and
								// the current much quicker check are meant to limit permutation checks on patterns where numerous
								// 1-1 fact types reference the same optional role player. Both of these systems are extremely fragile
								// to one of the uses of the value being made mandatory, in which case this loop does not apply.
								// We need to find a quicker mechanism for determining when we should allow an absorption towards
								// a fully optional object type, or some other check to eliminate extremely long chains (these can
								// easily consume all memory on a machine).
								bool allowMappingTowardsOptionalRole = true;
								if (null != (mandatory = secondRolePlayer.ImpliedMandatoryConstraint))
								{
									if (!(secondRoleIsUniqueAndPreferred && factType.ImpliedByObjectification != null))
									{
										foreach (Role testRole in mandatory.RoleCollection)
										{
											if (testRole != secondRole && !ShouldIgnoreFactType((testRole.Proxy ?? (RoleBase)testRole).FactType))
											{
												Role oppositeRole;
												if (testRole.SingleRoleAlethicUniquenessConstraint != null &&
													null != (oppositeRole = testRole.OppositeRoleAlwaysResolveProxy as Role) &&
													null != oppositeRole.SingleRoleAlethicUniquenessConstraint &&
													null != (mandatory = oppositeRole.SingleRoleAlethicMandatoryConstraint) &&
													!mandatory.IsImplied)
												{
													// If there are multiple 1-1 mappings towards an object type with
													// an implied mandatory, then don't consider any mappings towards
													// this entity.
													allowMappingTowardsOptionalRole = false;
													break;
												}
											}
										}
									}
								}

								if (allowMappingTowardsOptionalRole)
#endif // FALSE
								if (null == secondRolePlayer.ImpliedMandatoryConstraint ||
									((secondRoleIsUniqueAndPreferred && !secondRolePlayerIsValueType) || factType.ImpliedByObjectification != null))
								{
									// If secondRole is not preferred...
									if (!secondRoleIsUniqueAndPreferred)
									{
										// Shallow map toward secondRolePlayer.
										possibilityBits |= FIRST_SECOND_SHALLOW;
									}

									// Deep map toward secondRolePlayer.
									possibilityBits |= FIRST_SECOND_DEEP;
								}
							}
							else if (!firstRoleIsExplicitlyMandatory && secondRoleIsExplicitlyMandatory) // ...only secondRole is mandatory...
							{
								// Note that the second role cannot be preferred if the first role is not mandatory
								// Shallow map toward secondRolePlayer.
								possibilityBits |= FIRST_SECOND_SHALLOW;

#if FALSE
								// UNDONE: See comments above, duplicate code switching first and second
								bool allowMappingTowardsOptionalRole = true;
								if (null != (mandatory = firstRolePlayer.ImpliedMandatoryConstraint))
								{
									if (!(firstRoleIsUniqueAndPreferred && factType.ImpliedByObjectification != null))
									{
										foreach (Role testRole in mandatory.RoleCollection)
										{
											if (testRole != firstRole && !ShouldIgnoreFactType((testRole.Proxy ?? (RoleBase)testRole).FactType))
											{
												Role oppositeRole;
												if (testRole.SingleRoleAlethicUniquenessConstraint != null &&
													null != (oppositeRole = testRole.OppositeRoleAlwaysResolveProxy as Role) &&
													null != oppositeRole.SingleRoleAlethicUniquenessConstraint &&
													null != (mandatory = oppositeRole.SingleRoleAlethicMandatoryConstraint) &&
													!mandatory.IsImplied)
												{
													// If there are multiple 1-1 mappings towards an object type with
													// an implied mandatory, then don't consider any mappings towards
													// this entity.
													allowMappingTowardsOptionalRole = false;
													break;
												}
											}
										}
									}
								}

								if (allowMappingTowardsOptionalRole)
#endif // FALSE
								if (null == firstRolePlayer.ImpliedMandatoryConstraint ||
									((firstRoleIsUniqueAndPreferred && !firstRolePlayerIsValueType) || factType.ImpliedByObjectification != null))
								{
									// If firstRole is not preferred...
									if (!firstRoleIsUniqueAndPreferred)
									{
										// Shallow map toward firstRolePlayer.
										possibilityBits |= SECOND_FIRST_SHALLOW;
									}

									// Deep map toward firstRolePlayer.
									possibilityBits |= SECOND_FIRST_DEEP;
								}
							}
							else // ...both roles are mandatory...
							{
								// If firstRole is not preferred...
								if (!firstRoleIsUniqueAndPreferred)
								{
									// Shallow map toward firstRolePlayer.
									possibilityBits |= SECOND_FIRST_SHALLOW;
								}

								// If secondRole is not preferred...
								if (!secondRoleIsUniqueAndPreferred)
								{
									// Shallow map toward secondRolePlayer.
									possibilityBits |= FIRST_SECOND_SHALLOW;
								}

								// Possible deep map toward firstRolePlayer and toward secondRolePlayer
								possibilityBits |= FIRST_SECOND_DEEP | SECOND_FIRST_DEEP;
							}
						}
					}
					Debug.Assert(possibilityBits != 0);
					switch (possibilityBits)
					{
						case FIRST_SECOND_SHALLOW:
							(manyToOne ? decidedManyToOneFactTypeMappings : decidedOneToOneFactTypeMappings).Add(factType, new FactTypeMapping(factType, firstRole, secondRole, GetFlags(false, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory)));
							break;
						case SECOND_FIRST_SHALLOW:
							(manyToOne ? decidedManyToOneFactTypeMappings : decidedOneToOneFactTypeMappings).Add(factType, new FactTypeMapping(factType, secondRole, firstRole, GetFlags(false, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory)));
							break;
						case FIRST_SECOND_DEEP:
							(manyToOne ? decidedManyToOneFactTypeMappings : decidedOneToOneFactTypeMappings).Add(factType, new FactTypeMapping(factType, firstRole, secondRole, GetFlags(true, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory)));
							break;
						case SECOND_FIRST_DEEP:
							(manyToOne ? decidedManyToOneFactTypeMappings : decidedOneToOneFactTypeMappings).Add(factType, new FactTypeMapping(factType, secondRole, firstRole, GetFlags(true, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory)));
							break;
						default:
							{
								// UNDONE: I don't see any reason to use a heavy-weight list structure here. The
								// same information could be stored in an UndecidedFactTypeMapping structure that
								// uses a bit field mechanism similar to this block of code. This would allow us
								// to store the factType/firstRole/secondRole once and interpret the contents based
								// on a single bitfield. In the meantime, keep the list as small as possible.
								int countBits = possibilityBits;
								int count = 0;
								while (countBits != 0)
								{
									if (0 != (countBits & 1))
									{
										++count;
									}
									countBits >>= 1;
								}
								FactTypeMappingList potentialMappingList = new FactTypeMappingList(count);
								count = -1;
								if (0 != (possibilityBits & FIRST_SECOND_SHALLOW))
								{
									potentialMappingList.Add(new FactTypeMapping(factType, firstRole, secondRole, GetFlags(false, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory)));
								}
								if (0 != (possibilityBits & SECOND_FIRST_SHALLOW))
								{
									potentialMappingList.Add(new FactTypeMapping(factType, secondRole, firstRole, GetFlags(false, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory)));
								}
								if (0 != (possibilityBits & FIRST_SECOND_DEEP))
								{
									potentialMappingList.Add(new FactTypeMapping(factType, firstRole, secondRole, GetFlags(true, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory)));
								}
								if (0 != (possibilityBits & SECOND_FIRST_DEEP))
								{
									potentialMappingList.Add(new FactTypeMapping(factType, secondRole, firstRole, GetFlags(true, secondRolePlayerIsValueType, secondRoleIsMandatory, secondRoleIsImplicitlyMandatory, firstRolePlayerIsValueType, firstRoleIsMandatory, firstRoleIsImplicitlyMandatory)));
								}
								undecidedOneToOneFactTypeMappings.Add(factType, potentialMappingList);
								break;
							}
					}
				}
			}
		}
示例#32
0
文件: Role.cs 项目: cjheath/NORMA
		/// <summary>
		/// Determines the index of a specific Role in the list, resolving
		/// RoleProxy elements as needed
		/// </summary>
		/// <param name="roleBaseCollection">The list in which to locate the role</param>
		/// <param name="value">The Role to locate in the list</param>
		/// <returns>index of object</returns>
		public static int IndexOf(LinkedElementCollection<RoleBase> roleBaseCollection, Role value)
		{
			int count = roleBaseCollection.Count;
			for (int i = 0; i < count; ++i)
			{
				if (roleBaseCollection[i].Role == value)
				{
					return i;
				}
			}
			return -1;
		}
示例#33
0
			/// <summary>
			/// Reverses the binarization process performed by <see cref="BinarizeUnary"/>. Typically used when
			/// <paramref name="binarizedUnaryFactRoleCollection"/> no longer qualifies as the roles for a
			/// binarized unary <see cref="FactType"/>.
			/// </summary>
			private static void DebinarizeUnary(LinkedElementCollection<RoleBase> binarizedUnaryFactRoleCollection, bool deleteImplicitBooleanRole, INotifyElementAdded notifyAdded)
			{
				// UNDONE: We need to make sure the debinarization happens BEFORE the implied Objectification rules run on the binarized unary FactType.

				// The default implied role is the second one, walk the collection backwards
				int roleCount = binarizedUnaryFactRoleCollection.Count;
				for (int i = roleCount - 1; i >= 0; --i)
				{
					Role implicitBooleanRole;
					ObjectType implicitBooleanValueType;
					if (null != (implicitBooleanRole = binarizedUnaryFactRoleCollection[i].Role) &&
						null != (implicitBooleanValueType = implicitBooleanRole.RolePlayer) &&
						implicitBooleanValueType.IsImplicitBooleanValue)
					{
						// Delete the implicit boolean value type (which will also remove any value constraints on it)
						// Note that changes to IsImplicitBooleanValue are intentionally blocked so that the
						// deleted implied ValueType can be identified as such by events as well as rules.
						// implicitBooleanValueType.IsImplicitBooleanValue = false;
						bool ruleDisabled = false;
						RuleManager ruleManager = null;
						try
						{
							if (notifyAdded == null)
							{
								ruleManager = implicitBooleanRole.Store.RuleManager;
								ruleManager.DisableRule(typeof(ObjectTypePlaysRoleDeletedRuleClass));
								ruleDisabled = true;
							}
							if (deleteImplicitBooleanRole)
							{
								// We delete the role first so that rules do not
								// try to recreate and implied fact type for this rule
								// if it is part of an objectified FactType.
								implicitBooleanRole.Delete();
								--roleCount;
								if (!implicitBooleanValueType.IsDeleted)
								{
									// The Objectification.RolePlayerDeletingRule rule will delet this automatically
									implicitBooleanValueType.Delete();
								}
							}
							else
							{
								implicitBooleanValueType.Delete();
							}
						}
						finally
						{
							if (ruleDisabled)
							{
								ruleManager.EnableRule(typeof(ObjectTypePlaysRoleDeletedRuleClass));
							}
						}

						// Clear implied constraints
						for (int j = 0; j < roleCount; ++j)
						{
							Role role = binarizedUnaryFactRoleCollection[j] as Role;
							if (role != null)
							{
								if (role != implicitBooleanRole)
								{
									role.Name = "";
								}

								UniquenessConstraint singleRoleAlethicUniquenessConstraint = role.SingleRoleAlethicUniquenessConstraint;
								if (singleRoleAlethicUniquenessConstraint != null)
								{
									// Delete the uniqueness constraint
									singleRoleAlethicUniquenessConstraint.Delete();
								}

								// UNDONE: We are using open-world assumption now
								//MandatoryConstraint simpleMandatoryConstraint = role.SimpleMandatoryConstraint;
								//if (simpleMandatoryConstraint != null && simpleMandatoryConstraint.Modality == ConstraintModality.Alethic)
								//{
								//    // Delete the simple mandatory constraint (for closed-world assumption), if present
								//    simpleMandatoryConstraint.Delete();
								//}
							}
						}
						break;
					}
				}
			}
示例#34
0
        /// <summary>
        /// Ensure that the <see cref="UniquenessConstraint.IsPreferred"/> property is read-only
        /// when the <see cref="FactType.InternalUniquenessConstraintChangeRule"/> is
        /// unable to make it <see langword="true"/>.
        /// Make sure the <see cref="SetConstraint.Modality">Modality</see> property
        /// is read only for single-role uniqueness constraints on the Objectification end of an implied fact type.
        /// </summary>
        protected override bool IsPropertyDescriptorReadOnly(ElementPropertyDescriptor propertyDescriptor)
        {
            UniquenessConstraint uniquenessConstraint;
            Guid propertyId = propertyDescriptor.DomainPropertyInfo.Id;
            LinkedElementCollection <Role> roles;
            FactType factType;

            if (propertyId == UniquenessConstraint.IsPreferredDomainPropertyId)
            {
                uniquenessConstraint = ModelElement;
                ObjectType identifierFor = uniquenessConstraint.PreferredIdentifierFor;
                if (identifierFor != null)
                {
                    // If this is the preferred identifier for an objectifying type and
                    // is the only alethic internal uniqueness constraint for the nested FactType,
                    // then it will automatically be readded as the preferred identifier if it is
                    // changed to false. Don't allow it to change.
                    if (uniquenessConstraint.IsInternal &&
                        null != (factType = identifierFor.NestedFactType))
                    {
                        UniquenessConstraint           candidate       = null;
                        LinkedElementCollection <Role> constraintRoles = uniquenessConstraint.RoleCollection;
                        if (constraintRoles.Count == 1 && constraintRoles[0] is ObjectifiedUnaryRole)                         // Note there is only one FactType for an internal constraint
                        {
                            candidate = uniquenessConstraint;
                        }
                        else if (factType == uniquenessConstraint.FactTypeCollection[0] && null == factType.UnaryRole)
                        {
                            foreach (UniquenessConstraint constraint in factType.GetInternalConstraints <UniquenessConstraint>())
                            {
                                if (constraint.Modality == ConstraintModality.Alethic)
                                {
                                    if (candidate != null || constraint != uniquenessConstraint)
                                    {
                                        candidate = null;
                                        break;
                                    }
                                    else
                                    {
                                        candidate = constraint;
                                    }
                                }
                            }
                        }
                        if (candidate != null)
                        {
                            bool haveSupertype = false;
                            ObjectType.WalkSupertypeRelationships(
                                identifierFor,
                                delegate(SubtypeFact subtypeFact, ObjectType type, int depth)
                            {
                                // Note that we do not check if the supertype is a preferred
                                // path here, only that supertypes are available.
                                haveSupertype = true;
                                return(ObjectTypeVisitorResult.Stop);
                            });
                            return(!haveSupertype);
                        }
                    }
                    return(false);
                }
                else
                {
                    return(!uniquenessConstraint.TestAllowPreferred(null, false));
                }
            }
            else if (propertyId == UniquenessConstraint.ModalityDomainPropertyId &&
                     (uniquenessConstraint = ModelElement).Store != null &&
                     uniquenessConstraint.IsInternal &&
                     (roles = uniquenessConstraint.RoleCollection).Count == 1 &&
                     ((factType = roles[0].FactType).ImpliedByObjectification != null ||
                      factType is SubtypeFact))
            {
                return(true);
            }
            return(base.IsPropertyDescriptorReadOnly(propertyDescriptor));
        }
        private static void RestoreLinkShapes(Diagram diagram, LinkedElementCollection<LinkShapeInfo> infos)
        {                   
            // links
            List<LinkShape> newShapes = new List<LinkShape>();
            foreach (LinkShape shape in diagram.LinkShapes)
            {
                if (!ProcessLinkShape(shape, infos))
                    newShapes.Add(shape);
            }

            foreach (Diagram d in diagram.IncludedDiagrams)
                RestoreLinkShapes(d, infos);

            // update layout of new link shapes
            foreach (LinkShape linkShape in newShapes)
            {
                linkShape.Layout(FixedGeometryPoints.None);

                linkShape.SourceAnchor.DiscardLocationChange = false;
                linkShape.TargetAnchor.DiscardLocationChange = false;
            }
        }
示例#36
0
        private void DrawDiagram(bool refresh, ModelElement element, IHierarchyContextEnabled hierarchyElement)
        {
            bool storeChange = false;

            if (hierarchyElement == null && (myDiagram == null || (element != null && (storeChange = (element.Store != myDiagram.Store)))))
            {
                ModelElement selectedElement = element;
                element = myCurrentlySelectedObject as ModelElement;
                if (element != null && ((element.IsDeleted || element.Store == null) || storeChange))
                {
                    myCurrentlySelectedObject = null;
                    mySelectedPartitionId     = null;
                    RemoveDiagram();
                }
                hierarchyElement = myCurrentlySelectedObject;
                if (hierarchyElement == null && selectedElement != null && !selectedElement.IsDeleted && selectedElement.Store != null)
                {
                    ORMModel attachToModel = selectedElement as ORMModel;
                    if (attachToModel != null)
                    {
                        EnsureDiagram(attachToModel);
                    }
                }
            }
            else if (hierarchyElement == myCurrentlySelectedObject && hierarchyElement != null && !refresh && (myDiagram != null && myDiagram.HasChildren))
            {
                return;
            }
            if (hierarchyElement == null)
            {
                return;
            }
            myCurrentlySelectedObject = hierarchyElement;
            mySelectedPartitionId     = ((ModelElement)hierarchyElement).Partition.AlternateId;
            ORMModel model = hierarchyElement.Model;

            if (model == null)
            {
                return;
            }
            this.EnsureDiagram(model);
            if (myDiagram == null)
            {
                return;
            }
            Store            store        = element.Store;
            IORMToolServices toolServices = (IORMToolServices)store;

            if (!toolServices.CanAddTransaction)
            {
                return;
            }
            using (Transaction t = store.TransactionManager.BeginTransaction("Draw Context Diagram"))
            {
                myDiagram.NestedChildShapes.Clear();
                myDiagram.AutoPopulateShapes = true;

                PlaceObject(hierarchyElement);
                LinkedElementCollection <ShapeElement> collection = myDiagram.NestedChildShapes;
                LayoutManager bl = new LayoutManager(myDiagram, toolServices.GetLayoutEngine(typeof(ORMRadialLayoutEngine)));
                foreach (ShapeElement shape in collection)
                {
                    bl.AddShape(shape, false);
                }
                bl.Layout(true);

                myDiagram.AutoPopulateShapes = false;
                if (t.HasPendingChanges)
                {
                    t.Commit();
                }
            }
            return;
        }
        private static bool ProcessLinkShape(LinkShape shapeElement, LinkedElementCollection<LinkShapeInfo> infos)
        {
            // try to find NodeShapeInfo for shape element
            LinkShapeInfo info = null;
            LinkShapeInfo infoAdv = null;
            foreach (LinkShapeInfo i in infos)
            {
                if (i.ElementId == shapeElement.Element.Id)
                {
                    info = i;
                    break;
                }
                else if( shapeElement.Element.GetDomainClass().Id == i.LinkDomainClassId &&
                    shapeElement.FromShape.Element.Id == i.SourceElementId && 
                    shapeElement.ToShape.Element.Id == i.TargetElementId )
                {
                    infoAdv = i;
                }
            }

            if (info == null && infoAdv != null)
                info = infoAdv;

            if (info == null)
            {
                shapeElement.SourceAnchor.DiscardLocationChange = false;
                shapeElement.TargetAnchor.DiscardLocationChange = false;
                return false;
            }

            shapeElement.SourceAnchor.SetRelativeLocation(info.SourceLocation);
            shapeElement.TargetAnchor.SetRelativeLocation(info.TargetLocation);

            shapeElement.RoutingMode = info.RoutingMode;
            if (info.EdgePoints != null)
                shapeElement.EdgePoints = ConvertFromRelativeEdgePoints(info.EdgePoints, shapeElement.SourceAnchor.AbsoluteLocation);
            else
            {
                shapeElement.EdgePoints.Add(new EdgePoint(shapeElement.SourceAnchor.AbsoluteLocation));
                shapeElement.EdgePoints.Add(new EdgePoint(shapeElement.TargetAnchor.AbsoluteLocation));
            }

            return true;
        }
示例#38
0
 internal static int GetCompositeKeyCount(LinkedElementCollection<ModelProperty> properties)
 {
     return GetCompositeKeys(properties).Count;
 }
示例#39
0
		private static IList FilterElementsFromElementSchemaForProperties(LinkedElementCollection<PropertySchema> result)
		{
			return ShapeExtensions.FilterElementsFromCompartment<PropertySchema, string>(result,
				(item => true), item => item.Name);
		}
示例#40
0
        /// <summary>
        /// Add shared model error activation handlers. Activation handlers are
        /// static, this is called once during intitial load.
        /// </summary>
        /// <param name="store">The <see cref="Store"/></param>
        public static void RegisterModelErrorActivators(Store store)
        {
            IORMToolServices toolServices;
            IORMModelErrorActivationService activationService;

            if (null != (toolServices = store as IORMToolServices) &&
                null != (activationService = toolServices.ModelErrorActivationService))
            {
                #region Role error activation
                activationService.RegisterErrorActivator(
                    typeof(Role),
                    true,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    if (error is RolePlayerRequiredError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            RoleTypeDescriptor.GetRolePlayerDisplayPropertyDescriptor((Role)selectedElement),
                            true);
                    }
                    else if (error is ValueConstraintError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, Role.ValueRangeTextDomainPropertyId),
                            false);
                    }
                    else if (error is CardinalityRangeOverlapError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            RoleTypeDescriptor.CardinalityDisplayPropertyDescriptor,
                            false);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // Role error activation
                #region ValueConstraint error activation
                activationService.RegisterErrorActivator(
                    typeof(ValueConstraint),
                    true,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    if (error is ValueConstraintError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, ValueConstraint.TextDomainPropertyId),
                            false);
                    }
                    else if (error is ConstraintDuplicateNameError)
                    {
                        ActivateNameProperty(selectedElement);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // ValueConstraint error activation
                #region CardinalityConstraint error activation
                activationService.RegisterErrorActivator(
                    typeof(CardinalityConstraint),
                    true,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    if (error is CardinalityRangeOverlapError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, CardinalityConstraint.TextDomainPropertyId),
                            false);
                    }
                    else if (error is ConstraintDuplicateNameError)
                    {
                        ActivateNameProperty(selectedElement);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // CardinalityConstraint error activation
                #region SetConstraint error activation
                activationService.RegisterErrorActivator(
                    typeof(SetConstraint),
                    true,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    if (error is ConstraintDuplicateNameError)
                    {
                        ActivateNameProperty(selectedElement);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // SetConstraint error activation
                #region FrequencyConstraint error activation
                activationService.RegisterErrorActivator(
                    typeof(FrequencyConstraint),
                    true,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    if (error is FrequencyConstraintExactlyOneError)
                    {
                        ((FrequencyConstraint)selectedElement).ConvertToUniquenessConstraint();
                    }
                    else if (error is FrequencyConstraintNonRestrictiveRangeError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, FrequencyConstraint.MinFrequencyDomainPropertyId),
                            false);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // FrequencyConstraint error activation
                #region RingConstraint error activation
                activationService.RegisterErrorActivator(
                    typeof(RingConstraint),
                    false,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    if (error is RingConstraintTypeNotSpecifiedError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, RingConstraint.RingTypeDomainPropertyId),
                            true);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // RingConstraint error activation
                #region ValueComparisonConstraint error activation
                activationService.RegisterErrorActivator(
                    typeof(ValueComparisonConstraint),
                    false,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    if (error is ValueComparisonConstraintOperatorNotSpecifiedError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, ValueComparisonConstraint.OperatorDomainPropertyId),
                            true);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // ValueComparisonConstraint error activation
                #region SetComparisonConstraint error activation
                activationService.RegisterErrorActivator(
                    typeof(SetComparisonConstraint),
                    true,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    ConstraintDuplicateNameError duplicateName;
                    if (null != (duplicateName = error as ConstraintDuplicateNameError))
                    {
                        ActivateNameProperty(selectedElement);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // SetComparisonConstraint error activation
                #region ObjectType error activation
                activationService.RegisterErrorActivator(
                    typeof(ObjectType),
                    false,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    bool retVal = true;
                    PopulationMandatoryError populationMandatory;
                    if (error is DataTypeNotSpecifiedError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            ObjectTypeTypeDescriptor.DataTypeDisplayPropertyDescriptor,
                            true);
                    }
                    else if (error is EntityTypeRequiresReferenceSchemeError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, ObjectType.ReferenceModeDisplayDomainPropertyId),
                            true);
                    }
                    else if (error is ValueConstraintError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, ObjectType.ValueRangeTextDomainPropertyId),
                            false);
                    }
                    else if (error is CardinalityRangeOverlapError)
                    {
                        EditorUtility.ActivatePropertyEditor(
                            services.ServiceProvider,
                            ObjectTypeTypeDescriptor.CardinalityDisplayPropertyDescriptor,
                            false);
                    }
                    else if (error is ObjectTypeDuplicateNameError)
                    {
                        ActivateNameProperty(selectedElement);
                    }
                    else if (error is ObjectifiedInstanceRequiredError || error is TooFewEntityTypeRoleInstancesError)
                    {
                        ORMDesignerPackage.SamplePopulationEditorWindow.ActivateModelError(error);
                    }
                    else if (null != (populationMandatory = error as PopulationMandatoryError))
                    {
                        retVal = ORMDesignerPackage.SamplePopulationEditorWindow.AutoCorrectMandatoryError(populationMandatory, (ObjectType)selectedElement);
                    }
                    else
                    {
                        retVal = false;
                    }
                    return(retVal);
                });
                #endregion                 // ObjectType error activation
                #region FactType error activation
                activationService.RegisterErrorActivator(
                    typeof(FactType),
                    true,
                    delegate(IORMToolServices services, ModelElement selectedElement, ModelError error)
                {
                    PopulationMandatoryError populationMandatory;
                    TooFewReadingRolesError tooFew;
                    TooManyReadingRolesError tooMany;
                    ReadingRequiresUserModificationError userModification;
                    DuplicateReadingSignatureError duplicateSignature;
                    FactTypeRequiresReadingError noReading;
                    ValueConstraintError valueError;
                    CardinalityRangeOverlapError cardinalityRangeError;
                    FactType factType;
                    ImpliedInternalUniquenessConstraintError implConstraint;
                    Reading reading = null;
                    bool retVal     = true;
                    if (null != (populationMandatory = error as PopulationMandatoryError))
                    {
                        retVal = ORMDesignerPackage.SamplePopulationEditorWindow.AutoCorrectMandatoryError(populationMandatory, null, (FactType)selectedElement);
                    }
                    else if (null != (tooFew = error as TooFewReadingRolesError))
                    {
                        reading = tooFew.Reading;
                    }
                    else if (null != (tooMany = error as TooManyReadingRolesError))
                    {
                        reading = tooMany.Reading;
                    }
                    else if (null != (noReading = error as FactTypeRequiresReadingError))
                    {
                        factType = noReading.FactType;
                        Debug.Assert(factType != null);
                        ORMReadingEditorToolWindow newWindow = ORMDesignerPackage.ReadingEditorWindow;
                        newWindow.Show();
                        newWindow.ActivateReading(factType);
                    }
                    else if (null != (userModification = error as ReadingRequiresUserModificationError))
                    {
                        reading = userModification.Reading;
                    }
                    else if (null != (duplicateSignature = error as DuplicateReadingSignatureError))
                    {
                        factType = (FactType)selectedElement;
                        LinkedElementCollection <Reading> readings = duplicateSignature.ReadingCollection;
                        foreach (Reading testReading in readings)
                        {
                            if (testReading.ReadingOrder.FactType == factType)
                            {
                                reading = testReading;
                                break;
                            }
                        }
                        if (reading == null)
                        {
                            Objectification objectification;
                            if (null != (objectification = factType.Objectification))
                            {
                                foreach (Reading testReading in readings)
                                {
                                    if (testReading.ReadingOrder.FactType.ImpliedByObjectification == objectification)
                                    {
                                        reading = testReading;
                                        break;
                                    }
                                }
                            }
                            if (reading == null)
                            {
                                // Defensive, shouldn't happen.
                                reading = readings[0];
                            }
                        }
                    }
                    else if (null != (implConstraint = error as ImpliedInternalUniquenessConstraintError))
                    {
                        IServiceProvider provider;
                        IVsUIShell shell;
                        if (null != (provider = services.ServiceProvider) &&
                            null != (shell = (IVsUIShell)provider.GetService(typeof(IVsUIShell))))
                        {
                            Guid g = new Guid();
                            int pnResult;
                            shell.ShowMessageBox(0, ref g, ResourceStrings.PackageOfficialName,
                                                 ResourceStrings.ImpliedInternalConstraintFixMessage,
                                                 "", 0, OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
                                                 OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_QUERY, 0, out pnResult);
                            if (pnResult == (int)DialogResult.Yes)
                            {
                                implConstraint.FactType.RemoveImpliedInternalUniquenessConstraints();
                            }
                        }
                    }
                    else if (null != (valueError = error as ValueConstraintError))
                    {
                        if (valueError.ContextValueConstraint is RoleValueConstraint)
                        {
                            EditorUtility.ActivatePropertyEditor(
                                services.ServiceProvider,
                                DomainTypeDescriptor.CreatePropertyDescriptor(selectedElement, ObjectType.ValueRangeTextDomainPropertyId),
                                false);
                        }
                        else
                        {
                            retVal = false;
                        }
                    }
                    else if (null != (cardinalityRangeError = error as CardinalityRangeOverlapError))
                    {
                        if (cardinalityRangeError.CardinalityConstraint is ObjectTypeCardinalityConstraint)
                        {
                            EditorUtility.ActivatePropertyEditor(
                                services.ServiceProvider,
                                ObjectTypeTypeDescriptor.CardinalityDisplayPropertyDescriptor,
                                false);
                        }
                        else
                        {
                            retVal = false;
                        }
                    }
                    else if (error is TooFewFactTypeRoleInstancesError || error is ObjectifyingInstanceRequiredError)
                    {
                        ORMDesignerPackage.SamplePopulationEditorWindow.ActivateModelError(error);
                    }
                    else
                    {
                        retVal = false;
                    }

                    if (reading != null)
                    {
                        // Open the reading editor window and activate the reading
                        ORMReadingEditorToolWindow window = ORMDesignerPackage.ReadingEditorWindow;
                        window.Show();
                        window.ActivateReading(reading);
                    }
                    return(retVal);
                });
                #endregion                 // FactType error activation
            }
        }