/// <summary>
        /// Gets the dependencies for a specific model element.
        /// </summary>
        /// <param name="modelElement">Model element to get the dependencies for.</param>
        /// <param name="options">Options.</param>
        /// <returns>List of dependencies.</returns>
        public DependenciesData GetDependencies(ModelElement modelElement, DependenciesRetrivalOptions options)
        {
            List<ModelElement> elements = new List<ModelElement>();
            elements.Add(modelElement);

            return GetDependencies(elements, options);
        }
        //TODO: FIXME - This method is a royal mess! 
        public override  bool Visit(ElementWalker walker, ModelElement modelElement)
        {
            var result = base.Visit(walker, modelElement);
            if (walker.InternalElementList.Last() == modelElement)
            {
                var typesNode = this.treeView.Nodes[0].Nodes[0];
                typesNode.Text = "Models";
                foreach (ModelElementTreeNode classNode in typesNode.Nodes)
                {
                    var originalNodes = classNode.Nodes.OfType<RoleGroupTreeNode>().ToArray();
                    foreach (RoleGroupTreeNode roleGroupNode in originalNodes)
                    {
                        var toRemove = new List<ModelElementTreeNode>();
                        foreach (ModelElementTreeNode propNode in roleGroupNode.Nodes)
                        {
                            toRemove.Add(propNode);
                        }

                        foreach (var node in toRemove)
                        {
                            roleGroupNode.Nodes.Remove(node);
                            this.TreeContainer.InsertTreeNode(classNode.Nodes, node);
                        }
                    }
                    foreach (TreeNode node in originalNodes) classNode.Nodes.Remove(node);
                }
                typesNode.Expand();
            }
            return result;
        }
        public static void AddClass(ModelElement cls, CodeTypeDeclaration declaration)
        {
            if (!isInitialized)
                throw new ArgumentException("CodeGenerationContext must first be initialized");
            if (cls == null)
                throw new ArgumentNullException("No class supplied", "cls");
            if (declaration == null)
                throw new ArgumentNullException("No CodeTypeDeclaration supplied", "declaration");

            if (cls.GetType() == typeof(ModelClass))
            {
                ModelClass modelClass = (ModelClass)cls;
                if (!classDeclarations.ContainsKey(modelClass))
                    classDeclarations.Add(modelClass, declaration);
            }
            else if (cls.GetType() == typeof(NestedClass))
            {
                NestedClass nestedClass = (NestedClass)cls;
                if (!nestedClassDeclarations.ContainsKey(nestedClass))
                    nestedClassDeclarations.Add(nestedClass, declaration);
            }
            else
                throw new ArgumentException("Only ModelClass and NestedClass entities supported", "cls");

            generatedClassNames.Add(((NamedElement)cls).Name);
        }
        /// <summary>
        /// Gets the dependencies for a specific model element.
        /// </summary>
        /// <param name="modelElement">Model element to get the dependencies for.</param>
        /// <returns>List of dependencies.</returns>
        public DependenciesData GetDependencies(ModelElement modelElement)
        {
            List<ModelElement> elements = new List<ModelElement>();
            elements.Add(modelElement);

            return GetDependencies(elements);
        }
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="element">The element for which this explanation part is created</param>
 /// <param name="leftPart">The left path to associate to this explanation</param>
 /// <param name="rightPart">The value associate to this left part</param>
 public ExplanationPart(ModelElement element, object leftPart, INamable rightPart = null)
 {
     Element = element;
     LeftPart = leftPart;
     RightPart = rightPart;
     SubExplanations = new List<ExplanationPart>();
 }
        /// <summary>
        /// Ensures that the parameter provided corresponds to a function double->double
        /// </summary>
        /// <param name="root">Element on which the errors shall be attached</param>
        /// <param name="context">The context used to evaluate the expression</param>
        /// <param name="expression">The expression which references the function</param>
        /// <param name="count">the expected number of parameters</param>
        protected virtual void CheckFunctionalParameter(ModelElement root, Interpreter.InterpretationContext context, Interpreter.Expression expression, int count)
        {
            Types.Type type = expression.GetExpressionType();

            Function function = type as Function;
            if (function != null)
            {
                if (function.FormalParameters.Count == count)
                {
                    foreach (Parameter parameter in function.FormalParameters)
                    {
                        if (!parameter.Type.IsDouble())
                        {
                            root.AddError(expression.ToString() + " does not takes a double for parameter " + parameter.Name);
                        }
                    }
                }
                else
                {
                    root.AddError(expression.ToString() + " does not take " + count + "parameter(s) as input");
                }

                if (!function.ReturnType.IsDouble())
                {
                    root.AddError(expression.ToString() + " does not return a double");
                }
            }
            else
            {
                if (!type.IsDouble())
                {
                    root.AddError(expression.ToString() + " type is not double");
                }
            }
        }
        /// <summary>
        /// Gets the element name from the property that is marked as "IsElementName".
        /// </summary>
        /// <param name="modelElement">Domain class to get the name for.</param>
        /// <returns>Name of the domain class as string if found. Null otherwise.</returns>
        public virtual string GetName(ModelElement modelElement)
		{
			if( modelElement is IDomainModelOwnable )
				return (modelElement as IDomainModelOwnable).DomainElementName;
			
			return null;		
		}
 internal override EntityDesignerDiagram CreateDiagramHelper(Partition diagramPartition, ModelElement modelRoot)
 {
     var evm = modelRoot as EntityDesignerViewModel;
     var diagram = new EntityDesignerDiagram(diagramPartition);
     diagram.ModelElement = evm;
     return diagram;
 }
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="root"></param>
 /// <param name="log"></param>
 /// <param name="structure"></param>
 /// <param name="associations"></param>
 /// <param name="parsingData">Additional information about the parsing process</param>
 public StructExpression(ModelElement root, ModelElement log, Expression structure,
     Dictionary<Designator, Expression> associations, ParsingData parsingData)
     : base(root, log, parsingData)
 {
     Structure = SetEnclosed(structure);
     SetAssociation(associations);
 }
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="root"></param>
 /// <param name="log"></param>
 /// <param name="structure"></param>
 /// <param name="associations"></param>
 /// <param name="start">The start character for this expression in the original string</param>
 /// <param name="end">The end character for this expression in the original string</param>
 public StructExpression(ModelElement root, ModelElement log, Expression structure,
     Dictionary<Designator, Expression> associations, int start, int end)
     : base(root, log, start, end)
 {
     Structure = structure;
     SetAssociation(associations);
 }
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="root">The root element for which this element is built</param>
 /// <param name="log"></param>
 /// <param name="variableIdentification"></param>
 /// <param name="expression"></param>
 /// <param name="parsingData">Additional information about the parsing process</param>
 public VariableUpdateStatement(ModelElement root, ModelElement log, Expression variableIdentification,
     Expression expression, ParsingData parsingData)
     : base(root, log, parsingData)
 {
     VariableIdentification = SetEnclosed(variableIdentification);
     Expression = SetEnclosed(expression);
 }
Exemplo n.º 12
0
		/// <summary>
		/// Customize childshape create to set an initial location for a <see cref="TableShape"/>
		/// </summary>
		protected override ShapeElement CreateChildShape(ModelElement element)
		{
			object tablePositionsObject;
			Dictionary<Guid, PointD> tablePositions;
			PointD initialLocation;
			ReferenceConstraintTargetsTable referenceConstraintTargetsTable;
			Table table;
			ConceptType conceptType;
			ObjectType objectType;
			if (null != (table = element as Table))
			{
				if (element.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.TryGetValue(TablePositionDictionaryKey, out tablePositionsObject) &&
					null != (tablePositions = tablePositionsObject as Dictionary<Guid, PointD>) &&
					null != (conceptType = TableIsPrimarilyForConceptType.GetConceptType(table)) &&
					null != (objectType = ConceptTypeIsForObjectType.GetObjectType(conceptType)) &&
					tablePositions.TryGetValue(objectType.Id, out initialLocation))
				{
					return new TableShape(
						this.Partition,
						new PropertyAssignment(TableShape.AbsoluteBoundsDomainPropertyId, new RectangleD(initialLocation, new SizeD(1, 0.3))));
				}
			}
			else if (null != (referenceConstraintTargetsTable = element as ReferenceConstraintTargetsTable))
			{
				return new ForeignKeyConnector(Partition);
			}
			return base.CreateChildShape(element);
		}
		public static bool CanAcceptSourceAndTarget(ModelElement candidateSource, ModelElement candidateTarget)
		{
			if(candidateSource == null)
			{
				return false;
			}

			bool acceptSource = CanAcceptSource(candidateSource);
			// If the source wasn't accepted then there's no point checking targets.
			// If there is no target then the source controls the accept.
			if(!acceptSource || candidateTarget == null)
			{
				return acceptSource;
			}
			else // Check combinations
			{
				if(candidateSource is DataContractBase)
				{
                    if (candidateTarget is DataContract) 
					{
						if(HasNullReferences((DataContractBase)candidateSource, (Contract)candidateTarget))
						{
							return false;
						}						
						return true;
					}
				}
			}
			return false;
		}
Exemplo n.º 14
0
        /// <summary>
        /// Perform additional checks based on the parameter types
        /// </summary>
        /// <param name="root">The element on which the errors should be reported</param>
        /// <param name="context">The evaluation context</param>
        /// <param name="actualParameters">The parameters applied to this function call</param>
        public override void additionalChecks(ModelElement root, Interpreter.InterpretationContext context, Dictionary<string, Interpreter.Expression> actualParameters)
        {
            CheckFunctionalParameter(root, context, actualParameters[First.Name], 1);
            CheckFunctionalParameter(root, context, actualParameters[Second.Name], 1);

            Function function1 = actualParameters[First.Name].GetExpressionType() as Function;
            Function function2 = actualParameters[Second.Name].GetExpressionType() as Function;

            if (function1 != null && function2 != null)
            {
                if (function1.FormalParameters.Count == 1 && function2.FormalParameters.Count == 1)
                {
                    Parameter p1 = (Parameter)function1.FormalParameters[0];
                    Parameter p2 = (Parameter)function2.FormalParameters[0];

                    if (p1.Type != p2.Type && p1.Type != EFSSystem.DoubleType && p2.Type != EFSSystem.DoubleType)
                    {
                        root.AddError("The formal parameters for the functions provided as parameter are not the same");
                    }
                }

                if (function1.ReturnType != function2.ReturnType && function1.ReturnType != EFSSystem.DoubleType && function2.ReturnType != EFSSystem.DoubleType)
                {
                    root.AddError("The return values for the functions provided as parameter are not the same");
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Decides what the icon of the method will be in the interface shape
        /// </summary>
        protected System.Drawing.Image GetElementImage(ModelElement mel)
        {
            var assembly = Assembly.GetExecutingAssembly();

            if (_images.Count == 0)
            {
                _images.Add("field", new System.Drawing.Bitmap(assembly.GetManifestResourceStream(assembly.GetName().Name + ".Resources.field.png")));
                _images.Add("key", new System.Drawing.Bitmap(assembly.GetManifestResourceStream(assembly.GetName().Name + ".Resources.key.png")));
            }

            if (mel is nHydrate.Dsl.ViewField)
            {
                var field = mel as nHydrate.Dsl.ViewField;
                var image = field.CachedImage;
                if (image == null)
                {
                    image = _images["field"];

                    //Primary Key
                    if (field.IsPrimaryKey)
                        image = _images["key"];

                    field.CachedImage = image;
                }
                return image;
            }
            else
            {
                return null;
            }
        }
 /// <summary>
 ///     Constructor for MAP, REDUCE
 /// </summary>
 /// <param name="listExpression"></param>
 /// <param name="condition">the condition to apply to list elements</param>
 /// <param name="iteratorExpression">the expression to be evaluated on each element of the list</param>
 /// <param name="iteratorVariableName"></param>
 /// <param name="start">The start character for this expression in the original string</param>
 /// <param name="end">The end character for this expression in the original string</param>
 public ExpressionBasedListExpression(ModelElement root, ModelElement log, Expression listExpression,
     string iteratorVariableName, Expression condition, Expression iteratorExpression, int start, int end)
     : base(root, log, listExpression, iteratorVariableName, condition, start, end)
 {
     IteratorExpression = iteratorExpression;
     IteratorExpression.Enclosing = this;
 }
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="log"></param>
        /// <param name="listExpression"></param>
        /// <param name="condition"></param>
        /// <param name="expression"></param>
        /// <param name="root">the root element for which this expression should be parsed</param>
        /// <param name="iteratorVariableName"></param>
        /// <param name="parsingData">Additional information about the parsing process</param>
        public SumExpression(ModelElement root, ModelElement log, Expression listExpression, string iteratorVariableName,
            Expression condition, Expression expression, ParsingData parsingData)
            : base(root, log, listExpression, iteratorVariableName, condition, expression, parsingData)
        {
            AccumulatorVariable = CreateBoundVariable("RESULT", null);
            ISubDeclaratorUtils.AppendNamable(this, AccumulatorVariable);

            if (expression != null)
            {
                DefinedAccumulator = SetEnclosed(expression);
                Accumulator =
                    SetEnclosed(new BinaryExpression(
                        Root,
                        RootLog,
                        DefinedAccumulator,
                        BinaryExpression.Operator.Add,
                        new UnaryExpression(
                            Root,
                            RootLog,
                            new Term(
                                Root,
                                RootLog,
                                new Designator(Root, RootLog, "RESULT", ParsingData.SyntheticElement),
                                ParsingData.SyntheticElement),
                            ParsingData.SyntheticElement),
                        ParsingData.SyntheticElement));
            }
        }
Exemplo n.º 18
0
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="element">The element for which this explanation part is created</param>
 /// <param name="message">The message to display. MAKE SURE you do not use string concatenation to create this message</param>
 /// <param name="rightPart">The value associated to the message, if any</param>
 public ExplanationPart(ModelElement element, string message, INamable rightPart = null)
 {
     Element = element;
     Message = message;
     RightPart = rightPart;
     SubExplanations = new List<ExplanationPart>();
 }
        /// <summary>
        /// Verifies if a given modelElement has a name property or not.
        /// </summary>
        /// <param name="modelElement">ModelElement to verify.</param>
        /// <returns>
        /// True if the given model element has a property marked with "IsElementName" set to true. False otherwise.
        /// </returns>
        public virtual bool HasName(ModelElement modelElement)
		{
			if( modelElement is IDomainModelOwnable )
				return (modelElement as IDomainModelOwnable).DomainElementHasName;

			return false;
		}
Exemplo n.º 20
0
		/// <summary>
		/// Customize childshape create to set an initial location for a <see cref="BarkerEntityShape"/>
		/// </summary>
		protected override ShapeElement CreateChildShape(ModelElement element)
		{
			object barkerEntityPositionsObject;
			Dictionary<Guid, PointD> barkerEntityPositions;
			PointD initialLocation;
			BarkerErModelContainsBinaryAssociation modelContainsAssociation;
			EntityType barkerEntity;
			ConceptType conceptType;
			ObjectType objectType;
			if (null != (barkerEntity = element as EntityType))
			{
				if (element.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.TryGetValue(BarkerEntityPositionDictionaryKey, out barkerEntityPositionsObject) &&
					null != (barkerEntityPositions = barkerEntityPositionsObject as Dictionary<Guid, PointD>) &&
					null != (conceptType = EntityTypeIsPrimarilyForConceptType.GetConceptType(barkerEntity)) &&
					null != (objectType = ConceptTypeIsForObjectType.GetObjectType(conceptType)) &&
					barkerEntityPositions.TryGetValue(objectType.Id, out initialLocation))
				{
					return new BarkerEntityShape(
						this.Partition,
						new PropertyAssignment(BarkerEntityShape.AbsoluteBoundsDomainPropertyId, new RectangleD(initialLocation, new SizeD(1, 0.3))));
				}
			}
			else if (null != (modelContainsAssociation = element as BarkerErModelContainsBinaryAssociation))
			{
				return new AssociationConnector(Partition);
			}
			return base.CreateChildShape(element);
		}
        /// <summary>
        /// Retrieves all children of a specific parent element. This includes all model elements that are reachable
        /// from the parent element through the embedding relationship.
        /// </summary>
        /// <param name="parentElement">Parent element to retrieve children for.</param>
        /// <param name="bOnlyLocal">Specifies if children of the found children of the given element should be processed too.</param>
        /// <returns>List of model elements that are embedded under the parent element. May be empty.</returns>
        public virtual List<ModelElement> GetChildren(ModelElement parentElement, bool bOnlyLocal)
        {
            List<ModelElement> allChildren = new List<ModelElement>();

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

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

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

                            }
                        }
                    }
            }

            return allChildren;
        }
Exemplo n.º 22
0
        public static void Validate(ValidationElementState state, ValidationContext context, ModelElement currentElement)
		{
			Guard.ArgumentNotNull(context, "context");
			Guard.ArgumentNotNull(currentElement, "currentElement");

            if (ShouldAbortValidation(context))
            {
                return;
            }
            
            try
            {
                InitializeFactory(context);

                if (validatorFactory != null)
                {
                    DoValidate(currentElement, context, CommonRuleSet);
                    DoValidate(currentElement, context, context.Categories.ToString());
                    ShowStatus(currentElement);
                    return;
                }
                // trace when no config service
                context.LogWarning(Resources.NoValidationServiceAvailable, Constants.ValidationCode, currentElement);
            }
            catch (Exception ex)
            {
                context.LogFatal(LogEntry.ErrorMessageToString(ex), Constants.ValidationCode, currentElement);
                Trace.TraceError(ex.ToString());
            }
		}
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="root">The root for which this expression should be evaluated</param>
 /// <param name="log"></param>
 /// <param name="expression">The enclosed expression</param>
 /// <param name="unaryOp">the unary operator for this unary expression</param>
 /// <param name="start">The start character for this expression in the original string</param>
 /// <param name="end">The end character for this expression in the original string</param>
 public UnaryExpression(ModelElement root, ModelElement log, Expression expression, string unaryOp, int start,
     int end)
     : base(root, log, start, end)
 {
     Expression = SetEnclosed(expression);
     UnaryOp = unaryOp;
 }
Exemplo n.º 24
0
		protected string GetElementText(ModelElement mel)
		{
			if (mel is nHydrate.Dsl.StoredProcedureField)
			{
				var field = mel as nHydrate.Dsl.StoredProcedureField;
				var model = this.Diagram as nHydrateDiagram;
				var text = field.Name;
				if (model.DisplayType)
					text += " : " + field.DataType.GetSQLDefaultType(field.Length, field.Scale) +
						" " + (field.Nullable ? "Null" : "Not Null");
				return text;
			}
			else if (mel is nHydrate.Dsl.StoredProcedureParameter)
			{
				var parameter = mel as nHydrate.Dsl.StoredProcedureParameter;
				var model = this.Diagram as nHydrateDiagram;
				var text = parameter.Name;
				if (model.DisplayType)
					text += " : " + parameter.DataType.GetSQLDefaultType(parameter.Length, parameter.Scale) +
						" " + (parameter.Nullable ? "Null" : "Not Null");
				return text;
			}
			else
			{
				return string.Empty;
			}
		}
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="root">The root element for which this element is built</param>
 /// <param name="log"></param>
 /// <param name="value">The value to insert</param>
 /// <param name="listExpression">The list to alter</param>
 /// <param name="replaceElement">The element to be replaced, if any</param>
 /// <param name="parsingData">Additional information about the parsing process</param>
 public InsertStatement(ModelElement root, ModelElement log, Expression value, Expression listExpression,
     Expression replaceElement, ParsingData parsingData)
     : base(root, log, parsingData)
 {
     Value = SetEnclosed(value);
     ListExpression = SetEnclosed(listExpression);
     ReplaceElement = SetEnclosed(replaceElement);
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="root">The root for which this expression should be evaluated</param>
        /// <param name="expression">The enclosed expression</param>
        /// <param name="unaryOp">the unary operator for this unary expression</parparam>
        public UnaryExpression(ModelElement root, Expression expression, string unaryOp = null)
            : base(root)
        {
            Expression = expression;
            Expression.Enclosing = this;

            UnaryOp = unaryOp;
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="elementLink">Relationship instance.</param>
 /// <param name="category">Category of the dependency item.</param>
 public DependencyItem(ElementLink elementLink, DependencyItemCategory category, ModelElement source, ModelElement target)
 {
     this.elementLink = elementLink;
     this.itemCategory = category;
     this.SourceElement = source;
     this.TargetElement = target;
     this.Message = null;
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="elementLink">Relationship instance.</param>
 /// <param name="category">Category of the dependency item.</param>
 public DependencyItem(string message, DependencyItemCategory category, ModelElement source, ModelElement target)
 {
     this.elementLink = null;
     this.itemCategory = category;
     this.SourceElement = source;
     this.TargetElement = target;
     this.Message = message;
 }
Exemplo n.º 29
0
		/// <summary>
		/// Gets the <see cref="IORMExtendableElement"/> that the extension <see cref="ModelElement"/> specified
		/// by <paramref name="extensionElement"/> is attached to.
		/// </summary>
		public static IORMExtendableElement GetExtendedElement(ModelElement extensionElement)
		{
			if (extensionElement == null)
			{
				throw new ArgumentNullException("extensionElement");
			}
			return (IORMExtendableElement)DomainRoleInfo.GetLinkedElement(extensionElement, ORMModelElementHasExtensionElement.ExtensionDomainRoleId);
		}
Exemplo n.º 30
0
 private static void FixUpDiagram(ModelElement root, ModelElement child, string diagramId, IEnumerable<ShapeElement> shapes)
 {
     if (shapes.Count() == 0 ||
         !shapes.Any(shape => ((PatternModelSchemaDiagram)shape.Diagram).Id.ToString().Equals(diagramId, StringComparison.OrdinalIgnoreCase)))
     {
         root.Store.TransactionManager.DoWithinTransaction(() => Diagram.FixUpDiagram(root, child));
     }
 }
Exemplo n.º 31
0
        /// <summary>
        /// This method creates an instance of AblaufbausteinpunktRAblaufbausteinspezShape based on the tag currently pointed by the reader. The reader is guaranteed (by the caller)
        /// to be pointed at a serialized instance of AblaufbausteinpunktRAblaufbausteinspezShape.
        /// </summary>
        /// <remarks>
        /// The caller will guarantee that the reader is positioned at open XML tag of the ModelRoot instance being read. This method should
        /// not move the reader; the reader should remain at the same position when this method returns.
        /// </remarks>
        /// <param name="serializationContext">Serialization context.</param>
        /// <param name="reader">XmlReader to read serialized data from.</param>
        /// <param name="partition">Partition in which new AblaufbausteinpunktRAblaufbausteinspezShape instance should be created.</param>
        /// <returns>Created AblaufbausteinpunktRAblaufbausteinspezShape instance.</returns>
        protected override ModelElement CreateInstance(SerializationContext serializationContext, global::System.Xml.XmlReader reader, Partition partition)
        {
            string idStr = reader.GetAttribute("Id");

            try
            {
                global::System.Guid id;
                if (string.IsNullOrEmpty(idStr))
                {       // Create a default Id.
                    id = global::System.Guid.NewGuid();
                    TestDslDefinitionSerializationBehaviorSerializationMessages.MissingId(serializationContext, reader, id);
                }
                else
                {
                    id = new global::System.Guid(idStr);
                }

                string elementIdStr = reader.GetAttribute("internalElementId");
                if (string.IsNullOrEmpty(elementIdStr))
                {
                    return(null);
                }
                else
                {
                    global::System.Guid elementId = new global::System.Guid(elementIdStr);
                    ModelElement        element   = null;
                    if (elementId != System.Guid.Empty)
                    {
                        element = partition.ElementDirectory.FindElement(elementId);
                    }

                    string sourceShapeIdStr = reader.GetAttribute("sourceShapeId");
                    string targetShapeIdStr = reader.GetAttribute("targetShapeId");
                    if (string.IsNullOrEmpty(sourceShapeIdStr) || string.IsNullOrEmpty(targetShapeIdStr))
                    {
                        return(null);
                    }
                    else
                    {
                        global::System.Guid sourceShapeId = new global::System.Guid(sourceShapeIdStr);
                        global::System.Guid targetShapeId = new global::System.Guid(targetShapeIdStr);

                        NodeShape source = partition.ElementDirectory.FindElement(sourceShapeId) as NodeShape;
                        NodeShape target = partition.ElementDirectory.FindElement(targetShapeId) as NodeShape;

                        if (source == null || target == null)
                        {
                            return(null);
                        }


                        if (element == null)
                        {
                            element = CanAssignRelationship(source.Element, target.Element);
                        }

                        if (element == null || !(element is IDomainModelOwnable))
                        {
                            return(null);
                        }

                        return((element as IDomainModelOwnable).GetDomainModelServices().TopMostService.ShapeProvider.CreateShapeForElementLink(this.GetShapeClassId(), element, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) }));
                    }
                }
            }
            catch (global::System.ArgumentNullException /* anEx */)
            {
                TestDslDefinitionSerializationBehaviorSerializationMessages.InvalidPropertyValue(serializationContext, reader, "Id", typeof(global::System.Guid), idStr);
            }
            catch (global::System.FormatException /* fEx */)
            {
                TestDslDefinitionSerializationBehaviorSerializationMessages.InvalidPropertyValue(serializationContext, reader, "Id", typeof(global::System.Guid), idStr);
            }
            catch (global::System.OverflowException /* ofEx */)
            {
                TestDslDefinitionSerializationBehaviorSerializationMessages.InvalidPropertyValue(serializationContext, reader, "Id", typeof(global::System.Guid), idStr);
            }
            return(null);
        }
Exemplo n.º 32
0
        private Vector3 FixRotation(
            Vector3 v,
            ModelElement element)
        {
            if (element.Rotation.Axis != Axis.Undefined)
            {
                var r     = element.Rotation;
                var angle = (float)(r.Angle * (Math.PI / 180f));
                angle = (element.Rotation.Axis == Axis.Z) ? angle : -angle;

                var ci = 1.0f / MathF.Cos(angle);

                var origin = r.Origin;

                var c = MathF.Cos(angle);
                var s = MathF.Sin(angle);

                v.X -= (origin.X / 16.0f);
                v.Y -= (origin.Y / 16.0f);
                v.Z -= (origin.Z / 16.0f);

                switch (r.Axis)
                {
                case Axis.Y:
                {
                    var x = v.X;
                    var z = v.Z;

                    v.X = (x * c - z * s);
                    v.Z = (z * c + x * s);

                    if (r.Rescale)
                    {
                        v.X *= ci;
                        v.Z *= ci;
                    }
                }
                break;

                case Axis.X:
                {
                    var x = v.Z;
                    var z = v.Y;

                    v.Z = (x * c - z * s);
                    v.Y = (z * c + x * s);

                    if (r.Rescale)
                    {
                        v.Z *= ci;
                        v.Y *= ci;
                    }
                }
                break;

                case Axis.Z:
                {
                    var x = v.X;
                    var z = v.Y;

                    v.X = (x * c - z * s);
                    v.Y = (z * c + x * s);

                    if (r.Rescale)
                    {
                        v.X *= ci;
                        v.Y *= ci;
                    }
                }
                break;
                }

                v.X += (origin.X / 16.0f);
                v.Y += (origin.Y / 16.0f);
                v.Z += (origin.Z / 16.0f);
            }

            return(v);
        }
Exemplo n.º 33
0
        /// <summary>
        ///     Provides the possible references for this expression (only available during semantic analysis)
        /// </summary>
        /// <param name="instance">the instance on which this element should be found.</param>
        /// <param name="expectation">the expectation on the element found</param>
        /// <param name="last">indicates that this is the last element in a dereference chain</param>
        /// <returns></returns>
        public override ReturnValue GetReferences(INamable instance, BaseFilter expectation, bool last)
        {
            ReturnValue retVal = Arguments[0].GetReferences(instance, AllMatches.INSTANCE, false);

            if (retVal.IsEmpty)
            {
                retVal = Arguments[0].GetReferenceTypes(instance, AllMatches.INSTANCE, false);
            }

            // When variables & parameters are found, only consider the first one
            // which is the one that is closer in the tree
            {
                ReturnValue tmp2 = retVal;
                retVal = new ReturnValue();

                ReturnValueElement variable = null;
                foreach (ReturnValueElement elem in tmp2.Values)
                {
                    if (elem.Value is Parameter || elem.Value is IVariable)
                    {
                        if (variable == null)
                        {
                            variable = elem;
                            retVal.Values.Add(elem);
                        }
                    }
                    else
                    {
                        retVal.Values.Add(elem);
                    }
                }
            }

            if (retVal.IsUnique)
            {
                Arguments[0].Ref = retVal.Values[0].Value;
            }

            if (!retVal.IsEmpty)
            {
                for (int i = 1; i < Arguments.Count; i++)
                {
                    ReturnValue tmp2 = retVal;
                    retVal = new ReturnValue(Arguments[i]);

                    foreach (ReturnValueElement elem in tmp2.Values)
                    {
                        bool         removed = false;
                        ModelElement model   = elem.Value as ModelElement;
                        if (model != null)
                        {
                            removed = model.IsRemoved;
                        }

                        if (!removed)
                        {
                            retVal.Merge(elem,
                                         Arguments[i].GetReferences(elem.Value, AllMatches.INSTANCE, i == (Arguments.Count - 1)));
                        }
                    }

                    if (retVal.IsEmpty)
                    {
                        AddError("Cannot find " + Arguments[i] + " in " + Arguments[i - 1], RuleChecksEnum.SemanticAnalysisError);
                    }

                    if (retVal.IsUnique)
                    {
                        Arguments[i].Ref = retVal.Values[0].Value;
                    }
                }
            }
            else
            {
                AddError("Cannot evaluate " + Arguments[0], RuleChecksEnum.SemanticAnalysisError);
            }

            retVal.Filter(expectation);

            return(retVal);
        }
Exemplo n.º 34
0
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="baseLocation"></param>
 public RelocateTree(ModelElement baseLocation)
 {
     BaseLocation = baseLocation;
 }
Exemplo n.º 35
0
 private Moniker CustomCreateMonikerInstance(SerializationContext context, XmlReader reader, ModelElement sourceRolePlayer, Guid relDomainClassId, Partition partition)
 {
     return(DefaultCreateMonikerInstance(context, reader, sourceRolePlayer, relDomainClassId, partition));
 }
Exemplo n.º 36
0
 private void CustomWrite(SerializationContext context, ModelElement element, XmlWriter writer, RootElementSettings rootElementSettings)
 {
     DefaultWrite(context, element, writer, rootElementSettings);
 }
Exemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventSettingsTypeDescriptor"/> class.
 /// </summary>
 public EventSettingsTypeDescriptor(ModelElement modelElement)
     : base(modelElement)
 {
 }
Exemplo n.º 38
0
 /// <summary>
 /// Overridables for the derived class to provide a custom type descriptor.
 /// </summary>
 /// <param name="parent">Parent custom type descriptor.</param>
 /// <param name="element">Element to be described.</param>
 protected override ElementTypeDescriptor CreateTypeDescriptor(ICustomTypeDescriptor parent, ModelElement element)
 {
     return(new EventSettingsTypeDescriptor(element));
 }
Exemplo n.º 39
0
        private static string GetDisplayPropertyFromModelClassForAssociationsCompartment(ModelElement element)
        {
            Association association = (Association)element;
            ModelClass  target      = association.Target;

            // ReSharper disable once ConvertIfStatementToReturnStatement
            if (!string.IsNullOrEmpty(association.TargetPropertyName))
            {
                return($"{association.TargetPropertyName} : {target.Name}");
            }

            return(target.Name);
        }
Exemplo n.º 40
0
        /// <summary>
        /// Creates the link.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        private static ElementLink CreateLink(ModelElement source, ModelElement target)
        {
            s_initialContract = null;

            //     Assembly    ->      Assembly                AssemblyReferencesAssemblies
            //     Assembly    ->      Model                   DotnetPublication
            //     Assembly    ->      ExternalPort      ExternalServiceReference
            if (source is DotNetAssembly || target is DotNetAssembly)
            {
                if (target is DotNetAssembly && !(source is DotNetAssembly))
                {
                    Utils.Swap <ModelElement>(ref source, ref target);
                }
                return(CreateLinkFromDotNetAssembly(source, target));
            }

            // Important - Comme ExternalServiceContract hérite de ExternalPublicPort, il faut faire ce test avant
            if (source is ExternalServiceContract || target is ExternalServiceContract)
            {
                // Contract tjs en temps que source
                if (!(source is ExternalServiceContract))
                {
                    Utils.Swap <ModelElement>(ref source, ref target);
                }
                ServiceContract contract = null;
                if (target is InterfaceLayer)
                {
                    contract = CreateContract(((ExternalServiceContract)source).ReferencedServiceContract, (InterfaceLayer)target);
                    target   = GetDownestLayer((InterfaceLayer)target, null);
                }
                if (target is UIWorkflowLayer)
                {
                    Scenario scenario = CreateScenario(((ExternalServiceContract)source).ReferencedServiceContract, (UIWorkflowLayer)target);
                    return(new ClassUsesOperations(scenario, (ExternalServiceContract)source));
                }

                if (target is Layer)
                {
                    ClassImplementation clazz = CreateClass(((ExternalServiceContract)source).ReferencedServiceContract, (Layer)target);
                    if (contract != null)
                    {
                        clazz.Contract = contract;
                    }
                    target = clazz;
                }

                if (target is ClassImplementation || target is Scenario)
                {
                    return(new ClassUsesOperations((TypeWithOperations)target, (ExternalServiceContract)source));
                }
            }

            if (source is ExternalPublicPort || target is ExternalPublicPort)
            {
                // Contract tjs en temps que source
                if (!(source is ExternalPublicPort))
                {
                    Utils.Swap <ModelElement>(ref source, ref target);
                }

                if (target is AbstractLayer)
                {
                    return(new ExternalServiceReference((AbstractLayer)target, (ExternalPublicPort)source));
                }
            }

            if (source is ServiceContract || target is ServiceContract)
            {
                if (!(source is ServiceContract))
                {
                    Utils.Swap <ModelElement>(ref source, ref target);
                }

                s_initialContract = source as ServiceContract;
                if (target is ClassImplementation)
                {
                    return(CreateLink(s_initialContract, (ClassImplementation)target));
                }

                if (target is Scenario)
                {
                    return(new ScenarioUsesContracts((Scenario)target, (ServiceContract)source));
                }

                if (target is SoftwareLayer)
                {
                    return(CreateLink(s_initialContract, (SoftwareLayer)target));
                }
            }

            if (source is ClassImplementation)
            {
                if (target is ClassImplementation)
                {
                    return(CreateLink((ClassImplementation)source, (ClassImplementation)target));
                }
                if (target is InterfaceLayer)
                {
                    return(CreateLink((ClassImplementation)source, (SoftwareLayer)target));
                }
                if (target is ExternalServiceContract)
                {
                    return(new ClassUsesOperations((ClassImplementation)source, (ExternalServiceContract)target));
                }
            }

            return(null);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Finds out if a relationship can be assigned automatically between the given source
 /// and target element.
 /// </summary>
 /// <remarks>
 /// This method is required becase reference relationship do not need to be serialized
 /// with an id. But shapes still need to be created for them if a visual information
 /// is provided in the diagrams model.
 /// </remarks>
 protected virtual ModelElement CanAssignRelationship(ModelElement source, ModelElement target)
 {
     return(null);
 }
Exemplo n.º 42
0
        protected override void VisitDerefExpression(DerefExpression derefExpression)
        {
            ModelElement backup = BaseLocation;

            foreach (Expression expression in derefExpression.Arguments)
            {
                if (expression != null)
                {
                    ModelElement model = expression.Ref as ModelElement;

                    if (model is Structure)
                    {
                        if (expression is Call || expression is ListExpression)
                        {
                            // Because this is the return value instead of the target element
                            model = null;
                        }
                        else
                        {
                            UnaryExpression unaryExpression = expression as UnaryExpression;
                            if (unaryExpression != null)
                            {
                                if (unaryExpression.Term != null &&
                                    unaryExpression.Term.Designator != null &&
                                    unaryExpression.Term.Designator.IsPredefined())
                                {
                                    // No need to refactor a predefined item
                                    model = null;
                                }
                                else if (unaryExpression.Expression != null)
                                {
                                    // No need to change the enclosing parenthesed expression
                                    // Let's rely on the recursive call
                                    model = null;
                                }
                            }
                        }
                    }

                    if (model != null)
                    {
                        string referenceName = model.ReferenceName(BaseLocation);
                        ReplaceText(referenceName, expression.Start, expression.End);
                        break;
                    }
                    else
                    {
                        BaseLocation = backup;
                        VisitExpression(expression);
                        BaseLocation = expression.GetExpressionType();
                    }

                    if (expression.Ref != null)
                    {
                        ITypedElement typedElement = expression.Ref as ITypedElement;
                        if (typedElement != null && typedElement.Type != null)
                        {
                            BaseLocation = typedElement.Type;
                        }
                        else
                        {
                            BaseLocation = expression.Ref as ModelElement;
                        }
                    }
                }
            }

            BaseLocation = backup;
        }
Exemplo n.º 43
0
 private void CustomWritePropertiesAsAttributes(SerializationContext context, ModelElement element, XmlWriter writer)
 {
     DefaultWritePropertiesAsAttributes(context, element, writer);
 }
Exemplo n.º 44
0
        private void UpdateVerbalization()
        {
            if (CurrentORMSelectionContainer == null)
            {
                return;
            }
            if (myStringWriter != null)
            {
                myStringWriter.GetStringBuilder().Length = 0;

                ICollection selectedObjects = base.GetSelectedComponents();
                IDictionary <Type, IVerbalizationSets>            snippetsDictionary = null;
                IDictionary <string, object>                      options            = null;
                IVerbalizationSets <CoreVerbalizationSnippetType> snippets           = null;
                IExtensionVerbalizerService extensionVerbalizer = null;
                VerbalizationCallbackWriter callbackWriter      = null;
                bool showNegative     = ORMDesignerPackage.VerbalizationWindowSettings.ShowNegativeVerbalizations;
                bool firstCallPending = true;
                Dictionary <IVerbalize, IVerbalize> alreadyVerbalized = myAlreadyVerbalized;
                if (alreadyVerbalized == null)
                {
                    alreadyVerbalized   = new Dictionary <IVerbalize, IVerbalize>();
                    myAlreadyVerbalized = alreadyVerbalized;
                }
                else
                {
                    alreadyVerbalized.Clear();
                }
                Dictionary <object, object> locallyVerbalized = myLocallyVerbalized;
                if (locallyVerbalized == null)
                {
                    locallyVerbalized   = new Dictionary <object, object>();
                    myLocallyVerbalized = locallyVerbalized;
                }
                if (selectedObjects != null)
                {
                    foreach (object melIter in selectedObjects)
                    {
                        ModelElement        mel = melIter as ModelElement;
                        PresentationElement pel = mel as PresentationElement;
                        if (pel != null)
                        {
                            IRedirectVerbalization shapeRedirect = pel as IRedirectVerbalization;
                            if (null == (shapeRedirect = pel as IRedirectVerbalization) ||
                                null == (mel = shapeRedirect.SurrogateVerbalizer as ModelElement))
                            {
                                mel = pel.ModelElement;
                            }
                        }
                        if (mel != null && !mel.IsDeleted)
                        {
                            if (snippetsDictionary == null)
                            {
                                Store store = Utility.ValidateStore(mel.Store);
                                if (store == null)
                                {
                                    break;
                                }
                                IORMToolServices toolServices = (IORMToolServices)store;
                                extensionVerbalizer = toolServices.ExtensionVerbalizerService;
                                options             = toolServices.VerbalizationOptions;
                                snippetsDictionary  = toolServices.GetVerbalizationSnippetsDictionary(ORMCoreDomainModel.VerbalizationTargetName);
                                snippets            = (IVerbalizationSets <CoreVerbalizationSnippetType>)snippetsDictionary[typeof(CoreVerbalizationSnippetType)];
                                callbackWriter      = new VerbalizationCallbackWriter(snippets, myStringWriter, GetDocumentHeaderReplacementFields(mel, snippets));
                            }
                            locallyVerbalized.Clear();
                            VerbalizationHelper.VerbalizeElement(
                                mel,
                                snippetsDictionary,
                                extensionVerbalizer,
                                options,
                                ORMCoreDomainModel.VerbalizationTargetName,
                                alreadyVerbalized,
                                locallyVerbalized,
                                (showNegative ? VerbalizationSign.Negative : VerbalizationSign.Positive) | VerbalizationSign.AttemptOppositeSign,
                                callbackWriter,
                                true,
                                ref firstCallPending);
                        }
                    }
                }
                if (!firstCallPending)
                {
                    // Write footer
                    callbackWriter.WriteDocumentFooter();
                    // Clear cache
                    alreadyVerbalized.Clear();
                }
                else
                {
                    // Nothing happened, put in text for nothing happened
                }
                WebBrowser browser = myWebBrowser;
                if (browser != null)
                {
                    browser.DocumentText = myStringWriter.ToString();
                }
            }
        }
Exemplo n.º 45
0
 /// <summary>
 /// Adds the extension <see cref="ModelElement"/> specified by <paramref name="extensionElement"/> to the
 /// <see cref="IORMExtendableElement"/> specified by <paramref name="extendedElement"/>.
 /// </summary>
 public static void AddExtensionElement(IORMExtendableElement extendedElement, ModelElement extensionElement)
 {
     if (extendedElement == null)
     {
         throw new ArgumentNullException("extendedElement");
     }
     if (extensionElement == null)
     {
         throw new ArgumentNullException("extensionElement");
     }
     extendedElement.ExtensionCollection.Add(extensionElement);
 }
Exemplo n.º 46
0
 private void CustomReadPropertiesFromAttributes(SerializationContext context, ModelElement element, XmlReader reader)
 {
     DefaultReadPropertiesFromAttributes(context, element, reader);
 }
Exemplo n.º 47
0
 private void CustomWriteMoniker(SerializationContext context, ModelElement element, XmlWriter writer, ModelElement sourceRolePlayer, DomainRelationshipXmlSerializer relSerializer)
 {
     DefaultWriteMoniker(context, element, writer, sourceRolePlayer, relSerializer);
 }
Exemplo n.º 48
0
        // the following is based on code at https://stackoverflow.com/questions/44876242/center-a-dsl-shape-on-diagram-screen

        public static bool LocateInDiagram(this ModelElement element, bool ensureVisible)
        {
            DiagramView diagramView = element.GetActiveDiagramView();

            return(diagramView != null && diagramView.SelectModelElement(element, ensureVisible));
        }
Exemplo n.º 49
0
 private void CustomReadElements(SerializationContext context, ModelElement element, XmlReader reader)
 {
     DefaultReadElements(context, element, reader);
 }
Exemplo n.º 50
0
 /// <summary>
 /// Perform additional checks based on the parameter types
 /// </summary>
 /// <param name="root">The element on which the errors should be reported</param>
 /// <param name="context">The evaluation context</param>
 /// <param name="actualParameters">The parameters applied to this function call</param>
 public override void additionalChecks(ModelElement root, Interpreter.InterpretationContext context, Dictionary <string, Interpreter.Expression> actualParameters)
 {
     CheckFunctionalParameter(root, context, actualParameters[DefaultFunction.Name], 2);
     CheckFunctionalParameter(root, context, actualParameters[OverrideFunction.Name], 2);
 }
Exemplo n.º 51
0
        public static bool SelectModelElement(this DiagramView diagramView, ModelElement modelElement, bool ensureVisible)
        {
            // Get the shape element that corresponds to the model element

            ShapeElement shapeElement = PresentationViewsSubject.GetPresentation(modelElement).OfType <ShapeElement>().FirstOrDefault();

            if (shapeElement != null)
            {
                // Make sure the shape element is visible (because connectors can be hidden)
                if (!shapeElement.IsVisible)
                {
                    shapeElement.Show();
                }

                // Create a diagram item for this shape element and select it
                diagramView.Selection.Set(new DiagramItem(shapeElement));

                if (ensureVisible)
                {
                    diagramView.Selection.EnsureVisible(DiagramClientView.EnsureVisiblePreferences.ScrollIntoViewCenter);
                    diagramView.ZoomAtViewCenter(1);
                }

                return(true);
            }

            // If the model element does not have a shape, try to cast it IModelElementCompartmented

            if (modelElement is IModelElementInCompartment compartmentedModelElement)
            {
                // Get the parent
                IModelElementWithCompartments parentModelElement = compartmentedModelElement.ParentModelElement;

                if (parentModelElement != null)
                {
                    // Get the compartment that stores the model element
                    CompartmentShape       parentShapeElement = PresentationViewsSubject.GetPresentation((ModelElement)parentModelElement).OfType <CompartmentShape>().FirstOrDefault();
                    ElementListCompartment compartment        = parentShapeElement.GetCompartment(compartmentedModelElement.CompartmentName);

                    if (compartment != null)
                    {
                        if (!compartment.IsExpanded)
                        {
                            using (Transaction trans = modelElement.Store.TransactionManager.BeginTransaction("IsExpanded"))
                            {
                                compartment.IsExpanded = true;
                                trans.Commit();
                            }
                        }

                        // Find the model element in the compartment

                        int index = compartment.Items.IndexOf(modelElement);

                        if (index >= 0)
                        {
                            // Create a diagram item and select it
                            diagramView.Selection.Set(new DiagramItem(compartment, compartment.ListField, new ListItemSubField(index)));

                            if (ensureVisible)
                            {
                                diagramView.Selection.EnsureVisible(DiagramClientView.EnsureVisiblePreferences.ScrollIntoViewCenter);
                                diagramView.ZoomAtViewCenter(1);
                            }
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Exemplo n.º 52
0
 private string CustomGetMonikerQualifier(DomainXmlSerializerDirectory directory, ModelElement element)
 {
     return(DefaultGetMonikerQualifier(directory, element));
 }
Exemplo n.º 53
0
        public static DiagramView GetActiveDiagramView(this ModelElement element)
        {
            ShapeElement shapeElement = element.GetShapeElement();

            return(shapeElement?.GetActiveDiagramView());
        }
Exemplo n.º 54
0
 private string CustomCalculateQualifiedName(DomainXmlSerializerDirectory directory, ModelElement element)
 {
     return(DefaultCalculateQualifiedName(directory, element));
 }
Exemplo n.º 55
0
        private BlockShaderVertex[] ProcessVertices(BlockShaderVertex[] vertices,
                                                    BlockStateModel bsModel,
                                                    ModelElement element,
                                                    BlockTextureData?uvMap,
                                                    BlockFace blockFace,
                                                    ModelElementFace face)
        {
            for (int i = 0; i < vertices.Length; i++)
            {
                var v = vertices[i];

                v.Position /= 16f;
                v.Position  = FixRotation(v.Position, element);

                if (bsModel.X > 0)
                {
                    var rotX = bsModel.X * (MathHelper.Pi / 180f);
                    var c    = MathF.Cos(rotX);
                    var s    = MathF.Sin(rotX);
                    var z    = v.Position.Z - 0.5f;
                    var y    = v.Position.Y - 0.5f;

                    v.Position.Z = 0.5f + (z * c - y * s);
                    v.Position.Y = 0.5f + (y * c + z * s);
                }

                if (bsModel.Y > 0)
                {
                    var rotY = bsModel.Y * (MathHelper.Pi / 180f);
                    var c    = MathF.Cos(rotY);
                    var s    = MathF.Sin(rotY);
                    var x    = v.Position.X - 0.5f;
                    var z    = v.Position.Z - 0.5f;

                    v.Position.X = 0.5f + (x * c - z * s);
                    v.Position.Z = 0.5f + (z * c + x * s);
                }

                if (uvMap.HasValue)
                {
                    var tw = uvMap.Value.TextureInfo.Width;
                    var th = uvMap.Value.TextureInfo.Height;

                    var rot = face.Rotation;

                    if (rot > 0)
                    {
                        var rotY = rot * (MathHelper.Pi / 180f);
                        var c    = MathF.Cos(rotY);
                        var s    = MathF.Sin(rotY);
                        var x    = v.TexCoords.X - 8f * tw;
                        var y    = v.TexCoords.Y - 8f * th;

                        v.TexCoords.X = 8f * tw + (x * c - y * s);
                        v.TexCoords.Y = 8f * th + (y * c + x * s);
                    }

                    if (bsModel.Uvlock)
                    {
                        if (bsModel.Y > 0 && (blockFace == BlockFace.Up || blockFace == BlockFace.Down))
                        {
                            var rotY = bsModel.Y * (MathHelper.Pi / 180f);
                            var c    = MathF.Cos(rotY);
                            var s    = MathF.Sin(rotY);
                            var x    = v.TexCoords.X - 8f * tw;
                            var y    = v.TexCoords.Y - 8f * th;

                            v.TexCoords.X = 8f * tw + (x * c - y * s);
                            v.TexCoords.Y = 8f * th + (y * c + x * s);
                        }

                        if (bsModel.X > 0 && (blockFace != BlockFace.Up && blockFace != BlockFace.Down))
                        {
                            var rotX = bsModel.X * (MathHelper.Pi / 180f);
                            var c    = MathF.Cos(rotX);
                            var s    = MathF.Sin(rotX);
                            var x    = v.TexCoords.X - 8f * tw;
                            var y    = v.TexCoords.Y - 8f * th;

                            v.TexCoords.X = 8f * tw + (x * c - y * s);
                            v.TexCoords.Y = 8f * th + (y * c + x * s);
                        }
                    }

                    v.TexCoords += uvMap.Value.TextureInfo.Position;
                    v.TexCoords *= (Vector2.One / uvMap.Value.TextureInfo.AtlasSize);
                }

                v.Face      = blockFace;
                vertices[i] = v;
            }

            return(vertices);
        }
Exemplo n.º 56
0
 private void CustomWriteElements(SerializationContext context, ModelElement element, XmlWriter writer)
 {
     DefaultWriteElements(context, element, writer);
 }
Exemplo n.º 57
0
        public override void OnDragDrop(DiagramDragEventArgs diagramDragEventArgs)
        {
            // came from model explorer?
            ModelElement element = (diagramDragEventArgs.Data.GetData("Sawczyn.EFDesigner.EFModel.ModelClass") as ModelElement)
                                   ?? (diagramDragEventArgs.Data.GetData("Sawczyn.EFDesigner.EFModel.ModelEnum") as ModelElement);

            if (element != null)
            {
                ShapeElement newShape = AddExistingModelElement(this, element);

                if (newShape != null)
                {
                    using (Transaction t = element.Store.TransactionManager.BeginTransaction("Moving pasted shapes"))
                    {
                        if (newShape is NodeShape nodeShape)
                        {
                            nodeShape.Location = diagramDragEventArgs.MousePosition;
                        }

                        t.Commit();
                    }
                }
            }
            else
            {
                if (IsDroppingExternal)
                {
                    DisableDiagramRules();
                    Cursor prev = Cursor.Current;
                    Cursor.Current = Cursors.WaitCursor;

                    List <ModelElement> newElements = null;

                    try
                    {
                        try
                        {
                            // add to the model
                            string[] filenames;

                            if (diagramDragEventArgs.Data.GetData("Text") is string concatenatedFilenames)
                            {
                                filenames = concatenatedFilenames.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            }
                            else if (diagramDragEventArgs.Data.GetData("FileDrop") is string[] droppedFilenames)
                            {
                                filenames = droppedFilenames;
                            }
                            else
                            {
                                ErrorDisplay.Show(Store, "Unexpected error dropping files. Please create an issue in Github.");

                                return;
                            }

                            string[] existingFiles = filenames.Where(File.Exists).ToArray();
                            newElements = FileDropHelper.HandleMultiDrop(Store, existingFiles).ToList();

                            string[] missingFiles = filenames.Except(existingFiles).ToArray();

                            if (missingFiles.Any())
                            {
                                if (missingFiles.Length > 1)
                                {
                                    missingFiles[missingFiles.Length - 1] = "and " + missingFiles[missingFiles.Length - 1];
                                }

                                ErrorDisplay.Show(Store, $"Can't find files {string.Join(", ", missingFiles)}");
                            }
                        }
                        finally
                        {
                            if (newElements?.Count > 0)
                            {
                                string message = $"Created {newElements.Count} new elements that have been added to the Model Explorer. "
                                                 + $"Do you want these added to the current diagram as well? It could take a while.";

                                if (BooleanQuestionDisplay.Show(Store, message) == true)
                                {
                                    AddElementsToActiveDiagram(newElements);
                                }
                            }

                            //string message = $"{newElements.Count} have been added to the Model Explorer. You can add them to this or any other diagram by dragging them from the Model Explorer and dropping them onto the design surface.";
                            //MessageDisplay.Show(message);

                            IsDroppingExternal = false;
                        }
                    }
                    finally
                    {
                        EnableDiagramRules();
                        Cursor.Current = prev;

                        MessageDisplay.Show(newElements == null || !newElements.Any()
                                         ? "Import dropped files: no new elements added"
                                         : BuildMessage(newElements));

                        StatusDisplay.Show("Ready");
                    }
                }
                else
                {
                    try
                    {
                        base.OnDragDrop(diagramDragEventArgs);
                    }
                    catch (ArgumentException)
                    {
                        // ignore. byproduct of multiple diagrams
                    }
                }
            }

            StatusDisplay.Show("Ready");
            Invalidate();

            string BuildMessage(List <ModelElement> newElements)
            {
                int           classCount    = newElements.OfType <ModelClass>().Count();
                int           propertyCount = newElements.OfType <ModelClass>().SelectMany(c => c.Attributes).Count();
                int           enumCount     = newElements.OfType <ModelEnum>().Count();
                List <string> messageParts  = new List <string>();

                if (classCount > 0)
                {
                    messageParts.Add($"{classCount} classes");
                }

                if (propertyCount > 0)
                {
                    messageParts.Add($"{propertyCount} properties");
                }

                if (enumCount > 0)
                {
                    messageParts.Add($"{enumCount} enums");
                }

                return($"Import dropped files: added {(messageParts.Count > 1 ? string.Join(", ", messageParts.Take(messageParts.Count - 1)) + " and " + messageParts.Last() : messageParts.First())}");
            }
        }
Exemplo n.º 58
0
        /// <summary>
        /// This method deserializes all properties that are serialized as XML attributes.
        /// </summary>
        /// <remarks>
        /// Because this method only handles properties serialized as XML attributes, the passed-in reader shouldn't be moved inside this method.
        /// The caller will guarantee that the reader is positioned on the open XML tag of the current element being deserialized.
        /// </remarks>
        /// <param name="serializationContext">Serialization context.</param>
        /// <param name="element">In-memory LinkShape instance that will get the deserialized data.</param>
        /// <param name="reader">XmlReader to read serialized data from.</param>
        protected override void ReadPropertiesFromAttributes(SerializationContext serializationContext, ModelElement element, System.Xml.XmlReader reader)
        {
            LinkShape instanceOfLinkShape = element as LinkShape;

            global::System.Diagnostics.Debug.Assert(instanceOfLinkShape != null, "Expecting an instance of LinkShape");

            // DummyProperty
            if (!serializationContext.Result.Failed)
            {
                string attribDummyProperty = DiagramsDSLSerializationHelper.Instance.ReadAttribute(serializationContext, element, reader, "dummyProperty");
                if (attribDummyProperty != null)
                {
                    global::System.String valueOfDummyProperty;
                    if (SerializationUtilities.TryGetValue <global::System.String>(serializationContext, attribDummyProperty, out valueOfDummyProperty))
                    {
                        instanceOfLinkShape.DummyProperty = valueOfDummyProperty;
                    }
                    else
                    {   // Invalid property value, ignored.
                        TestDslDefinitionSerializationBehaviorSerializationMessages.IgnoredPropertyValue(serializationContext, reader, "dummyProperty", typeof(global::System.String), attribDummyProperty);
                    }
                }
            }
            // RoutingMode
            if (!serializationContext.Result.Failed)
            {
                string attribRoutingMode = DiagramsDSLSerializationHelper.Instance.ReadAttribute(serializationContext, element, reader, "routingMode");
                if (attribRoutingMode != null)
                {
                    RoutingMode valueOfRoutingMode;
                    if (SerializationUtilities.TryGetValue <RoutingMode>(serializationContext, attribRoutingMode, out valueOfRoutingMode))
                    {
                        instanceOfLinkShape.RoutingMode = valueOfRoutingMode;
                    }
                    else
                    {   // Invalid property value, ignored.
                        TestDslDefinitionSerializationBehaviorSerializationMessages.IgnoredPropertyValue(serializationContext, reader, "routingMode", typeof(RoutingMode), attribRoutingMode);
                    }
                }
            }
            //base.ReadPropertiesFromAttributes(serializationContext, element, reader);
        }
Exemplo n.º 59
0
        private static ElementLink ConnectSourceToTarget(ModelElement source, ModelElement target)
        {
            if (source is VDEventBase && target is VDActionBase)
            {
                VDEventBase  evt = source as VDEventBase;
                VDActionBase act = target as VDActionBase;
                evt.TargetComponents.Add(act);
                return(R_Event2Component.GetLink(evt, act));
            }
            else if (source is VDActionJoint && target is VDViewComponent)
            {
                VDActionJoint   joint = source as VDActionJoint;
                VDViewComponent tgt   = target as VDViewComponent;
                joint.TargetComponents.Add(tgt);
                return(R_ActionJoint2Component.GetLink(joint, tgt));
            }
            else if (source is VDViewComponent && target is VDActionBase)
            {
                VDViewComponent        srcComponent = source as VDViewComponent;
                VDActionBase           targetAction = target as VDActionBase;
                Component2ActionDialog dlg          = new Component2ActionDialog();
                dlg.SetComponentAndAction(srcComponent, targetAction);
                dlg.ShowDialog();

                if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    IEventInfo  evtInfo  = dlg.SelectedEvent;
                    VDEventBase newEvent = evtInfo.CreateEvent(srcComponent);
                    newEvent.Widget = srcComponent;
                    newEvent.TargetComponents.Add(targetAction);
                    return(R_Event2Component.GetLink(newEvent, targetAction));
                }
            }
            else if (source is VDEventBase && target is VDViewComponent) // create new action
            {
                VDEventBase               sourceEvent     = source as VDEventBase;
                VDViewComponent           targetComponent = target as VDViewComponent;
                Component2ComponentDialog dlg             = new Component2ComponentDialog(false);
                dlg.NewAction.SetSourceEvent(sourceEvent).SetTarget(targetComponent);
                dlg.ShowDialog();

                if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    IActionInfo  actInfo = dlg.NewAction.SelectedAction;
                    VDActionBase newAct  = actInfo.CreateAction(sourceEvent.Partition);
                    VDWidget.GetCommonParent(sourceEvent.Widget, targetComponent).Children.Add(newAct);
                    //sourceEvent.Widget.Parent.Children.Add(newAct);
                    sourceEvent.TargetComponents.Add(newAct);

                    IActionJointInfo jointInfo = dlg.NewAction.SelectedJoint;
                    VDActionJoint    newJoint  = jointInfo.CreateActionJoint(newAct, targetComponent);
                    newJoint.Widget = newAct;
                    newJoint.TargetComponents.Add(targetComponent);
                    return(R_ActionJoint2Component.GetLink(newJoint, targetComponent));
                }
            }
            else if (source is VDViewComponent && target is VDViewComponent) // create new action or target
            {
                VDViewComponent           srcComponent = source as VDViewComponent;
                VDViewComponent           tgtComponent = target as VDViewComponent;
                Component2ComponentDialog dlg          = new Component2ComponentDialog();
                dlg.NewAction.SetSource(srcComponent).SetTarget(tgtComponent);
                dlg.NewTarget.SetSource(srcComponent).SetTarget(tgtComponent);
                dlg.ShowDialog();

                if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    if (dlg.IfCreateNewAction)
                    {
                        IEventInfo  evtInfo  = dlg.NewAction.SelectedEvent;
                        VDEventBase newEvent = evtInfo.CreateEvent(srcComponent);
                        newEvent.Widget = srcComponent;

                        IActionInfo  actInfo = dlg.NewAction.SelectedAction;
                        VDActionBase newAct  = actInfo.CreateAction(srcComponent.Partition);
                        VDWidget.GetCommonParent(srcComponent, tgtComponent).Children.Add(newAct);
                        //srcComponent.Parent.Children.Add(newAct);
                        newEvent.TargetComponents.Add(newAct);

                        IActionJointInfo jointInfo = dlg.NewAction.SelectedJoint;
                        VDActionJoint    newJoint  = jointInfo.CreateActionJoint(newAct, tgtComponent);
                        newJoint.Widget = newAct;
                        newJoint.TargetComponents.Add(tgtComponent);
                        return(R_ActionJoint2Component.GetLink(newJoint, tgtComponent));
                    }
                    else
                    {
                        IActionJointInfo jointInfo = dlg.NewTarget.SelectedJoint;
                        VDActionJoint    joint     = jointInfo.CreateActionJoint(srcComponent, tgtComponent);
                        joint.Widget = srcComponent;
                        joint.TargetComponents.Add(tgtComponent);
                        return(R_ActionJoint2Component.GetLink(joint, tgtComponent));
                    }
                }
            }

            return(null);
        }
Exemplo n.º 60
0
 private static string GetDisplayPropertyFromModelClassForAttributesCompartment(ModelElement element)
 {
     return(((ModelAttribute)element).ToDisplayString());
 }