Beispiel #1
0
 /// <summary>
 /// Primary thread of execution
 /// All logic starts here!
 /// </summary>
 public Core()
 {
     userModel = ModelFactory.UserModel;
     setModel = ModelFactory.ProblemSetModel;
     problemModel = ModelFactory.ProblemModel;
     classModel = ModelFactory.ClassModel;
     progressModel = ModelFactory.ProgressModel;
 }
        public void UpdateClassTest()
        {
            const string className = "ChangedClassName";
            var model = new ClassModel() { Id = 2, Name = className};
            var result = Update(model, 2);

            Assert.IsTrue(result.Result);

            var entity = _repository.GetById(2);


            Assert.IsNotNull(entity);
            Assert.AreEqual(entity.Result.Name, className);
            Assert.AreEqual(entity.Result.Id, 2);
        }
        private TypeModel CreateTypeModel(Uri source, XmlSchemaComplexType complexType, NamespaceModel namespaceModel, XmlQualifiedName qualifiedName, List <DocumentationModel> docs)
        {
            var name = _configuration.NamingProvider.ComplexTypeNameFromQualifiedName(qualifiedName);

            if (namespaceModel != null)
            {
                name = namespaceModel.GetUniqueTypeName(name);
            }

            var classModel = new ClassModel(_configuration)
            {
                Name           = name,
                Namespace      = namespaceModel,
                XmlSchemaName  = qualifiedName,
                XmlSchemaType  = complexType,
                IsAbstract     = complexType.IsAbstract,
                IsAnonymous    = string.IsNullOrEmpty(complexType.QualifiedName.Name),
                IsMixed        = complexType.IsMixed,
                IsSubstitution = complexType.Parent is XmlSchemaElement && !((XmlSchemaElement)complexType.Parent).SubstitutionGroup.IsEmpty
            };

            classModel.Documentation.AddRange(docs);

            if (namespaceModel != null)
            {
                namespaceModel.Types[classModel.Name] = classModel;
            }

            if (!qualifiedName.IsEmpty)
            {
                var key = BuildKey(complexType, qualifiedName);
                Types[key] = classModel;
            }

            if (complexType.BaseXmlSchemaType != null && complexType.BaseXmlSchemaType.QualifiedName != AnyType)
            {
                var baseModel = CreateTypeModel(source, complexType.BaseXmlSchemaType, complexType.BaseXmlSchemaType.QualifiedName);
                classModel.BaseClass = baseModel;
                if (baseModel is ClassModel baseClassModel)
                {
                    baseClassModel.DerivedTypes.Add(classModel);
                }
            }

            XmlSchemaParticle particle = null;

            if (classModel.BaseClass != null)
            {
                if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
                {
                    particle = complexContent.Particle;
                }

                // If it's a restriction, do not duplicate elements on the derived class, they're already in the base class.
                // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
            }
            else
            {
                particle = complexType.Particle ?? complexType.ContentTypeParticle;
            }

            var items = GetElements(particle, complexType).ToList();

            if (_configuration.GenerateInterfaces)
            {
                var interfaces = items.Select(i => i.XmlParticle).OfType <XmlSchemaGroupRef>()
                                 .Select(i => (InterfaceModel)CreateTypeModel(CodeUtilities.CreateUri(i.SourceUri), Groups[i.RefName], i.RefName)).ToList();

                classModel.AddInterfaces(interfaces);
            }

            var properties = CreatePropertiesForElements(source, classModel, particle, items);

            classModel.Properties.AddRange(properties);

            XmlSchemaObjectCollection attributes = null;

            if (classModel.BaseClass != null)
            {
                if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
                {
                    attributes = complexContent.Attributes;
                }
                else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension simpleContent)
                {
                    attributes = simpleContent.Attributes;
                }

                // If it's a restriction, do not duplicate attributes on the derived class, they're already in the base class.
                // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
            }
            else
            {
                attributes = complexType.Attributes;
            }

            if (attributes != null)
            {
                var attributeProperties = CreatePropertiesForAttributes(source, classModel, attributes.Cast <XmlSchemaObject>());
                classModel.Properties.AddRange(attributeProperties);

                if (_configuration.GenerateInterfaces)
                {
                    var attributeInterfaces = attributes.OfType <XmlSchemaAttributeGroupRef>()
                                              .Select(i => (InterfaceModel)CreateTypeModel(CodeUtilities.CreateUri(i.SourceUri), AttributeGroups[i.RefName], i.RefName));
                    classModel.AddInterfaces(attributeInterfaces);
                }
            }

            if (complexType.AnyAttribute != null)
            {
                var property = new PropertyModel(_configuration)
                {
                    OwningType = classModel,
                    Name       = "AnyAttribute",
                    Type       = new SimpleModel(_configuration)
                    {
                        ValueType = typeof(XmlAttribute), UseDataTypeAttribute = false
                    },
                    IsAttribute  = true,
                    IsCollection = true,
                    IsAny        = true
                };

                var attributeDocs = GetDocumentation(complexType.AnyAttribute);
                property.Documentation.AddRange(attributeDocs);

                classModel.Properties.Add(property);
            }

            return(classModel);
        }
Beispiel #4
0
 /// <exception cref="ArgumentException">
 /// The <paramref name="model"/> is invalid.
 /// </exception>
 protected abstract ProjectGenerator CreateProjectGenerator(ClassModel model);
Beispiel #5
0
        /// <summary>
        /// Generates scalar function model from schema data.
        /// </summary>
        /// <param name="dataContext">Data context model.</param>
        /// <param name="func">Function schema.</param>
        /// <param name="defaultSchemas">List of default database schema names.</param>
        private void BuildScalarFunction(DataContextModel dataContext, ScalarFunction func, ISet <string> defaultSchemas)
        {
            var(name, isNonDefaultSchema) = ProcessObjectName(func.Name, defaultSchemas);

            var method = new MethodModel(
                _namingServices.NormalizeIdentifier(_options.DataModel.ProcedureNameOptions,
                                                    (func.Name.Package != null ? $"{func.Name.Package}_" : null) + name.Name))
            {
                Modifiers = Modifiers.Public | Modifiers.Static,
                Summary   = func.Description
            };

            var metadata = new FunctionMetadata()
            {
                Name           = name,
                ServerSideOnly = true
            };

            var funcModel = new ScalarFunctionModel(name, method, metadata);

            BuildParameters(func.Parameters, funcModel.Parameters);

            // thanks to pgsql, scalar function could return not only scalar, but also tuple or just nothing
            switch (func.Result.Kind)
            {
            case ResultKind.Scalar:
            {
                var scalarResult = (ScalarResult)func.Result;
                var typeMapping  = MapType(scalarResult.Type);
                funcModel.Return = typeMapping.CLRType.WithNullability(scalarResult.Nullable);
                // TODO: DataType not used by current scalar function mapping API
                break;
            }

            case ResultKind.Tuple:
            {
                var tupleResult = (TupleResult)func.Result;

                // tuple model class
                var @class = new ClassModel(
                    _namingServices.NormalizeIdentifier(
                        _options.DataModel.FunctionTupleResultClassNameOptions,
                        func.Name.Name))
                {
                    Modifiers = Modifiers.Public | Modifiers.Partial
                };
                funcModel.ReturnTuple = new TupleModel(@class)
                {
                    CanBeNull = tupleResult.Nullable
                };

                // fields order must be preserved, as tuple fields mapped by ordinal
                foreach (var field in tupleResult.Fields)
                {
                    var typeMapping = MapType(field.Type);

                    var prop = new PropertyModel(_namingServices.NormalizeIdentifier(_options.DataModel.FunctionTupleResultPropertyNameOptions, field.Name ?? "Field"), typeMapping.CLRType.WithNullability(field.Nullable))
                    {
                        Modifiers = Modifiers.Public,
                        IsDefault = true,
                        HasSetter = true
                    };
                    funcModel.ReturnTuple.Fields.Add(new TupleFieldModel(prop, field.Type)
                        {
                            DataType = typeMapping.DataType
                        });
                }
                break;
            }

            case ResultKind.Void:
                // just regular postgresql void function, nothing to see here...
                // because function must have return type to be callable in query, we set return type to object?
                funcModel.Return = WellKnownTypes.System.ObjectNullable;
                break;
            }

            _interceptors.PreprocessScalarFunction(_languageProvider.TypeParser, funcModel);

            if (isNonDefaultSchema && _options.DataModel.GenerateSchemaAsType)
            {
                GetOrAddAdditionalSchema(dataContext, func.Name.Schema !).ScalarFunctions.Add(funcModel);
            }
            else
            {
                dataContext.ScalarFunctions.Add(funcModel);
            }
        }
        private void BuildModel()
        {
            DocumentationModel.DisableComments = _configuration.DisableComments;
            var objectModel = new SimpleModel(_configuration)
            {
                Name                 = "AnyType",
                Namespace            = CreateNamespaceModel(new Uri(XmlSchema.Namespace), AnyType),
                XmlSchemaName        = AnyType,
                XmlSchemaType        = null,
                ValueType            = typeof(object),
                UseDataTypeAttribute = false
            };

            Types[AnyType] = objectModel;

            AttributeGroups = Set.Schemas().Cast <XmlSchema>().SelectMany(s => s.AttributeGroups.Values.Cast <XmlSchemaAttributeGroup>())
                              .DistinctBy(g => g.QualifiedName.ToString())
                              .ToDictionary(g => g.QualifiedName);
            Groups = Set.Schemas().Cast <XmlSchema>().SelectMany(s => s.Groups.Values.Cast <XmlSchemaGroup>())
                     .DistinctBy(g => g.QualifiedName.ToString())
                     .ToDictionary(g => g.QualifiedName);

            foreach (var globalType in Set.GlobalTypes.Values.Cast <XmlSchemaType>())
            {
                var schema = globalType.GetSchema();
                var source = (schema == null ? null : new Uri(schema.SourceUri));
                var type   = CreateTypeModel(source, globalType, globalType.QualifiedName);
            }

            foreach (var rootElement in Set.GlobalElements.Values.Cast <XmlSchemaElement>())
            {
                var source        = new Uri(rootElement.GetSchema().SourceUri);
                var qualifiedName = rootElement.ElementSchemaType.QualifiedName;
                if (qualifiedName.IsEmpty)
                {
                    qualifiedName = rootElement.QualifiedName;
                }
                var type = CreateTypeModel(source, rootElement.ElementSchemaType, qualifiedName);

                if (type.RootElementName != null)
                {
                    if (type is ClassModel)
                    {
                        // There is already another global element with this type.
                        // Need to create an empty derived class.

                        var derivedClassModel = new ClassModel(_configuration)
                        {
                            Name      = ToTitleCase(rootElement.QualifiedName.Name),
                            Namespace = CreateNamespaceModel(source, rootElement.QualifiedName)
                        };

                        derivedClassModel.Documentation.AddRange(GetDocumentation(rootElement));

                        if (derivedClassModel.Namespace != null)
                        {
                            derivedClassModel.Name = derivedClassModel.Namespace.GetUniqueTypeName(derivedClassModel.Name);
                            derivedClassModel.Namespace.Types[derivedClassModel.Name] = derivedClassModel;
                        }

                        Types[rootElement.QualifiedName] = derivedClassModel;

                        derivedClassModel.BaseClass = (ClassModel)type;
                        ((ClassModel)derivedClassModel.BaseClass).DerivedTypes.Add(derivedClassModel);

                        derivedClassModel.RootElementName = rootElement.QualifiedName;
                    }
                    else
                    {
                        Types[rootElement.QualifiedName] = type;
                    }
                }
                else
                {
                    if (type is ClassModel classModel)
                    {
                        classModel.Documentation.AddRange(GetDocumentation(rootElement));
                    }

                    type.RootElementName = rootElement.QualifiedName;
                }
            }
        }
        private async Task seedDatabase()
        {
            scienceRoom = new ClassRoom()
            {
                ClassRoomName     = "Science Room",
                SeatsHorizontally = 10,
                SeatsVertically   = 8
            };
            scienceRoom = new ClassRoom()
            {
                ClassRoomName     = "Science Room",
                SeatsHorizontally = 10,
                SeatsVertically   = 8
            };
            jonathan = new Teacher()
            {
                TeacherName = "jonathan"
            };
            heber = new Teacher()
            {
                TeacherName = "not jonathan"
            };
            sam = new Student()
            {
                StudentName = "sam"
            };
            ben = new Student()
            {
                StudentName = "ben"
            };
            tim = new Student()
            {
                StudentName = "tim"
            };
            await classRepository.AddClassRoomAsync(scienceRoom);

            await classRepository.AddTeacherAsync(jonathan);

            await classRepository.AddTeacherAsync(heber);

            await studentRepository.AddStudentAsync(sam);

            await studentRepository.AddStudentAsync(ben);

            await studentRepository.AddStudentAsync(tim);

            mathClass = new ClassModel()
            {
                ClassName   = "math",
                TeacherId   = jonathan.TeacherId,
                ClassRoomId = scienceRoom.ClassRoomId
            };
            scienceClass = new ClassModel()
            {
                ClassName   = "science",
                TeacherId   = jonathan.TeacherId,
                ClassRoomId = scienceRoom.ClassRoomId
            };
            notScienceClass = new ClassModel()
            {
                ClassName   = "not science",
                TeacherId   = heber.TeacherId,
                ClassRoomId = scienceRoom.ClassRoomId
            };
            await classRepository.AddClassAsync(mathClass);

            await classRepository.AddClassAsync(scienceClass);

            await classRepository.AddClassAsync(notScienceClass);

            math1010 = new Course()
            {
                CourseName = "Math 1010",
                TeacherId  = jonathan.TeacherId
            };
            await courseRepository.AddCourseAsync(math1010);

            await classRepository.EnrollStudentAsync(sam.StudentId, mathClass.ClassId, math1010.CourseId);

            await classRepository.EnrollStudentAsync(sam.StudentId, scienceClass.ClassId, math1010.CourseId);

            await classRepository.EnrollStudentAsync(sam.StudentId, notScienceClass.ClassId, math1010.CourseId);
        }
 public TypeTreeNode(ClassModel model)
     : base(model.FullName)
 {
     Tag = model.InFile.FileName + "@" + model.Name;
     if ((model.Flags & FlagType.Interface) > 0) ImageIndex = SelectedImageIndex = PluginUI.ICON_INTERFACE;
     else ImageIndex = SelectedImageIndex = PluginUI.ICON_TYPE;
 }
Beispiel #9
0
 /// <summary>
 /// Show the current class/member in the current outline
 /// </summary>
 /// <param name="classModel"></param>
 /// <param name="memberModel"></param>
 internal void Highlight(ClassModel classModel, MemberModel memberModel)
 {
     if (outlineTree.Nodes.Count == 0) return;
     string match;
     // class or class member
     if (classModel != null && classModel != ClassModel.VoidClass)
     {
         match = classModel.Name;
         TreeNode found = MatchNodeText(outlineTree.Nodes[0].Nodes, match, false);
         if (found != null)
         {
             if (memberModel != null)
             {
                 match = memberModel.ToString();
                 TreeNode foundSub = MatchNodeText(found.Nodes, match, true);
                 if (foundSub != null)
                 {
                     SetHighlight(foundSub);
                     return;
                 }
             }
             SetHighlight(found);
             return;
         }
     }
     // file member
     else if (memberModel != null)
     {
         match = memberModel.ToString();
         TreeNode found = MatchNodeText(outlineTree.Nodes[0].Nodes, match, true);
         if (found != null)
         {
             SetHighlight(found);
             return;
         }
     }
     // no match
     SetHighlight(null);
 }
Beispiel #10
0
        /// <summary>
        /// Maps all foundScripts for all variables and children of the type of the variable
        /// </summary>
        /// <param name="newIDs">The IDs of the new project</param>
        /// <param name="foundScripts">The existing foundScripts that will be looked in and added to</param>
        /// <param name="oldClassModel">Current class data of the old project as this maps to the scene file</param>
        /// <returns></returns>
        /// <exception cref="NullReferenceException"></exception>
        private FoundScript FoundScriptMappingRecursively(List <ClassModel> newIDs,
                                                          ref List <FoundScript> foundScripts, ClassModel oldClassModel)
        {
            if (oldClassModel == null)
            {
                throw new NullReferenceException("No old classData found");
            }

            FoundScript existingFoundScript = foundScripts.FirstOrDefault(script =>
                                                                          script.oldClassModel.FullName == oldClassModel.FullName);

            ClassModel replacementClassModel =
                existingFoundScript
                ?.newClassModel;

            if (replacementClassModel == null && oldClassModel.Fields != null)
            {
                replacementClassModel = findNewID(newIDs, oldClassModel); //todo : testScript gets called double
                if (replacementClassModel == null)
                {
                    return(null);
                }
            }
            else if (replacementClassModel != null)
            {
                return(existingFoundScript);
            }
            else
            {
                return(null);
            }

            if (existingFoundScript != null)
            {
                return(existingFoundScript);
            }


            existingFoundScript = new FoundScript
            {
                oldClassModel = oldClassModel,
                newClassModel = replacementClassModel
            };
            MappedState hasBeenMapped = existingFoundScript.CheckHasBeenMapped();

            if (hasBeenMapped == MappedState.NotMapped)
            {
                existingFoundScript.GenerateMappingNode(foundScripts);
            }

            foundScripts.Add(existingFoundScript);

            //If it doesn't exist then create it

            if (oldClassModel.Fields != null && oldClassModel.Fields.Length != 0)
            {
                foreach (FieldModel field in oldClassModel.Fields)
                {
                    // Check if the type is null as this would cause so errors in the mapping
                    if (field.Type == null)
                    {
                        throw new NullReferenceException("type of field is null for some reason");
                    }

                    FoundScriptMappingRecursively(newIDs, ref foundScripts, field.Type);
                }
            }

            return(existingFoundScript);
        }
Beispiel #11
0
 private void AssertHasProperty(ClassModel classModel, string propertyName, BuiltInType type)
 {
     Assert.IsNotNull(classModel.Properties.FirstOrDefault(p => p.Name == propertyName && p.BuiltInType == type), $"{classModel.Name}.{propertyName} -> {type} is missing.");
 }
        /// <summary>
        /// Checks if a given search match actually points to the given target source
        /// </summary>
        /// <returns>True if the SearchMatch does point to the target source.</returns>
        public static ASResult DeclarationLookupResult(ScintillaControl Sci, int position)
        {
            if (!ASContext.Context.IsFileValid || (Sci == null))
            {
                return(null);
            }
            // get type at cursor position
            ASResult result = ASComplete.GetExpressionType(Sci, position);

            if (result.IsPackage)
            {
                return(result);
            }
            // open source and show declaration
            if (!result.IsNull())
            {
                if (result.Member != null && (result.Member.Flags & FlagType.AutomaticVar) > 0)
                {
                    return(null);
                }
                FileModel model = result.InFile ?? ((result.Member != null && result.Member.InFile != null) ? result.Member.InFile : null) ?? ((result.Type != null) ? result.Type.InFile : null);
                if (model == null || model.FileName == "")
                {
                    return(null);
                }
                ClassModel inClass = result.InClass ?? result.Type;
                // for Back command
                int lookupLine = Sci.CurrentLine;
                int lookupCol  = Sci.CurrentPos - Sci.PositionFromLine(lookupLine);
                ASContext.Panel.SetLastLookupPosition(ASContext.Context.CurrentFile, lookupLine, lookupCol);
                // open the file
                if (model != ASContext.Context.CurrentModel)
                {
                    if (model.FileName.Length > 0 && File.Exists(model.FileName))
                    {
                        ASContext.MainForm.OpenEditableDocument(model.FileName, false);
                    }
                    else
                    {
                        ASComplete.OpenVirtualFile(model);
                        result.InFile = ASContext.Context.CurrentModel;
                        if (result.InFile == null)
                        {
                            return(null);
                        }
                        if (inClass != null)
                        {
                            inClass = result.InFile.GetClassByName(inClass.Name);
                            if (result.Member != null)
                            {
                                result.Member = inClass.Members.Search(result.Member.Name, 0, 0);
                            }
                        }
                        else if (result.Member != null)
                        {
                            result.Member = result.InFile.Members.Search(result.Member.Name, 0, 0);
                        }
                    }
                }
                if ((inClass == null || inClass.IsVoid()) && result.Member == null)
                {
                    return(null);
                }
                Sci = ASContext.CurSciControl;
                if (Sci == null)
                {
                    return(null);
                }
                int    line    = 0;
                string name    = null;
                bool   isClass = false;
                // member
                if (result.Member != null && result.Member.LineFrom > 0)
                {
                    line = result.Member.LineFrom;
                    name = result.Member.Name;
                }
                // class declaration
                else if (inClass.LineFrom > 0)
                {
                    line    = inClass.LineFrom;
                    name    = inClass.Name;
                    isClass = true;
                    // constructor
                    foreach (MemberModel member in inClass.Members)
                    {
                        if ((member.Flags & FlagType.Constructor) > 0)
                        {
                            line    = member.LineFrom;
                            name    = member.Name;
                            isClass = false;
                            break;
                        }
                    }
                }
                if (line > 0) // select
                {
                    if (isClass)
                    {
                        ASComplete.LocateMember("(class|interface)", name, line);
                    }
                    else
                    {
                        ASComplete.LocateMember("(function|var|const|get|set|property|[,(])", name, line);
                    }
                }
                return(result);
            }
            return(null);
        }
Beispiel #13
0
        /// <summary>
        /// Replaces the GUID and fileID, matching the oldIDs with the currentIDs
        /// </summary>
        /// <param name="linesToChange"></param>
        /// <param name="oldIDs">List of GUIDs and FileID for all classes in the previous project.</param>
        /// <param name="newIDs">List of GUIDs and FileID for all currently in the project classes.</param>
        /// <param name="foundScripts"></param>
        /// <returns></returns>
        private string[] MigrateGUIDsAndFieldIDs(string[] linesToChange, List <ClassModel> oldIDs,
                                                 List <ClassModel> newIDs,
                                                 ref List <FoundScript> foundScripts)
        {
            string sceneContent = string.Join("\r\n", linesToChange);

            YamlStream yamlStream = new YamlStream();

            yamlStream.Load(new StringReader(sceneContent));
            IEnumerable <YamlDocument> yamlDocuments =
                yamlStream.Documents.Where(document => document.GetName() == "MonoBehaviour");

            foreach (YamlDocument document in yamlDocuments)
            {
                YamlNode monoBehaviour = document.RootNode.GetChildren()["MonoBehaviour"];

                YamlNode oldFileIdNode = monoBehaviour["m_Script"]["fileID"];
                YamlNode oldGuidNode   = monoBehaviour["m_Script"]["guid"];

                string oldFileId = oldFileIdNode.ToString();
                string oldGuid   = oldGuidNode.ToString();

                ClassModel oldClassModel =
                    oldIDs.FirstOrDefault(data =>
                                          data.Guid == oldGuid && data.FileID == oldFileId);
                if (oldClassModel == null)
                {
                    Debug.LogError("Could not find class for script with type, not migrating guid : " + oldGuid +
                                   " oldFileID : " + oldFileId);
                    continue;
                }

                FoundScript
                    mapping = FoundScriptMappingRecursively(newIDs, ref foundScripts,
                                                            oldClassModel);
                if (mapping == null)
                {
                    Debug.LogError("mapping is null for " + oldClassModel.FullName);
                    continue;
                }

                int line = oldFileIdNode.Start.Line - 1;
                if (!string.IsNullOrEmpty(mapping.newClassModel.Guid))
                {
                    // Replace the Guid
                    linesToChange[line] = linesToChange[line].ReplaceFirst(oldGuid, mapping.newClassModel.Guid);
                }
                else
                {
                    Debug.Log("Found empty guid");
                    continue;
                    //todo : this should throw an error
                    //todo : this is when a non script is being used or the guid is not available. This should probably be a popup with a warning
                }

                if (!String.IsNullOrEmpty(oldFileId))
                {
                    linesToChange[line] = linesToChange[line].ReplaceFirst(oldFileId, mapping.newClassModel.FileID);
                }
            }

            return(linesToChange);
        }
Beispiel #14
0
        public EditClassPage(ClassModel chosenClass)
        {
            Chosen  = chosenClass;
            Padding = new Thickness(0, 8);
            var layout = new StackLayout();

            var exitEdit = new ToolbarItem
            {
                Text     = "Cancel",
                Priority = 0
            };

            exitEdit.Clicked += OnExitEditClicked;
            ToolbarItems.Add(exitEdit);

            String text = "";

            if (chosenClass.TypeOfClass == "Curs")
            {
                text = "There are no similar classes";
            }
            else
            {
                text = "Choose from other groups' classes";
            }

            Frame f1 = new Frame
            {
                BackgroundColor = (Color)Application.Current.Resources["cursColor"],
                BorderColor     = (Color)Application.Current.Resources["cursColor"],
                CornerRadius    = 4,
                Margin          = new Thickness(16, 8),
                Content         = new Label
                {
                    Text                    = text,
                    TextColor               = Color.White,
                    FontAttributes          = FontAttributes.Bold,
                    FontSize                = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                    Margin                  = 0,
                    HorizontalOptions       = LayoutOptions.Center,
                    VerticalOptions         = LayoutOptions.Center,
                    HorizontalTextAlignment = TextAlignment.Center,
                    VerticalTextAlignment   = TextAlignment.Center
                }
            };

            var msg = new Label
            {
                Text                    = "Custom edit your class",
                TextColor               = Color.White,
                FontAttributes          = FontAttributes.Bold,
                FontSize                = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                Margin                  = 0,
                HorizontalOptions       = LayoutOptions.Center,
                VerticalOptions         = LayoutOptions.Center,
                HorizontalTextAlignment = TextAlignment.Center,
                VerticalTextAlignment   = TextAlignment.Center
            };
            var tgr = new TapGestureRecognizer();

            tgr.Tapped += (s, e) =>
            {
                Navigation.PushAsync(new CustomEdit(chosenClass));
            };
            msg.GestureRecognizers.Add(tgr);

            Frame f2 = new Frame
            {
                BackgroundColor = (Color)Application.Current.Resources["seminarColor"],
                BorderColor     = (Color)Application.Current.Resources["seminarColor"],
                CornerRadius    = 4,
                Margin          = new Thickness(16, 8),
                Content         = msg,
            };

            var msg2 = new Label
            {
                Text                    = "Remove this class",
                TextColor               = Color.White,
                FontAttributes          = FontAttributes.Bold,
                FontSize                = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                Margin                  = 0,
                HorizontalOptions       = LayoutOptions.Center,
                VerticalOptions         = LayoutOptions.Center,
                HorizontalTextAlignment = TextAlignment.Center,
                VerticalTextAlignment   = TextAlignment.Center
            };
            var tgr2 = new TapGestureRecognizer();

            tgr2.Tapped += OnAlertYesNoClicked;
            msg2.GestureRecognizers.Add(tgr2);

            Frame f3 = new Frame
            {
                BackgroundColor = (Color)Application.Current.Resources["labColor"],
                BorderColor     = (Color)Application.Current.Resources["labColor"],
                CornerRadius    = 4,
                Margin          = new Thickness(16, 8),
                Content         = msg2,
            };

            layout.Children.Add(f1);

            //get all equivalent classes
            foreach (ClassModel c in StudentInfoModel.SortedClasses[chosenClass.ClassName][chosenClass.TypeOfClass])
            {
                if (!c.Equals(chosenClass))
                {
                    var classView = new DetailedClassView(c);

                    var tgr3 = new TapGestureRecognizer();
                    tgr3.Tapped += (s, e) =>
                    {
                        WriteToFile(c);
                    };
                    classView.GestureRecognizers.Add(tgr3);

                    layout.Children.Add(classView);
                }
            }

            layout.Children.Add(f2);
            layout.Children.Add(f3);

            var view = new ScrollView()
            {
                Content = layout
            };

            Content = view;
        }
        public IEnumerable <MethodDeclarationSyntax> Create(IMethodModel method, ClassModel model)
        {
            if (method is null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            for (var i = 0; i < method.Parameters.Count; i++)
            {
                if (!method.Parameters[i].TypeInfo.Type.IsReferenceType)
                {
                    continue;
                }

                if (method.Parameters[i].TypeInfo.Type.SpecialType == SpecialType.System_String)
                {
                    continue;
                }

                if (method.Parameters[i].Node.Modifiers.Any(x => x.Kind() == SyntaxKind.OutKeyword))
                {
                    continue;
                }

                var paramList = new List <CSharpSyntaxNode>();

                var methodName      = string.Format(CultureInfo.InvariantCulture, "CannotCall{0}WithNull{1}", model.GetMethodUniqueName(method), method.Parameters[i].Name.ToPascalCase());
                var generatedMethod = _frameworkSet.TestFramework.CreateTestMethod(methodName, method.IsAsync && _frameworkSet.TestFramework.AssertThrowsAsyncIsAwaitable, model.IsStatic);

                for (var index = 0; index < method.Parameters.Count; index++)
                {
                    var parameter = method.Parameters[index];
                    if (parameter.Node.Modifiers.Any(x => x.Kind() == SyntaxKind.RefKeyword))
                    {
                        var defaultAssignmentValue = AssignmentValueHelper.GetDefaultAssignmentValue(parameter.TypeInfo, model.SemanticModel, _frameworkSet);

                        if (index == i)
                        {
                            defaultAssignmentValue = SyntaxFactory.DefaultExpression(method.Parameters[i].TypeInfo.ToTypeSyntax(_frameworkSet.Context));
                        }

                        generatedMethod = generatedMethod.AddBodyStatements(SyntaxFactory.LocalDeclarationStatement(
                                                                                SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName(Strings.Create_var))
                                                                                .WithVariables(SyntaxFactory.SingletonSeparatedList(
                                                                                                   SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(parameter.Name))
                                                                                                   .WithInitializer(SyntaxFactory.EqualsValueClause(defaultAssignmentValue))))));

                        paramList.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(parameter.Name)).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword)));
                    }
                    else if (parameter.Node.Modifiers.Any(x => x.Kind() == SyntaxKind.OutKeyword))
                    {
                        paramList.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("_")).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.OutKeyword)));
                    }
                    else
                    {
                        if (index == i)
                        {
                            paramList.Add(SyntaxFactory.DefaultExpression(method.Parameters[i].TypeInfo.ToTypeSyntax(_frameworkSet.Context)));
                        }
                        else
                        {
                            paramList.Add(AssignmentValueHelper.GetDefaultAssignmentValue(parameter.TypeInfo, model.SemanticModel, _frameworkSet));
                        }
                    }
                }

                var methodCall = method.Invoke(model, true, _frameworkSet, paramList.ToArray());

                if (method.IsAsync)
                {
                    generatedMethod = generatedMethod.AddBodyStatements(_frameworkSet.TestFramework.AssertThrowsAsync(SyntaxFactory.IdentifierName("ArgumentNullException"), methodCall));
                }
                else
                {
                    generatedMethod = generatedMethod.AddBodyStatements(_frameworkSet.TestFramework.AssertThrows(SyntaxFactory.IdentifierName("ArgumentNullException"), methodCall));
                }

                yield return(generatedMethod);
            }
        }
 public static Class ToEntity(this ClassModel model, Class destination)
 {
     return(model.MapTo(destination));
 }
Beispiel #17
0
 public string DoWork(ClassModel objectClass, string inputStr)
 {
     return inputStr;
 }
Beispiel #18
0
 private void AssertHasOneToManyProperty(ClassModel classModel, string propertyName)
 {
     Assert.IsNotNull(classModel.Properties.FirstOrDefault(p => p.Name == propertyName && p.BuiltInType == BuiltInType.Object && p.IsCollection && !p.IsManyToMany), $"{classModel.Name}.{propertyName} is missing.");
 }
 public static Class ToEntity(this ClassModel model)
 {
     return(model.MapTo <ClassModel, Class>());
 }
Beispiel #20
0
 private static void BuildDomainEventPublisher(ITypeModelRegistry registry, BodyBuilder builder, Aggregate aggregate, ClassModel @class, ClassModel domainEvent, List <MethodParameter> parameters)
 {
     if (aggregate.UniqueIdentifier != null)
     {
         if (aggregate.UniqueIdentifier.Type.Resolve(registry) != SystemTypes.Guid)
         {
             builder.InvokeMethod(
                 SystemTypes.DomainEventPublishMethodName,
                 domainEvent.Construct(
                     parameters.ToExpressions(),
                     domainEvent.Initializer(SystemTypes.DomainEventAggregateRootIdentifierName, @class.GetMethod("ToGuid").Invoke(parameters.First().Expression)))
                 );
         }
         else
         {
             builder.InvokeMethod(
                 SystemTypes.DomainEventPublishMethodName,
                 domainEvent.Construct(
                     parameters.ToExpressions(),
                     domainEvent.Initializer(SystemTypes.DomainEventAggregateRootIdentifierName, parameters.First().Expression))
                 );
         }
     }
     else
     {
         builder.InvokeMethod(SystemTypes.DomainEventPublishMethodName, domainEvent.Construct(parameters.ToExpressions().ToArray()));
     }
 }
Beispiel #21
0
		/// <summary>
		/// Add the class object to a cache
		/// TODO  change to FileModel
		/// </summary>
		/// <param name="aClass">Class object to cache</param>
		private bool AddClassToCache(ClassModel aClass)
		{
			/*if (!aClass.IsVoid())
			{
				ClassModel check = (ClassModel)classes[aClass.ClassName];
				if (check != null && lastClassWarning != aClass.ClassName)
				{
					// if this class was defined in another file, check if it is still open
					if (String.CompareOrdinal(check.InFile.FileName, aClass.InFile.FileName) != 0)
					{
						ScintillaNet.ScintillaControl sci = MainForm.CurSciControl;
						WeifenLuo.WinFormsUI.DockContent[] docs = MainForm.GetDocuments();
						int found = 0;
						bool isActive = false;
						string tabFile;
						// check if the classes are open
						foreach(WeifenLuo.WinFormsUI.DockContent doc in docs)
						{
							tabFile = MainForm.GetSciControl(doc).Tag.ToString();
							if (String.CompareOrdinal(check.InFile.FileName, tabFile) == 0
							    || String.CompareOrdinal(aClass.InFile.FileName, tabFile) == 0)
							{
								if (MainForm.GetSciControl(doc) == sci)
									isActive = true;
								found++;
							}
						}
						// if there are several files declaring the same class
						if (found > 1 && isActive)
						{
							lastClassWarning = aClass.ClassName;
							
							Match cdecl = Regex.Match(sci.Text, "[\\s]class[\\s]+(?<cname>"+aClass.ClassName+")[^\\w]");
							int line = 1;
							if (cdecl.Success) 
							{
								line = 1+sci.LineFromPosition( sci.MBSafeCharPosition(cdecl.Groups["cname"].Index) );
							}
							string msg = String.Format("The class '{2}' is already declared in {3}",
							                           aClass.InFile.FileName, line, aClass.ClassName, check.InFile.FileName);
							MessageBar.ShowWarning(msg);
						}
						else lastClassWarning = null;
					}
				}
				classes[aClass.ClassName] = aClass;
				return true;
			}*/
			return false;
		}
 static MemberTreeNode GetClassTreeNode(ClassModel classModel, bool isInherited, bool isImported)
 {
     int imageNum = ((classModel.Flags & FlagType.Intrinsic) > 0) ? PluginUI.ICON_INTRINSIC_TYPE :
                    ((classModel.Flags & FlagType.Interface) > 0) ? PluginUI.ICON_INTERFACE : PluginUI.ICON_TYPE;
     return isInherited ? new InheritedClassTreeNode(classModel, imageNum, Settings.ShowQualifiedClassName) :
            isImported ? new ImportTreeNode(classModel, imageNum, Settings.ShowQualifiedClassName) :
                         new ClassTreeNode(classModel, imageNum, Settings.ShowQualifiedClassName) as MemberTreeNode;
 }
Beispiel #23
0
        void AddClassContracts(ClassModel model)
        {
            if (model.BaseClassType == null && !model.Interfaces.Any())
            {
                return;
            }


        #line default
        #line hidden

        #line 83 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            this.Write(" : ");


        #line default
        #line hidden

        #line 83 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"

            if (model.BaseClassType != null)
            {
        #line default
        #line hidden

        #line 86 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(model.BaseClassType.FullName));


        #line default
        #line hidden

        #line 86 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(" ");


        #line default
        #line hidden

        #line 86 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"

                if (model.Interfaces.Any())
                {
        #line default
        #line hidden

        #line 89 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write(", ");


        #line default
        #line hidden

        #line 89 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                }
            }
            if (model.Interfaces.Any())
            {
                string interfaces = string.Join(",", model.Interfaces.Select(i => i.FullName).ToList());


        #line default
        #line hidden

        #line 95 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(interfaces));


        #line default
        #line hidden

        #line 95 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            }
        }
        static IEnumerable<MemberTreeNode> GetInheritedMembers(ClassModel classModel)
        {
            var memberNodes = Enumerable.Empty<MemberTreeNode>();

            // Add members from our super class as long as it is not null, Object, Void, or haXe Dynamic
            while (!IsRootType(classModel))
            {
                memberNodes = memberNodes.Concat(classModel.Members
                    .OfType<MemberModel>()
                    .Select(member => GetMemberTreeNode(member, classModel))
                    .Where(mn => mn != null));

                // Follow the inheritence chain down
                classModel = classModel.Extends;
            }

            return memberNodes;
        }
        // ReSharper disable once FunctionComplexityOverflow
        private TypeModel CreateTypeModel(Uri source, XmlSchemaAnnotated type, XmlQualifiedName qualifiedName)
        {
            if (!qualifiedName.IsEmpty && Types.TryGetValue(qualifiedName, out TypeModel typeModel))
            {
                return(typeModel);
            }

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            var namespaceModel = CreateNamespaceModel(source, qualifiedName);

            var docs = GetDocumentation(type);

            if (type is XmlSchemaGroup group)
            {
                var name = "I" + ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    name = namespaceModel.GetUniqueTypeName(name);
                }

                var interfaceModel = new InterfaceModel(_configuration)
                {
                    Name          = name,
                    Namespace     = namespaceModel,
                    XmlSchemaName = qualifiedName
                };

                interfaceModel.Documentation.AddRange(docs);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[name] = interfaceModel;
                }
                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = interfaceModel;
                }

                var particle   = group.Particle;
                var items      = GetElements(particle);
                var properties = CreatePropertiesForElements(source, interfaceModel, particle, items.Where(i => !(i.XmlParticle is XmlSchemaGroupRef)));
                interfaceModel.Properties.AddRange(properties);
                var interfaces = items.Select(i => i.XmlParticle).OfType <XmlSchemaGroupRef>()
                                 .Select(i => (InterfaceModel)CreateTypeModel(new Uri(i.SourceUri), Groups[i.RefName], i.RefName));
                interfaceModel.Interfaces.AddRange(interfaces);

                return(interfaceModel);
            }

            if (type is XmlSchemaAttributeGroup attributeGroup)
            {
                var name = "I" + ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    name = namespaceModel.GetUniqueTypeName(name);
                }

                var interfaceModel = new InterfaceModel(_configuration)
                {
                    Name          = name,
                    Namespace     = namespaceModel,
                    XmlSchemaName = qualifiedName
                };

                interfaceModel.Documentation.AddRange(docs);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[name] = interfaceModel;
                }
                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = interfaceModel;
                }

                var items      = attributeGroup.Attributes;
                var properties = CreatePropertiesForAttributes(source, interfaceModel, items.OfType <XmlSchemaAttribute>());
                interfaceModel.Properties.AddRange(properties);
                var interfaces = items.OfType <XmlSchemaAttributeGroupRef>()
                                 .Select(a => (InterfaceModel)CreateTypeModel(new Uri(a.SourceUri), AttributeGroups[a.RefName], a.RefName));
                interfaceModel.Interfaces.AddRange(interfaces);

                return(interfaceModel);
            }

            if (type is XmlSchemaComplexType complexType)
            {
                var name = ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    name = namespaceModel.GetUniqueTypeName(name);
                }

                var classModel = new ClassModel(_configuration)
                {
                    Name           = name,
                    Namespace      = namespaceModel,
                    XmlSchemaName  = qualifiedName,
                    XmlSchemaType  = complexType,
                    IsAbstract     = complexType.IsAbstract,
                    IsAnonymous    = complexType.QualifiedName.Name == "",
                    IsMixed        = complexType.IsMixed,
                    IsSubstitution = complexType.Parent is XmlSchemaElement && !((XmlSchemaElement)complexType.Parent).SubstitutionGroup.IsEmpty
                };

                classModel.Documentation.AddRange(docs);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[classModel.Name] = classModel;
                }

                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = classModel;
                }

                if (complexType.BaseXmlSchemaType != null && complexType.BaseXmlSchemaType.QualifiedName != AnyType)
                {
                    var baseModel = CreateTypeModel(source, complexType.BaseXmlSchemaType, complexType.BaseXmlSchemaType.QualifiedName);
                    classModel.BaseClass = baseModel;
                    if (baseModel is ClassModel)
                    {
                        ((ClassModel)classModel.BaseClass).DerivedTypes.Add(classModel);
                    }
                }

                XmlSchemaParticle particle = null;
                if (classModel.BaseClass != null)
                {
                    if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
                    {
                        particle = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Particle;
                    }

                    // If it's a restriction, do not duplicate elements on the derived class, they're already in the base class.
                    // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
                    //else if (complexType.ContentModel.Content is XmlSchemaComplexContentRestriction)
                    //    particle = ((XmlSchemaComplexContentRestriction)complexType.ContentModel.Content).Particle;
                }
                else
                {
                    particle = complexType.ContentTypeParticle;
                }

                var items      = GetElements(particle);
                var properties = CreatePropertiesForElements(source, classModel, particle, items);
                classModel.Properties.AddRange(properties);

                if (GenerateInterfaces)
                {
                    var interfaces = items.Select(i => i.XmlParticle).OfType <XmlSchemaGroupRef>()
                                     .Select(i => (InterfaceModel)CreateTypeModel(new Uri(i.SourceUri), Groups[i.RefName], i.RefName));
                    classModel.Interfaces.AddRange(interfaces);
                }

                XmlSchemaObjectCollection attributes = null;
                if (classModel.BaseClass != null)
                {
                    if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
                    {
                        attributes = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Attributes;
                    }
                    else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension)
                    {
                        attributes = ((XmlSchemaSimpleContentExtension)complexType.ContentModel.Content).Attributes;
                    }

                    // If it's a restriction, do not duplicate attributes on the derived class, they're already in the base class.
                    // See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
                    //else if (complexType.ContentModel.Content is XmlSchemaComplexContentRestriction)
                    //    attributes = ((XmlSchemaComplexContentRestriction)complexType.ContentModel.Content).Attributes;
                    //else if (complexType.ContentModel.Content is XmlSchemaSimpleContentRestriction)
                    //    attributes = ((XmlSchemaSimpleContentRestriction)complexType.ContentModel.Content).Attributes;
                }
                else
                {
                    attributes = complexType.Attributes;
                }

                if (attributes != null)
                {
                    var attributeProperties = CreatePropertiesForAttributes(source, classModel, attributes.Cast <XmlSchemaObject>());
                    classModel.Properties.AddRange(attributeProperties);

                    if (GenerateInterfaces)
                    {
                        var attributeInterfaces = attributes.OfType <XmlSchemaAttributeGroupRef>()
                                                  .Select(i => (InterfaceModel)CreateTypeModel(new Uri(i.SourceUri), AttributeGroups[i.RefName], i.RefName));
                        classModel.Interfaces.AddRange(attributeInterfaces);
                    }
                }

                if (complexType.AnyAttribute != null)
                {
                    var property = new PropertyModel(_configuration)
                    {
                        OwningType = classModel,
                        Name       = "AnyAttribute",
                        Type       = new SimpleModel(_configuration)
                        {
                            ValueType = typeof(XmlAttribute), UseDataTypeAttribute = false
                        },
                        IsAttribute  = true,
                        IsCollection = true,
                        IsAny        = true
                    };

                    var attributeDocs = GetDocumentation(complexType.AnyAttribute);
                    property.Documentation.AddRange(attributeDocs);

                    classModel.Properties.Add(property);
                }

                return(classModel);
            }

            if (type is XmlSchemaSimpleType simpleType)
            {
                var restrictions = new List <RestrictionModel>();

                if (simpleType.Content is XmlSchemaSimpleTypeRestriction typeRestriction)
                {
                    var enumFacets = typeRestriction.Facets.OfType <XmlSchemaEnumerationFacet>().ToList();
                    var isEnum     = (enumFacets.Count == typeRestriction.Facets.Count && enumFacets.Count != 0) ||
                                     (EnumTypes.Contains(typeRestriction.BaseTypeName.Name) && enumFacets.Any());
                    if (isEnum)
                    {
                        // we got an enum
                        var name = ToTitleCase(qualifiedName.Name);
                        if (namespaceModel != null)
                        {
                            name = namespaceModel.GetUniqueTypeName(name);
                        }

                        var enumModel = new EnumModel(_configuration)
                        {
                            Name          = name,
                            Namespace     = namespaceModel,
                            XmlSchemaName = qualifiedName,
                            XmlSchemaType = simpleType,
                        };

                        enumModel.Documentation.AddRange(docs);

                        foreach (var facet in enumFacets.DistinctBy(f => f.Value))
                        {
                            var value = new EnumValueModel
                            {
                                Name  = _configuration.NamingProvider.EnumMemberNameFromValue(enumModel.Name, facet.Value),
                                Value = facet.Value
                            };

                            var valueDocs = GetDocumentation(facet);
                            value.Documentation.AddRange(valueDocs);

                            var deprecated = facet.Annotation != null && facet.Annotation.Items.OfType <XmlSchemaAppInfo>()
                                             .Any(a => a.Markup.Any(m => m.Name == "annox:annotate" && m.HasChildNodes && m.FirstChild.Name == "jl:Deprecated"));
                            value.IsDeprecated = deprecated;

                            enumModel.Values.Add(value);
                        }

                        if (namespaceModel != null)
                        {
                            namespaceModel.Types[enumModel.Name] = enumModel;
                        }

                        if (!qualifiedName.IsEmpty)
                        {
                            Types[qualifiedName] = enumModel;
                        }

                        return(enumModel);
                    }

                    restrictions = GetRestrictions(typeRestriction.Facets.Cast <XmlSchemaFacet>(), simpleType).Where(r => r != null).Sanitize().ToList();
                }

                var simpleModelName = ToTitleCase(qualifiedName.Name);
                if (namespaceModel != null)
                {
                    simpleModelName = namespaceModel.GetUniqueTypeName(simpleModelName);
                }

                var simpleModel = new SimpleModel(_configuration)
                {
                    Name          = simpleModelName,
                    Namespace     = namespaceModel,
                    XmlSchemaName = qualifiedName,
                    XmlSchemaType = simpleType,
                    ValueType     = simpleType.Datatype.GetEffectiveType(_configuration),
                };

                simpleModel.Documentation.AddRange(docs);
                simpleModel.Restrictions.AddRange(restrictions);

                if (namespaceModel != null)
                {
                    namespaceModel.Types[simpleModel.Name] = simpleModel;
                }

                if (!qualifiedName.IsEmpty)
                {
                    Types[qualifiedName] = simpleModel;
                }

                return(simpleModel);
            }

            throw new Exception(string.Format("Cannot build declaration for {0}", qualifiedName));
        }
        static MemberTreeNode GetMemberTreeNode(MemberModel memberModel, ClassModel classModel)
        {
            MemberTreeNode node = null;
            int imageIndex = PluginUI.GetIcon(memberModel.Flags, memberModel.Access);

            if (imageIndex != 0)
                node = classModel == null ?
                    new MemberTreeNode(memberModel, imageIndex, Settings.LabelPropertiesLikeFunctions) :
                    new InheritedMemberTreeNode(classModel, memberModel, imageIndex, Settings.LabelPropertiesLikeFunctions);

            return node;
        }
Beispiel #27
0
        public PastLifeEditScreen()
        {
            InitializeComponent();
            NumClasses  = ClassModel.GetNumClasses();
            NumSkills   = SkillModel.GetNumSkills();
            NumIconic   = RaceModel.GetNumIconic();
            AllowChange = false;
            int           xpos        = 4;
            int           ypos        = 0;
            float         iconposx    = 4;
            float         iconposy    = 0;
            int           currentrow  = 0;
            int           PanelHeight = PastLifeClassPanel.Height;
            int           PanelWidth  = PastLifeClassPanel.Width;
            int           maxrow      = (int)System.Math.Ceiling((decimal)NumClasses / 4);
            StringBuilder controlName;

            ClassPanelEntry.ClassIcon = new IconClass[NumClasses];
            //ClassPanelEntry.ClassPastLifeValue = new Label[NumClasses];
            ClassPanelEntry.ClassPastLifeUpDown = new NumericUpDownWithBlank[NumClasses];
            ClassNames = ClassModel.GetNames();
            int xposstart = 10;

            for (int i = 0; i < NumClasses; i++)
            {
                //create Icon
                ClassPanelEntry.ClassIcon[i] = new IconClass("Classes\\" + ClassNames[i]);

                //create updown data entry
                controlName = new StringBuilder();
                controlName.Append("ClassUpDown");
                controlName.Append(i);


                ClassPanelEntry.ClassPastLifeUpDown[i]      = new NumericUpDownWithBlank();
                ClassPanelEntry.ClassPastLifeUpDown[i].Name = controlName.ToString();
                PastLifeClassPanel.Controls.Add(ClassPanelEntry.ClassPastLifeUpDown[i]);
                ClassPanelEntry.ClassPastLifeUpDown[i].Size          = new Size(39, 20);
                ClassPanelEntry.ClassPastLifeUpDown[i].Blank         = true;
                ClassPanelEntry.ClassPastLifeUpDown[i].ValueChanged += ClassUpDownValueChanged;
                ClassPanelEntry.ClassPastLifeUpDown[i].Minimum       = 1;
                //TODO: Hardcoded value! Remove into the database
                ClassPanelEntry.ClassPastLifeUpDown[i].Maximum = 3;

                //create position start point
                currentrow = (int)i / 4;
                xpos       = (i - (currentrow * 4)) * 100 + xposstart;
                iconposx   = ((float)xpos / (float)PanelWidth);
                ypos       = 30 + ((PastLifeClassPanel.Height - 30) / maxrow) * currentrow;
                iconposy   = ((float)ypos / (float)PanelHeight);
                // Place Icon and control
                ClassPanelEntry.ClassIcon[i].SetLocation(PastLifeClassPanel.Width, PastLifeClassPanel.Height, new PointF(iconposx, iconposy));
                ClassPanelEntry.ClassPastLifeUpDown[i].Location = new Point(xpos + 40, ypos + 5);
            }
            //populate the Iconic past life panel
            xpos        = 4;
            ypos        = 0;
            iconposx    = 0;
            iconposy    = 0;
            currentrow  = 0;
            PanelHeight = PastLifeIconicPanel.Height;
            PanelWidth  = PastLifeIconicPanel.Width;
            maxrow      = (int)System.Math.Ceiling((decimal)NumIconic / 4);
            IconicPanelEntry.IconicIcon           = new IconClass[NumIconic];
            IconicPanelEntry.IconicPastLifeUpDown = new NumericUpDownWithBlank[NumIconic];
            IconicNames = RaceModel.GetIconicNames();
            for (int i = 0; i < NumIconic; i++)
            {
                //create Icon
                IconicPanelEntry.IconicIcon[i] = new IconClass("Races\\" + IconicNames[i] + " Icon");

                //create updown data entry
                controlName = new StringBuilder();
                controlName.Append("IconicUpDown");
                controlName.Append(i);

                IconicPanelEntry.IconicPastLifeUpDown[i]      = new NumericUpDownWithBlank();
                IconicPanelEntry.IconicPastLifeUpDown[i].Name = controlName.ToString();
                PastLifeIconicPanel.Controls.Add(IconicPanelEntry.IconicPastLifeUpDown[i]);
                IconicPanelEntry.IconicPastLifeUpDown[i].Size          = new Size(39, 20);
                IconicPanelEntry.IconicPastLifeUpDown[i].Blank         = true;
                IconicPanelEntry.IconicPastLifeUpDown[i].ValueChanged += IconiocUpDownValueChanged;
                IconicPanelEntry.IconicPastLifeUpDown[i].Minimum       = 1;
                //TODO: Hardcoded value! Remove into the database
                IconicPanelEntry.IconicPastLifeUpDown[i].Maximum = 3;

                //create position start point
                currentrow = (int)i / 4;
                xpos       = (i - (currentrow * 4)) * 100 + xposstart;
                iconposx   = ((float)xpos / (float)PanelWidth);
                ypos       = 30 + ((PastLifeClassPanel.Height - 30) / maxrow) * currentrow;
                iconposy   = ((float)ypos / (float)PanelHeight);
                // Place Icon and control
                IconicPanelEntry.IconicIcon[i].SetLocation(PastLifeIconicPanel.Width, PastLifeIconicPanel.Height, new PointF(iconposx, iconposy));
                IconicPanelEntry.IconicPastLifeUpDown[i].Location = new Point(xpos + 40, ypos + 10);
            }

            //populate the skills panel
            SkillNames = Enum.GetNames(typeof(CharacterSkillClass.Skills)).ToList();
            SkillTomePanelEntry.SkillLabel  = new Label[NumSkills];
            SkillTomePanelEntry.SkillUpDown = new NumericUpDownWithBlank[NumSkills];
            xpos = 20;
            ypos = 0;
            Control[] control;
            NumericUpDownWithBlank upDown;
            int rowsplit = (int)System.Math.Ceiling((decimal)NumSkills / 2);

            for (int i = 0; i < NumSkills; i++)
            {
                ypos = 30 * i;
                if (i >= rowsplit)
                {
                    ypos -= 30 * rowsplit;
                }
                SkillTomePanelEntry.SkillLabel[i] = new Label();
                SkillTomeSubPanel.Controls.Add(SkillTomePanelEntry.SkillLabel[i]);
                SkillTomePanelEntry.SkillLabel[i].Text      = SkillNames[i].Replace("_", " ");
                SkillTomePanelEntry.SkillLabel[i].Location  = new Point(xpos, ypos + 3);
                SkillTomePanelEntry.SkillLabel[i].AutoSize  = true;
                SkillTomePanelEntry.SkillLabel[i].ForeColor = System.Drawing.Color.Gold;
                SkillTomePanelEntry.SkillLabel[i].Font      = new Font("Times New Roman", 9, FontStyle.Bold);
                SkillTomePanelEntry.SkillLabel[i].Name      = "SkillLabel" + i;
                SkillTomePanelEntry.SkillUpDown[i]          = new NumericUpDownWithBlank();
                SkillTomeSubPanel.Controls.Add(SkillTomePanelEntry.SkillUpDown[i]);
                SkillTomePanelEntry.SkillUpDown[i].Location      = new Point(xpos + 120, ypos);
                SkillTomePanelEntry.SkillUpDown[i].Name          = "SkillUpDown" + SkillNames[i];
                SkillTomePanelEntry.SkillUpDown[i].Size          = new Size(39, 20);
                SkillTomePanelEntry.SkillUpDown[i].Blank         = true;
                SkillTomePanelEntry.SkillUpDown[i].Minimum       = 1;
                SkillTomePanelEntry.SkillUpDown[i].ValueChanged += SkillUpDownValueChanged;

                System.Guid SkillID   = SkillModel.GetIdFromName(SkillNames[i].Replace("_", " "));
                int         UpDownMax = TomeModel.GetMaxBonus(SkillID);
                SkillTomePanelEntry.SkillUpDown[i].Maximum = UpDownMax;
                if (i >= rowsplit - 1)
                {
                    xpos = 200;
                }
            }
            AllowChange = true;
            for (int i = 0; i < NumSkills; ++i)
            {
                SetSkillUpDown(SkillTomePanelEntry.SkillUpDown[i]);
            }
            SetAbilityUpDown(StrUpDown);
            SetAbilityUpDown(DexUpDown);
            SetAbilityUpDown(ConUpDown);
            SetAbilityUpDown(IntUpDown);
            SetAbilityUpDown(WisUpDown);
            SetAbilityUpDown(ChaUpDown);
            for (int i = 0; i < NumClasses; ++i)
            {
                controlName = new StringBuilder();
                controlName.Append("ClassUpDown");
                controlName.Append(i);
                control = Controls.Find(controlName.ToString(), true);
                upDown  = (NumericUpDownWithBlank)control[0];
                if (upDown == null)
                {
                    continue;
                }
                SetClassUpDown(upDown);
            }
            for (int i = 0; i < NumIconic; ++i)
            {
                controlName = new StringBuilder();
                controlName.Append("IconicUpDown");
                controlName.Append(i);
                control = Controls.Find(controlName.ToString(), true);
                upDown  = (NumericUpDownWithBlank)control[0];
                if (upDown == null)
                {
                    continue;
                }
                SetIconicUpDown(upDown);
            }

            ClassTooltipDisplay  = -1;
            IconicTooltipDisplay = -1;
        }
 static bool IsRootType(ClassModel classModel)
 {
     return classModel == null ||
            classModel.Name == "Object" ||
            classModel == ClassModel.VoidClass ||
            (classModel.InFile.haXe && classModel.Type == "Dynamic");
 }
Beispiel #29
0
        /// <summary>
        /// Create table function/stored procedure result set model using existing entity or custom model.
        /// </summary>
        /// <param name="funcName">Database name for function/procedure.</param>
        /// <param name="columns">Result set columns schema. Must be ordered by ordinal.</param>
        /// <returns>Model for result set.</returns>
        private FunctionResult PrepareResultSetModel(SqlObjectName funcName, IReadOnlyCollection <ResultColumn> columns)
        {
            // try to find entity model with same set of columns
            // column equality check includes: name, database type and nullability
            if (_options.DataModel.MapProcedureResultToEntity)
            {
                var names = new Dictionary <string, (DatabaseType type, bool isNullable)>();
                foreach (var column in columns)
                {
                    // columns without name or duplicate names indicate that it is not entity and requires custom
                    // mapper with by-ordinal mapping
                    if (string.IsNullOrEmpty(column.Name) || names.ContainsKey(column.Name !))
                    {
                        break;
                    }

                    names.Add(column.Name !, (column.Type, column.Nullable));
                }

                if (names.Count == columns.Count)
                {
                    foreach (var(schemaObject, entity) in _entities.Values)
                    {
                        if (schemaObject.Columns.Count == names.Count)
                        {
                            var match = true;
                            foreach (var column in schemaObject.Columns)
                            {
                                if (!names.TryGetValue(column.Name, out var columnType) ||
                                    !column.Type.Equals(columnType.type) ||
                                    column.Nullable != columnType.isNullable)
                                {
                                    match = false;
                                    break;
                                }
                            }

                            if (match)
                            {
                                return(new FunctionResult(null, _entities[schemaObject.Name].Entity, null));
                            }
                        }
                    }
                }
            }

            var resultClass = new ClassModel(
                _namingServices.NormalizeIdentifier(
                    _options.DataModel.ProcedureResultClassNameOptions,
                    (funcName.Package != null ? $"{funcName.Package}_" : null) + funcName.Name))
            {
                Modifiers = Modifiers.Partial | Modifiers.Public
            };
            var model = new ResultTableModel(resultClass);

            foreach (var col in columns)
            {
                var typeMapping = MapType(col.Type);

                var metadata = new ColumnMetadata()
                {
                    Name      = col.Name ?? string.Empty,
                    DbType    = _options.DataModel.GenerateDbType   ? col.Type             : null,
                    DataType  = _options.DataModel.GenerateDataType ? typeMapping.DataType : null,
                    CanBeNull = col.Nullable
                };

                var property = new PropertyModel(
                    _namingServices.NormalizeIdentifier(_options.DataModel.ProcedureResultColumnPropertyNameOptions, col.Name ?? "Column"),
                    typeMapping.CLRType.WithNullability(col.Nullable))
                {
                    Modifiers = Modifiers.Public,
                    HasSetter = true,
                    IsDefault = true,
                };

                var colModel = new ColumnModel(metadata, property);
                model.Columns.Add(colModel);
            }

            return(new FunctionResult(model, null, null));
        }
        public static bool GotoDeclaration()
        {
            ScintillaNet.ScintillaControl sci = PluginBase.MainForm.CurrentDocument.SciControl;
            if (sci == null)
            {
                return(false);
            }
            if (sci.ConfigurationLanguage != "xml")
            {
                return(false);
            }

            int pos = sci.CurrentPos;
            int len = sci.TextLength;

            while (pos < len)
            {
                char c = (char)sci.CharAt(pos);
                if (c <= 32 || c == '/' || c == '>')
                {
                    break;
                }
                pos++;
            }
            XMLContextTag ctag = XMLComplete.GetXMLContextTag(sci, pos);

            if (ctag.Name == null)
            {
                return(true);
            }
            string word = sci.GetWordFromPosition(sci.CurrentPos);

            string     type  = ResolveType(mxmlContext, ctag.Name);
            ClassModel model = context.ResolveType(type, mxmlContext.model);

            if (model.IsVoid()) // try resolving tag as member of parent tag
            {
                parentTag = XMLComplete.GetParentTag(sci, ctag);
                if (parentTag.Name != null)
                {
                    ctag  = parentTag;
                    type  = ResolveType(mxmlContext, ctag.Name);
                    model = context.ResolveType(type, mxmlContext.model);
                    if (model.IsVoid())
                    {
                        return(true);
                    }
                }
                else
                {
                    return(true);
                }
            }

            if (!ctag.Name.EndsWith(word))
            {
                ASResult found = ResolveAttribute(model, word);
                ASComplete.OpenDocumentToDeclaration(sci, found);
            }
            else
            {
                ASResult found = new ASResult();
                found.InFile = model.InFile;
                found.Type   = model;
                ASComplete.OpenDocumentToDeclaration(sci, found);
            }
            return(true);
        }
        private void CreateElements(IEnumerable <XmlSchemaElement> elements)
        {
            foreach (var rootElement in elements)
            {
                var rootSchema    = rootElement.GetSchema();
                var source        = CodeUtilities.CreateUri(rootSchema.SourceUri);
                var qualifiedName = rootElement.ElementSchemaType.QualifiedName;
                if (qualifiedName.IsEmpty)
                {
                    qualifiedName = rootElement.QualifiedName;
                }
                var type = CreateTypeModel(source, rootElement.ElementSchemaType, qualifiedName);

                if (type.RootElementName != null)
                {
                    if (type is ClassModel classModel)
                    {
                        // There is already another global element with this type.
                        // Need to create an empty derived class.

                        var derivedClassModel = new ClassModel(_configuration)
                        {
                            Name      = _configuration.NamingProvider.RootClassNameFromQualifiedName(rootElement.QualifiedName),
                            Namespace = CreateNamespaceModel(source, rootElement.QualifiedName)
                        };

                        derivedClassModel.Documentation.AddRange(GetDocumentation(rootElement));

                        if (derivedClassModel.Namespace != null)
                        {
                            derivedClassModel.Name = derivedClassModel.Namespace.GetUniqueTypeName(derivedClassModel.Name);
                            derivedClassModel.Namespace.Types[derivedClassModel.Name] = derivedClassModel;
                        }

                        var key = BuildKey(rootElement, rootElement.QualifiedName);
                        Types[key] = derivedClassModel;

                        derivedClassModel.BaseClass = classModel;
                        ((ClassModel)derivedClassModel.BaseClass).DerivedTypes.Add(derivedClassModel);

                        derivedClassModel.RootElementName = rootElement.QualifiedName;
                    }
                    else
                    {
                        var key = BuildKey(rootElement, rootElement.QualifiedName);
                        Types[key] = type;
                    }
                }
                else
                {
                    if (type is ClassModel classModel)
                    {
                        classModel.Documentation.AddRange(GetDocumentation(rootElement));
                        if (!rootElement.SubstitutionGroup.IsEmpty)
                        {
                            classModel.IsSubstitution   = true;
                            classModel.SubstitutionName = rootElement.QualifiedName;
                        }
                    }

                    type.RootElementName = rootElement.QualifiedName;
                }
            }
        }
 public void InsertClassTest()
 {
     var model = new ClassModel() {Id = 1, Name = "ClassName"};
     var result = _repository.Insert(model);
     Assert.IsTrue(result.Result);
 }
 public static void Build(OutputModel outputModel, ClassModel classModel, AttributeData attributeData) => classModel.PartitionDefinitionAttribute = new();
 private async Task<bool> Update(ClassModel classModel, int id)
 {
      return await _repository.Update(classModel, id);
 }
        private static bool GetTagAttributes(ClassModel tagClass, List <ICompletionListItem> mix, List <string> excludes, string ns)
        {
            ClassModel curClass    = mxmlContext.model.GetPublicClass();
            ClassModel tmpClass    = tagClass;
            FlagType   mask        = FlagType.Variable | FlagType.Setter;
            Visibility acc         = context.TypesAffinity(curClass, tmpClass);
            bool       isContainer = false;

            if (tmpClass.InFile.Package != "mx.builtin" && tmpClass.InFile.Package != "fx.builtin")
            {
                mix.Add(new HtmlAttributeItem("id", "String", null, ns));
            }
            else
            {
                isContainer = true;
            }

            while (tmpClass != null && !tmpClass.IsVoid())
            {
                string className = tmpClass.Name;
                // look for containers
                if (!isContainer && tmpClass.Implements != null &&
                    (tmpClass.Implements.Contains("IContainer") ||
                     tmpClass.Implements.Contains("IVisualElementContainer") ||
                     tmpClass.Implements.Contains("IFocusManagerContainer")))
                {
                    isContainer = true;
                }

                foreach (MemberModel member in tmpClass.Members)
                {
                    if ((member.Flags & FlagType.Dynamic) > 0 && (member.Flags & mask) > 0 &&
                        (member.Access & acc) > 0)
                    {
                        string mtype = member.Type;

                        if ((member.Flags & FlagType.Setter) > 0)
                        {
                            if (member.Parameters != null && member.Parameters.Count > 0)
                            {
                                mtype = member.Parameters[0].Type;
                            }
                            else
                            {
                                mtype = null;
                            }
                        }
                        mix.Add(new HtmlAttributeItem(member.Name, mtype, className, ns));
                    }
                }

                ExploreMetadatas(tmpClass.InFile, mix, excludes, ns);

                tmpClass = tmpClass.Extends;
                if (tmpClass != null && tmpClass.InFile.Package == "" && tmpClass.Name == "Object")
                {
                    break;
                }
                // members visibility
                acc = context.TypesAffinity(curClass, tmpClass);
            }

            return(isContainer);
        }
Beispiel #36
0
        void AddClass(ClassModel model)
        {
            foreach (var section in model.XmlCommentsModel.Sections)
            {
                foreach (var line in section.Replace(Environment.NewLine, "\n").Split('\n'))
                {
        #line default
        #line hidden

        #line 36 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write("    /// ");


        #line default
        #line hidden

        #line 37 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write(this.ToStringHelper.ToStringWithCulture(line));


        #line default
        #line hidden

        #line 37 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write("\r\n");


        #line default
        #line hidden

        #line 38 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                }
            }

            foreach (var tag in model.GetAttributeStereoType().Tags)
            {
        #line default
        #line hidden

        #line 43 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write("    [");


        #line default
        #line hidden

        #line 44 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(tag.Name));


        #line default
        #line hidden

        #line 44 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write("(");


        #line default
        #line hidden

        #line 44 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(tag.Value));


        #line default
        #line hidden

        #line 44 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(")]\r\n");


        #line default
        #line hidden

        #line 45 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            }

        #line default
        #line hidden

        #line 45 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            this.Write("    public partial ");


        #line default
        #line hidden

        #line 46 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            this.Write(this.ToStringHelper.ToStringWithCulture(model.IsAbstract ? "abstract " : ""));


        #line default
        #line hidden

        #line 46 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            this.Write("class ");


        #line default
        #line hidden

        #line 46 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            this.Write(this.ToStringHelper.ToStringWithCulture(model.ClassType.TypeName));


        #line default
        #line hidden

        #line 46 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            AddClassContracts(model);

        #line default
        #line hidden

        #line 46 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            this.Write("\r\n    {\r\n");


        #line default
        #line hidden

        #line 49 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"

            foreach (var property in model.Properties)
            {
                foreach (var section in property.XmlCommentsModel.Sections)
                {
                    foreach (var line in section.Replace(Environment.NewLine, "\n").Split('\n'))
                    {
        #line default
        #line hidden

        #line 56 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                        this.Write("        /// ");


        #line default
        #line hidden

        #line 57 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                        this.Write(this.ToStringHelper.ToStringWithCulture(line));


        #line default
        #line hidden

        #line 57 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                        this.Write("\r\n");


        #line default
        #line hidden

        #line 58 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    }
                }

                foreach (var tag in property.GetAttributeStereoType().Tags)
                {
        #line default
        #line hidden

        #line 63 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write("        [");


        #line default
        #line hidden

        #line 64 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write(this.ToStringHelper.ToStringWithCulture(tag.Name));


        #line default
        #line hidden

        #line 64 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write("(");


        #line default
        #line hidden

        #line 64 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write(this.ToStringHelper.ToStringWithCulture(tag.Value));


        #line default
        #line hidden

        #line 64 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                    this.Write(")]\r\n");


        #line default
        #line hidden

        #line 65 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                }

        #line default
        #line hidden

        #line 65 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write("        public ");


        #line default
        #line hidden

        #line 66 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(property.Type.FullName));


        #line default
        #line hidden

        #line 66 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(" ");


        #line default
        #line hidden

        #line 66 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(property.Name.ToPascalCase()));


        #line default
        #line hidden

        #line 66 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
                this.Write(" { get; set;}\r\n\r\n");


        #line default
        #line hidden

        #line 68 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            }

        #line default
        #line hidden

        #line 68 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            this.Write("    }\r\n\r\n");


        #line default
        #line hidden

        #line 71 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
            foreach (var child in model.ChildClasses)
            {
                AddClass(child);
            }


        #line default
        #line hidden

        #line 76 "C:\Dev\Intent\IntentArchitect\Modules\Intent.Modules.Application.Contracts\Legacy\DTO\GenericClassTemplate.tt"
        }
        public IEnumerable <MethodDeclarationSyntax> Create(IMethodModel method, ClassModel model)
        {
            if (method is null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var methodName = string.Format(CultureInfo.InvariantCulture, "{0}PerformsMapping", model.GetMethodUniqueName(method));

            var generatedMethod = _frameworkSet.TestFramework.CreateTestMethod(methodName, method.IsAsync, model.IsStatic);

            var paramExpressions = new List <CSharpSyntaxNode>();

            foreach (var parameter in method.Parameters)
            {
                if (parameter.Node.Modifiers.Any(x => x.Kind() == SyntaxKind.OutKeyword))
                {
                    paramExpressions.Add(SyntaxFactory.Argument(SyntaxFactory.DeclarationExpression(SyntaxFactory.IdentifierName(Strings.Create_var), SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(parameter.Name)))).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.OutKeyword)));
                }
                else
                {
                    var defaultAssignmentValue = AssignmentValueHelper.GetDefaultAssignmentValue(parameter.TypeInfo, model.SemanticModel, _frameworkSet);

                    generatedMethod = generatedMethod.AddBodyStatements(SyntaxFactory.LocalDeclarationStatement(
                                                                            SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName(Strings.Create_var))
                                                                            .WithVariables(SyntaxFactory.SingletonSeparatedList(
                                                                                               SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(parameter.Name))
                                                                                               .WithInitializer(SyntaxFactory.EqualsValueClause(defaultAssignmentValue))))));

                    if (parameter.Node.Modifiers.Any(x => x.Kind() == SyntaxKind.RefKeyword))
                    {
                        paramExpressions.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(parameter.Name)).WithRefKindKeyword(SyntaxFactory.Token(SyntaxKind.RefKeyword)));
                    }
                    else
                    {
                        paramExpressions.Add(SyntaxFactory.IdentifierName(parameter.Name));
                    }
                }
            }

            var methodCall = method.Invoke(model, false, _frameworkSet, paramExpressions.ToArray());

            bool requiresInstance = false;

            if (method.IsAsync)
            {
                if (model.SemanticModel.GetSymbolInfo(method.Node.ReturnType).Symbol is INamedTypeSymbol type)
                {
                    requiresInstance = type.TypeArguments.Any();
                }
            }
            else
            {
                requiresInstance = !method.IsVoid;
            }

            StatementSyntax bodyStatement;

            if (requiresInstance)
            {
                bodyStatement = SyntaxFactory.LocalDeclarationStatement(
                    SyntaxFactory.VariableDeclaration(
                        SyntaxFactory.IdentifierName(Strings.Create_var))
                    .WithVariables(
                        SyntaxFactory.SingletonSeparatedList(
                            SyntaxFactory.VariableDeclarator(
                                SyntaxFactory.Identifier(Strings.CanCallMethodGenerationStrategy_Create_result))
                            .WithInitializer(
                                SyntaxFactory.EqualsValueClause(methodCall)))));
            }
            else
            {
                bodyStatement = SyntaxFactory.ExpressionStatement(methodCall);
            }

            generatedMethod = generatedMethod.AddBodyStatements(bodyStatement);

            var returnTypeInfo = model.SemanticModel.GetTypeInfo(method.Node.ReturnType).Type;

            if (returnTypeInfo == null || returnTypeInfo.SpecialType != SpecialType.None || method.Node.IsKind(SyntaxKind.IndexerDeclaration) || (returnTypeInfo.ToFullName() == typeof(Task).FullName && !(returnTypeInfo is INamedTypeSymbol namedTypeSymbol && namedTypeSymbol.IsGenericType)))
            {
                yield break;
            }

            if (returnTypeInfo is INamedTypeSymbol namedType && namedType.IsGenericType && returnTypeInfo.ToFullName() == typeof(Task).FullName)
            {
                returnTypeInfo = namedType.TypeArguments[0];
            }

            var returnTypeMembers = GetProperties(returnTypeInfo);

            foreach (var methodParameter in method.Parameters)
            {
                if (returnTypeMembers.Contains(methodParameter.Name))
                {
                    var returnTypeMember = returnTypeMembers.FirstOrDefault(x => string.Equals(x, methodParameter.Name, StringComparison.OrdinalIgnoreCase));
                    var resultProperty   = Generate.PropertyAccess(SyntaxFactory.IdentifierName(Strings.CanCallMethodGenerationStrategy_Create_result), returnTypeMember);
                    generatedMethod = generatedMethod.AddBodyStatements(_frameworkSet.TestFramework.AssertEqual(resultProperty, SyntaxFactory.IdentifierName(methodParameter.Name)));
                    continue;
                }

                if (methodParameter.TypeInfo.Type.SpecialType == SpecialType.None && !Equals(methodParameter.TypeInfo.Type, returnTypeInfo))
                {
                    var properties = GetProperties(methodParameter.TypeInfo.Type);
                    foreach (var matchedSourceProperty in properties.Where(x => returnTypeMembers.Contains(x)))
                    {
                        var returnTypeMember = returnTypeMembers.FirstOrDefault(x => string.Equals(x, matchedSourceProperty, StringComparison.OrdinalIgnoreCase));
                        var resultProperty   = Generate.PropertyAccess(SyntaxFactory.IdentifierName(Strings.CanCallMethodGenerationStrategy_Create_result), returnTypeMember);
                        generatedMethod = generatedMethod.AddBodyStatements(_frameworkSet.TestFramework.AssertEqual(resultProperty, Generate.PropertyAccess(SyntaxFactory.IdentifierName(methodParameter.Name), matchedSourceProperty)));
                    }
                }
            }

            yield return(generatedMethod);
        }
        public ClassControl(ClassModel model)
        {
            Model = model;

            InitializeComponent();
        }
Beispiel #39
0
        private void AddExtend(TreeNodeCollection tree, ClassModel aClass)
        {
            TreeNode folder = new TreeNode(TextHelper.GetString("Info.ExtendsNode"), ICON_FOLDER_CLOSED, ICON_FOLDER_OPEN);

            //if ((aClass.Flags & FlagType.TypeDef) > 0 && aClass.Members.Count == 0)
            //    folder.Text = "Defines"; // TODO need a better word I guess

            while (!string.IsNullOrEmpty(aClass.ExtendsType) 
                && aClass.ExtendsType != "Object" 
                && (!aClass.InFile.haXe || aClass.ExtendsType != "Dynamic"))
            {
                string extends = aClass.ExtendsType;
                aClass = aClass.Extends;
                if (!aClass.IsVoid()) extends = aClass.QualifiedName;
                if (extends.ToLower() == "void")
                    break;
                TreeNode extNode = new TreeNode(extends, ICON_TYPE, ICON_TYPE);
                extNode.Tag = "import";
                folder.Nodes.Add(extNode);
            }
            if (folder.Nodes.Count > 0) tree.Add(folder);
        }
        private static TypeDeclarationSyntax ApplyStrategies(bool withRegeneration, TypeDeclarationSyntax targetType, IFrameworkSet frameworkSet, ClassModel classModel)
        {
            targetType = new ClassDecorationStrategyFactory(frameworkSet).Apply(targetType, classModel);

            if (!classModel.IsSingleItem || classModel.Constructors.Any())
            {
                targetType = AddGeneratedItems(classModel, targetType, new ClassLevelGenerationStrategyFactory(frameworkSet), x => new[] { x }, withRegeneration);
            }

            if (classModel.Interfaces.Count > 0)
            {
                targetType = AddGeneratedItems(classModel, targetType, new InterfaceGenerationStrategyFactory(frameworkSet), x => new[] { x }, withRegeneration);
            }

            targetType = AddGeneratedItems(classModel, targetType, new MethodGenerationStrategyFactory(frameworkSet), x => x.Methods, withRegeneration);
            targetType = AddGeneratedItems(classModel, targetType, new OperatorGenerationStrategyFactory(frameworkSet), x => x.Operators, withRegeneration);
            targetType = AddGeneratedItems(classModel, targetType, new PropertyGenerationStrategyFactory(frameworkSet), x => x.Properties, withRegeneration);
            targetType = AddGeneratedItems(classModel, targetType, new IndexerGenerationStrategyFactory(frameworkSet), x => x.Indexers, withRegeneration);
            return(targetType);
        }
Beispiel #41
0
		/// <summary>
		/// (Re)Parse and cache a class file
		/// TODO  change to FileModel
		/// </summary>
		/// <param name="aClass">Class object</param>
		/// <returns>The class object</returns>
		public override ClassModel UpdateClass(ClassModel aClass)
		{
			/*if (aClass.InFile == null || !aClass.InFile.OutOfDate) 
				return aClass;
			
			// remove from cache
			if (!aClass.IsVoid())
				classes.Remove(aClass.ClassName);
			// (re)parse
			FileModel aFile = ASFileParser.ParseFile(aClass.InFile);
			aClass = aFile.GetPublicClass();
			// add to cache
			AddClassToCache(aClass);*/
			return aClass;
		}
        private static TypeDeclarationSyntax EnsureAllConstructorParametersHaveFields(IFrameworkSet frameworkSet, ClassModel classModel, TypeDeclarationSyntax targetType)
        {
            var setupMethod = frameworkSet.TestFramework.CreateSetupMethod(frameworkSet.GetTargetTypeName(classModel, true));

            BaseMethodDeclarationSyntax foundMethod = null, updatedMethod = null;

            if (setupMethod is MethodDeclarationSyntax methodSyntax)
            {
                updatedMethod = foundMethod = targetType.Members.OfType <MethodDeclarationSyntax>().FirstOrDefault(x => x.Identifier.Text == methodSyntax.Identifier.Text && x.ParameterList.Parameters.Count == 0);
            }
            else if (setupMethod is ConstructorDeclarationSyntax)
            {
                updatedMethod = foundMethod = targetType.Members.OfType <ConstructorDeclarationSyntax>().FirstOrDefault(x => x.ParameterList.Parameters.Count == 0);
            }

            if (foundMethod != null)
            {
                var parametersEmitted = new HashSet <string>();
                var allFields         = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                var fields = new List <FieldDeclarationSyntax>();
                foreach (var parameterModel in classModel.Constructors.SelectMany(x => x.Parameters))
                {
                    allFields.Add(classModel.GetConstructorParameterFieldName(parameterModel));
                }

                // generate fields for each constructor parameter that doesn't have an existing field
                foreach (var parameterModel in classModel.Constructors.SelectMany(x => x.Parameters))
                {
                    if (!parametersEmitted.Add(parameterModel.Name))
                    {
                        continue;
                    }

                    var fieldName = classModel.GetConstructorParameterFieldName(parameterModel);

                    var fieldExists = targetType.Members.OfType <FieldDeclarationSyntax>().Any(x => x.Declaration.Variables.Any(v => v.Identifier.Text == fieldName));

                    if (!fieldExists)
                    {
                        var variable = SyntaxFactory.VariableDeclaration(parameterModel.TypeInfo.ToTypeSyntax(frameworkSet.Context))
                                       .AddVariables(SyntaxFactory.VariableDeclarator(fieldName));
                        var field = SyntaxFactory.FieldDeclaration(variable)
                                    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword));

                        fields.Add(field);

                        var defaultExpression = AssignmentValueHelper.GetDefaultAssignmentValue(parameterModel.TypeInfo, classModel.SemanticModel, frameworkSet);

                        var statement = SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(fieldName), defaultExpression));

                        var body = updatedMethod.Body ?? SyntaxFactory.Block();

                        SyntaxList <StatementSyntax> newStatements;
                        var index = body.Statements.LastIndexOf(x => x.DescendantNodes().OfType <AssignmentExpressionSyntax>().Any(a => a.Left is IdentifierNameSyntax identifierName && allFields.Contains(identifierName.Identifier.Text)));
                        if (index >= 0 && index < body.Statements.Count - 1)
                        {
                            newStatements = body.Statements.Insert(index + 1, statement);
                        }
                        else
                        {
                            newStatements = body.Statements.Add(statement);
                        }

                        updatedMethod = updatedMethod.WithBody(body.WithStatements(newStatements));
                    }
                }

                if (fields.Any())
                {
                    targetType = targetType.ReplaceNode(foundMethod, updatedMethod);
                    var existingField = targetType.Members.OfType <FieldDeclarationSyntax>().LastOrDefault();
                    if (existingField != null)
                    {
                        targetType = targetType.InsertNodesAfter(existingField, fields);
                    }
                    else
                    {
                        targetType = targetType.AddMembers(fields.OfType <MemberDeclarationSyntax>().ToArray());
                    }
                }
            }

            return(targetType);
        }
Beispiel #43
0
		/// <summary>
		/// Resolve wildcards in imports
		/// TODO  change to FileModel
		/// </summary>
		/// <param name="package">Package to explore</param>
		/// <param name="inClass">Current class</param>
		/// <param name="known">Packages already added</param>
		public override void ResolveImports(string package, ClassModel inClass, ArrayList known)
		{
			string subpath;
			string path;
			string[] files;
			
			// validation
			if ((package == null) || (inClass == null)) return;
			subpath = package.Replace(".", dirSeparator);
			
			// search in classpath
			MemberModel newImport;
			string basepath = "";
			foreach(PathModel aPath in classPath)
			try
			{
				basepath = aPath.Path;
				if (System.IO.Directory.Exists(basepath+subpath))
				{
					path = basepath+subpath;
					DebugConsole.Trace("Search "+path);
					files = System.IO.Directory.GetFiles(path, "*.as");
					if (files == null) 
						continue;
					// add classes found
					int plen = basepath.Length;
					foreach(string file in files)
					{
						package = file.Substring(plen,file.Length-3-plen).Replace(dirSeparator,".");
						if (known.Contains(package))
							continue;
						known.Add(package);
						//
						newImport = new MemberModel();
						newImport.Name = GetLastStringToken(package, ".");
						newImport.Type = package;
						inClass.InFile.Imports.Add(newImport);
					}
				}
			}
			catch(Exception ex)
			{
				ErrorHandler.ShowError(ex.Message+"\n"+basepath+subpath, ex);
			}
		}
        private static TypeDeclarationSyntax GetOrCreateTargetType(SyntaxNode sourceSymbol, SyntaxNode targetNamespace, IFrameworkSet frameworkSet, ClassModel classModel, out TypeDeclarationSyntax originalTargetType)
        {
            TypeDeclarationSyntax targetType = null;

            originalTargetType = null;

            if (targetNamespace != null && sourceSymbol != null)
            {
                var types = TestableItemExtractor.GetTypeDeclarations(targetNamespace);

                var targetClassName = frameworkSet.GetTargetTypeName(classModel, true);
                originalTargetType = targetType = types.FirstOrDefault(x => string.Equals(x.GetClassName(), targetClassName, StringComparison.OrdinalIgnoreCase));

                if (originalTargetType == null)
                {
                    targetClassName    = frameworkSet.GetTargetTypeName(classModel, false);
                    originalTargetType = targetType = types.FirstOrDefault(x => string.Equals(x.GetClassName(), targetClassName, StringComparison.OrdinalIgnoreCase));
                }
            }

            if (targetType == null)
            {
                targetType = new ClassGenerationStrategyFactory(frameworkSet).CreateFor(classModel);
            }
            else
            {
                targetType = EnsureAllConstructorParametersHaveFields(frameworkSet, classModel, targetType);
            }

            return(targetType);
        }
Beispiel #45
0
 private void AddExtend(TreeNodeCollection tree, ClassModel aClass)
 {
     TreeNode folder = new TreeNode(TextHelper.GetString("Info.ExtendsNode"), ICON_FOLDER_CLOSED, ICON_FOLDER_OPEN);
     //aClass.ResolveExtends();
     while (aClass.ExtendsType != null && aClass.ExtendsType.Length > 0
         && aClass.ExtendsType != "Object"
         && (!aClass.InFile.haXe || aClass.ExtendsType != "Dynamic"))
     {
         string extends = aClass.ExtendsType;
         aClass = aClass.Extends;
         if (!aClass.IsVoid()) extends = aClass.QualifiedName;
         if (extends.ToLower() == "void")
             break;
         TreeNode extNode = new TreeNode(extends, ICON_TYPE, ICON_TYPE);
         extNode.Tag = "import";
         folder.Nodes.Add(extNode);
     }
     if (folder.Nodes.Count > 0) tree.Add(folder);
 }
Beispiel #46
0
 private IFileModel GenerateFile(ClassModel model) =>
 model.Type switch
 {