Esempio n. 1
0
        public ProviderInfo()
        {
            MappingSet = new MappingSetImpl(new Database("New Database", ArchAngel.Providers.EntityModel.Controller.DatabaseLayer.DatabaseTypes.SQLServer2005), new EntitySetImpl());

            Name        = "Entity Provider";
            Description = "A Provider that allows mapping between Database Tables/Views/StoredProcedures and Entities";

            //if (ArchAngel.Interfaces.SharedData.CurrentProject.Options.SingleOrDefault(o => o.VariableName == "abc") == null)
            //{
            //    ArchAngel.Interfaces.SharedData.CurrentProject.Options.Add(new ArchAngel.Interfaces.TemplateInfo.Option()
            //    {
            //        Category = "C#",
            //        DefaultValue = "false",
            //        DefaultValueIsFunction = false,
            //        Description = "Include foreign-key?",
            //        DisplayToUserValue = true,
            //        Enabled = true,
            //        ResetPerSession = false,
            //        Text = "Include the foreign-key column in the model?",
            //        VarType = typeof(bool),
            //        VariableName = "IncludeForeignKeyColumn",
            //        IteratorName = "ArchAngel.Providers.EntityModel.Model.EntityLayer.Reference"
            //    });
            //}
            this.OptionForms.Add(new UI.PropertyGrids.FormPrefixes());
        }
Esempio n. 2
0
        /// <summary>
        /// Creates one Entity per database table, and one Reference per database relationship.
        /// It then looks for association tables and maps them correctly. 
        /// </summary>
        /// <param name="database"></param>
        /// <returns></returns>
        public MappingSet CreateOneToOneMapping(IDatabase database, List<string> tablePrefixes, List<string> columnPrefixes, List<string> tableSuffixes, List<string> columnSuffixes)
        {
            EntitySet entitySet = new EntitySetImpl();
            MappingSet set = new MappingSetImpl(database, entitySet);
            set.TablePrefixes = tablePrefixes;
            set.ColumnPrefixes = columnPrefixes;
            set.TableSuffixes = tableSuffixes;
            set.ColumnSuffixes = columnSuffixes;
            entitySet.MappingSet = set;

            ArchAngel.Interfaces.ProjectOptions.ModelScripts.Scripts.ExistingEntityNames = new List<string>();
            ArchAngel.Interfaces.ProjectOptions.ModelScripts.Scripts.TablePrefixes = (List<string>)tablePrefixes;
            ArchAngel.Interfaces.ProjectOptions.ModelScripts.Scripts.ColumnPrefixes = (List<string>)columnPrefixes;
            ArchAngel.Interfaces.ProjectOptions.ModelScripts.Scripts.TableSuffixes = (List<string>)tableSuffixes;
            ArchAngel.Interfaces.ProjectOptions.ModelScripts.Scripts.ColumnSuffixes = (List<string>)columnSuffixes;

            foreach (var table in database.Tables)
                ProcessTable(set, table);

            foreach (var view in database.Views)
                ProcessTable(set, view);

            foreach (var relationship in database.Relationships)
                ProcessRelationship(set, relationship);

            CreateManyToManyMappings(entitySet.Entities.ToList(), entitySet);
            return set;
        }
        public void The_Rule_Fails_But_Only_For_The_Parent()
        {
            var set = new MappingSetImpl();
            var parentEntity = new EntityImpl("Parent");
            var childEntity = new EntityImpl("Child");
            childEntity.Parent = parentEntity;
            var property = new PropertyImpl("Property1");
            parentEntity.AddProperty(property);
            set.EntitySet.AddEntity(parentEntity);
            set.EntitySet.AddEntity(childEntity);

            var table = new Table("Table1");
            var column = new Column("Column1");
            table.AddColumn(column);
            set.Database.AddTable(table);

            var rule = new CheckAllPropertiesMappedRule();
            var result = rule.Run(set);

            Assert.That(result.HasIssues);
            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Warning));
            Assert.That(issue.Object, Is.SameAs(property));
            StringAssert.Contains("Property1", issue.Description);
            StringAssert.Contains("Parent", issue.Description);
        }
Esempio n. 4
0
        public ProviderInfo()
        {
            MappingSet = new MappingSetImpl(new Database("New Database", ArchAngel.Providers.EntityModel.Controller.DatabaseLayer.DatabaseTypes.SQLServer2005), new EntitySetImpl());

            Name = "Entity Provider";
            Description = "A Provider that allows mapping between Database Tables/Views/StoredProcedures and Entities";

            //if (ArchAngel.Interfaces.SharedData.CurrentProject.Options.SingleOrDefault(o => o.VariableName == "abc") == null)
            //{
            //    ArchAngel.Interfaces.SharedData.CurrentProject.Options.Add(new ArchAngel.Interfaces.TemplateInfo.Option()
            //    {
            //        Category = "C#",
            //        DefaultValue = "false",
            //        DefaultValueIsFunction = false,
            //        Description = "Include foreign-key?",
            //        DisplayToUserValue = true,
            //        Enabled = true,
            //        ResetPerSession = false,
            //        Text = "Include the foreign-key column in the model?",
            //        VarType = typeof(bool),
            //        VariableName = "IncludeForeignKeyColumn",
            //        IteratorName = "ArchAngel.Providers.EntityModel.Model.EntityLayer.Reference"
            //    });
            //}
            this.OptionForms.Add(new UI.PropertyGrids.FormPrefixes());
        }
Esempio n. 5
0
        public override void Clear()
        {
            MappingSet = new MappingSetImpl(new Database("New Database", ArchAngel.Providers.EntityModel.Controller.DatabaseLayer.DatabaseTypes.Unknown), new EntitySetImpl());

            if (editModelScreen != null)
            {
                editModelScreen.SetMappingSet(MappingSet);
            }
        }
        public void The_Rule_Fails()
        {
            var mappingSet = new MappingSetImpl();
            var rule = new CheckEntityInheritanceForTablePerSubclassRule();
            var result = rule.Run(mappingSet);

            Assert.That(result.HasWarnings, Is.True);
            Assert.That(result.Issues[0].ErrorLevel, Is.EqualTo(ValidationErrorLevel.Warning));
        }
        public void It_Should_Serialise_To_This()
        {
            var set = new MappingSetImpl();
            set.AddMapping(When_Serialising_A_Mapping_With_All_Fields_Set.GetMapping());
            set.AddMapping(When_Serialising_A_ReferenceMapping_With_All_Fields_Set.GetMapping());

            string outputXML = new MappingSetSerialisationScheme().SerialiseMappingSet(set);
            outputXML = XmlSqueezer.RemoveWhitespaceBetweenElements(outputXML);
            Assert.That(outputXML, Is.EqualTo(FullMappingSetXml));
        }
Esempio n. 8
0
        public static MappingSet SetupModel()
        {
            MappingSet ms = new MappingSetImpl();

            SetupDatabase(ms.Database);
            SetupEntities(ms.EntitySet);

            SetupMappings(ms);

            return ms;
        }
Esempio n. 9
0
        public void It_Is_Deleted()
        {
            MappingSet ms = new MappingSetImpl();
            Mapping m = new MappingImpl();
            ms.AddMapping(m);

            Assert.That(ms.Mappings.Contains(m));

            m.Delete();

            Assert.That(ms.Mappings.Contains(m) == false);
        }
        public void The_Rule_Fails()
        {
            var set = new MappingSetImpl();
            var emptyEntity = new Table("");
            set.Database.AddTable(emptyEntity);

            DatabaseNamingRule rule = new DatabaseNamingRule();
            var result = rule.Run(set);

            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Error));
            Assert.That(issue.Object, Is.SameAs(emptyEntity));
            StringAssert.Contains("name", issue.Description);
        }
        public void SetUp()
        {
            mappingSet = new MappingSetImpl();
            engine = new ValidationRulesEngine(mappingSet);

            rule1 = MockRepository.GenerateMock<IValidationRule>();
            rule2 = MockRepository.GenerateMock<IValidationRule>();
            result1 = new ValidationResult(rule1);
            result2 = new ValidationResult(rule2);

            rule1.Stub(r => r.Run(mappingSet)).Return(result1);
            rule2.Stub(r => r.Run(mappingSet)).Return(result2);

            engine.AddRule(rule1);
            engine.AddRule(rule2);
        }
        public void Form_Is_Set_Up()
        {
            IComponentSpecificationForm form = MockRepository.GenerateMock<IComponentSpecificationForm>();
            IMainPanel panel = MockRepository.GenerateMock<IMainPanel>();

            var mappingSet = new MappingSetImpl();
            var entity = new EntityImpl("Entity1");
            entity.AddProperty(new PropertyImpl("Property1"));
            var table = new Table("Table1");
            table.AddColumn(new Column("Column1"));
            table.AddColumn(new Column("Street"));
            mappingSet.EntitySet.AddEntity(entity);

            mappingSet.ChangeMappedColumnFor(entity.Properties.First()).To(table.Columns[0]);

            ComponentSpecification spec = new ComponentSpecificationImpl("Address");
            spec.AddProperty(new ComponentPropertyImpl("Street"));
            Component component = spec.CreateImplementedComponentFor(entity, "Street");
            mappingSet.EntitySet.AddComponentSpecification(spec);

            var mapping = new ComponentMappingImpl {ToComponent = component, FromTable = table};
            mapping.AddPropertyAndColumn(component.Properties[0], table.Columns[0]);
            mappingSet.AddMapping(mapping);

            form.Expect(f => f.SetProperties(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<ComponentProperty>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            form.Expect(f => f.SetUsages(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Entity>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            form.Expect(f => f.SetFullEntityList(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Entity>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            ComponentSpecificationPresenter presenter = new ComponentSpecificationPresenter(panel, form);
            presenter.AttachToModel(spec);

            form.AssertWasCalled(f => f.Clear());
            form.AssertWasCalled(f => f.SpecName = spec.Name);
            form.AssertWasCalled(f => f.SetVirtualProperties(spec.Ex));

            form.VerifyAllExpectations();
        }
        public void The_Rule_Does_Not_Identify_It_As_A_Duplicate_Property()
        {
            var set = new MappingSetImpl();
            var parent = new EntityImpl("Entity1");
            var child = new EntityImpl("Entity2");
            set.EntitySet.AddEntity(parent);
            set.EntitySet.AddEntity(child);

            var property = new PropertyImpl("Property1");
            parent.AddProperty(property);
            child.Parent = parent;
            child.CopyPropertyFromParent(property);

            EntityNamingRule rule = new EntityNamingRule();
            var result = rule.Run(set);

            Assert.That(result.HasIssues, Is.False);
        }
        public void The_Rule_Passes()
        {
            var mappingSet = new MappingSetImpl();
            var parent = new EntityImpl("Parent");
            var child = new EntityImpl("Child");

            child.Parent = parent;
            var idProperty = new PropertyImpl("ID") { IsKeyProperty = true };
            parent.AddProperty(idProperty);
            child.CopyPropertyFromParent(idProperty);

            mappingSet.EntitySet.AddEntity(parent);
            mappingSet.EntitySet.AddEntity(child);

            var rule = new CheckEntityInheritanceForTablePerSubclassRule();
            var result = rule.Run(mappingSet);

            Assert.That(result.HasIssues, Is.False);
        }
        public void The_Rule_Fails()
        {
            var set = new MappingSetImpl();
            set.Database.AddTable(new Table("Table1"));
            set.Database.AddTable(new Table("Table2"));
            set.Database.Tables[0].AddKey(new Key("Key1"));
            var duplicate = new Key("Key1");
            set.Database.Tables[1].AddKey(duplicate);

            DatabaseNamingRule rule = new DatabaseNamingRule();
            var result = rule.Run(set);

            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Error));
            Assert.That(issue.Object, Is.SameAs(duplicate));
            StringAssert.Contains("Key1", issue.Description);
        }
        public void The_Rule_Passes()
        {
            var set = new MappingSetImpl();
            var entity = new EntityImpl("Entity1");
            var property = new PropertyImpl("Property1");
            entity.AddProperty(property);
            set.EntitySet.AddEntity(entity);

            var table = new Table("Table1");
            var column = new Column("Column1");
            table.AddColumn(column);
            set.Database.AddTable(table);

            set.ChangeMappedColumnFor(property).To(column);

            var rule = new CheckAllPropertiesMappedRule();
            var result = rule.Run(set);

            Assert.That(result.HasIssues, Is.False);
        }
        public void The_Rule_Fails()
        {
            var set = new MappingSetImpl();
            var entity1 = new EntityImpl("Entity1");
            var entity2 = new EntityImpl("Entity2");
            set.EntitySet.AddEntity(entity1);
            set.EntitySet.AddEntity(entity2);
            entity1.AddProperty(new PropertyImpl("Property1"));
            var reference = entity1.CreateReferenceTo(entity2);
            reference.End1Name = "Property1";

            EntityNamingRule rule = new EntityNamingRule();
            var result = rule.Run(set);

            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Error));
            Assert.That(issue.Object, Is.SameAs(reference));
            StringAssert.Contains("Property1", issue.Description);
        }
        public void The_Rule_Fails()
        {
            var mappingSet = new MappingSetImpl();
            var parent = new EntityImpl("Parent");
            var child = new EntityImpl("Child");

            child.Parent = parent;
            var idProperty = new PropertyImpl("ID") { IsKeyProperty = true };
            parent.AddProperty(idProperty);

            mappingSet.EntitySet.AddEntity(parent);
            mappingSet.EntitySet.AddEntity(child);

            var rule = new CheckEntityInheritanceForTablePerSubclassRule();
            var result = rule.Run(mappingSet);

            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.Object, Is.SameAs(child));
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Error));
            StringAssert.Contains("ID", issue.Description);
        }
Esempio n. 19
0
        public override void Clear()
        {
            MappingSet = new MappingSetImpl(new Database("New Database", ArchAngel.Providers.EntityModel.Controller.DatabaseLayer.DatabaseTypes.Unknown), new EntitySetImpl());

            if (editModelScreen != null)
                editModelScreen.SetMappingSet(MappingSet);
        }
        public MappingSet DeserialiseMappingSet(XmlNode mappingSetNode, IDatabase database, EntitySet entitySet)
        {
            var mappingSet = new MappingSetImpl(database, entitySet);
            var nodes      = mappingSetNode.SelectNodes("Mappings/Mapping");

            if (nodes != null)
            {
                foreach (XmlNode node in nodes)
                {
                    var mapping = DeserialiseMapping(node, database, entitySet);

                    if (mapping != null)
                    {
                        mappingSet.AddMapping(mapping);
                    }
                }
            }
            var refNodes = mappingSetNode.SelectNodes("ReferenceMappings/TableReferenceMapping");

            if (refNodes != null)
            {
                foreach (XmlNode node in refNodes)
                {
                    mappingSet.AddMapping(DeserialiseReferenceMapping(node, database, entitySet));
                }
            }

            var relationshipNodes = mappingSetNode.SelectNodes("ReferenceMappings/RelationshipReferenceMapping");

            if (relationshipNodes != null)
            {
                foreach (XmlNode node in relationshipNodes)
                {
                    RelationshipReferenceMapping relRefMapping = DeserialiseRelationshipMapping(node, database, entitySet);

                    if (relRefMapping != null)
                    {
                        mappingSet.AddMapping(relRefMapping);
                    }
                }
            }
            var componentNodes = mappingSetNode.SelectNodes("ComponentMappings/ComponentMapping");

            if (componentNodes != null)
            {
                foreach (XmlNode node in componentNodes)
                {
                    mappingSet.AddMapping(DeserialiseComponentMapping(node, database, entitySet));
                }
            }

            #region Table Prefixes
            var prefixNodes = mappingSetNode.SelectNodes("TablePrefixes/Prefix");

            if (prefixNodes != null)
            {
                foreach (XmlNode node in prefixNodes)
                {
                    mappingSet.TablePrefixes.Add(DeserialisePrefix(node));
                }
            }

            #endregion

            #region Column Prefixes
            prefixNodes = mappingSetNode.SelectNodes("ColumnPrefixes/Prefix");

            if (prefixNodes != null)
            {
                foreach (XmlNode node in prefixNodes)
                {
                    mappingSet.ColumnPrefixes.Add(DeserialisePrefix(node));
                }
            }

            #endregion

            #region Table Suffixes
            prefixNodes = mappingSetNode.SelectNodes("TableSuffixes/Suffix");

            if (prefixNodes != null)
            {
                foreach (XmlNode node in prefixNodes)
                {
                    mappingSet.TableSuffixes.Add(DeserialisePrefix(node));
                }
            }

            #endregion

            #region Column Prefixes
            prefixNodes = mappingSetNode.SelectNodes("ColumnSuffixes/Suffix");

            if (prefixNodes != null)
            {
                foreach (XmlNode node in prefixNodes)
                {
                    mappingSet.ColumnSuffixes.Add(DeserialisePrefix(node));
                }
            }

            #endregion

            ProcessScriptBase(mappingSet, mappingSetNode);
            return(mappingSet);
        }
        public void The_Rule_Passes()
        {
            var mappingSet = new MappingSetImpl();
            mappingSet.EntitySet.AddEntity(new EntityImpl("Entity1"));
            var rule = new CheckEntityInheritanceForTablePerSubclassRule();
            var result = rule.Run(mappingSet);

            Assert.That(result.HasIssues, Is.False);
        }
Esempio n. 22
0
 public MappingChanger(MappingSetImpl ms, Property property)
 {
     this.ms = ms;
     this.property = property;
 }
        public MappingSet DeserialiseMappingSet(XmlNode mappingSetNode, IDatabase database, EntitySet entitySet)
        {
            var mappingSet = new MappingSetImpl(database, entitySet);
            var nodes = mappingSetNode.SelectNodes("Mappings/Mapping");

            if (nodes != null)
                foreach (XmlNode node in nodes)
                {
                    var mapping = DeserialiseMapping(node, database, entitySet);

                    if (mapping != null)
                        mappingSet.AddMapping(mapping);
                }
            var refNodes = mappingSetNode.SelectNodes("ReferenceMappings/TableReferenceMapping");

            if (refNodes != null)
                foreach (XmlNode node in refNodes)
                    mappingSet.AddMapping(DeserialiseReferenceMapping(node, database, entitySet));

            var relationshipNodes = mappingSetNode.SelectNodes("ReferenceMappings/RelationshipReferenceMapping");

            if (relationshipNodes != null)
                foreach (XmlNode node in relationshipNodes)
                {
                    RelationshipReferenceMapping relRefMapping = DeserialiseRelationshipMapping(node, database, entitySet);

                    if (relRefMapping != null)
                        mappingSet.AddMapping(relRefMapping);
                }
            var componentNodes = mappingSetNode.SelectNodes("ComponentMappings/ComponentMapping");

            if (componentNodes != null)
                foreach (XmlNode node in componentNodes)
                    mappingSet.AddMapping(DeserialiseComponentMapping(node, database, entitySet));

            #region Table Prefixes
            var prefixNodes = mappingSetNode.SelectNodes("TablePrefixes/Prefix");

            if (prefixNodes != null)
                foreach (XmlNode node in prefixNodes)
                    mappingSet.TablePrefixes.Add(DeserialisePrefix(node));

            #endregion

            #region Column Prefixes
            prefixNodes = mappingSetNode.SelectNodes("ColumnPrefixes/Prefix");

            if (prefixNodes != null)
                foreach (XmlNode node in prefixNodes)
                    mappingSet.ColumnPrefixes.Add(DeserialisePrefix(node));

            #endregion

            #region Table Suffixes
            prefixNodes = mappingSetNode.SelectNodes("TableSuffixes/Suffix");

            if (prefixNodes != null)
                foreach (XmlNode node in prefixNodes)
                    mappingSet.TableSuffixes.Add(DeserialisePrefix(node));

            #endregion

            #region Column Prefixes
            prefixNodes = mappingSetNode.SelectNodes("ColumnSuffixes/Suffix");

            if (prefixNodes != null)
                foreach (XmlNode node in prefixNodes)
                    mappingSet.ColumnSuffixes.Add(DeserialisePrefix(node));

            #endregion

            ProcessScriptBase(mappingSet, mappingSetNode);
            return mappingSet;
        }
        public void The_Mapping_Should_Be_Deleted()
        {
            var m = new MappingImpl();
            var ms = new MappingSetImpl();

            ms.AddMapping(m);

            Assert.That(ms.Mappings.Contains(m), Is.True);
            //presenter.AttachToModel(m);

            form.Raise(f => f.RemoveMapping += null, form, new EventArgs());

            Assert.That(ms.Mappings.Contains(m), Is.False);
        }
 public MappingChanger(MappingSetImpl ms, Property property)
 {
     this.ms       = ms;
     this.property = property;
 }
        public void The_Rule_Fails()
        {
            var set = new MappingSetImpl();
            set.EntitySet.AddEntity(new EntityImpl("Entity1"));
            var duplicate = new EntityImpl("Entity1");
            set.EntitySet.AddEntity(duplicate);

            EntityNamingRule rule = new EntityNamingRule();
            var result = rule.Run(set);

            Assert.That(result.Issues, Has.Count(1));

            var issue = result.Issues[0];
            Assert.That(issue.ErrorLevel, Is.EqualTo(ValidationErrorLevel.Error));
            Assert.That(issue.Object, Is.SameAs(duplicate));
            StringAssert.Contains("Entity1", issue.Description);
        }
Esempio n. 27
0
        public MappingSet GetEntities(IEnumerable<string> hbmFiles, ParseResults parseResults, IDatabase database)
        {
            EntitySet entities = new EntitySetImpl();
            MappingSet mappingSet = new MappingSetImpl(database, entities);
            Dictionary<Class, ComponentSpecification> existingComponentSpecs = new Dictionary<Class, ComponentSpecification>();

            List<hibernatemapping> mappingFiles = new List<hibernatemapping>();
            List<ValidationEventArgs> mappingErrors = new List<ValidationEventArgs>();
            List<NHibernateLoaderException.HbmXmlFile> errorFiles = new List<NHibernateLoaderException.HbmXmlFile>();

            GetMappingFiles(hbmFiles, mappingFiles, mappingErrors, errorFiles);

            if (errorFiles.Count > 0)
                throw new NHibernateLoaderException(string.Format("Unsupported Elements found in HBM file."), errorFiles, mappingErrors);

            foreach (var hm in mappingFiles)
            {
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("AutoImport", hm.autoimport);
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("DefaultAccess", (TopLevelAccessTypes)Enum.Parse(typeof(TopLevelAccessTypes), hm.defaultaccess));
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("DefaultCascade", (TopLevelCascadeTypes)Enum.Parse(typeof(TopLevelCascadeTypes), hm.defaultcascade.Replace("-", "_"), true));
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("DefaultLazy", hm.defaultlazy);
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("ProjectNamespace", hm.@namespace);

                foreach (var hClass in hm.Classes())
                {
                    Entity newEntity;
                    string @namespace;
                    string name;

                    if (IsNameFullyQualified(hClass.name, out @namespace, out name))
                    {
                        newEntity = new EntityImpl(name);

                        string currentNamespace = ArchAngel.Interfaces.SharedData.CurrentProject.GetUserOption("ProjectNamespace") == null ? "" : ArchAngel.Interfaces.SharedData.CurrentProject.GetUserOption("ProjectNamespace").ToString();

                        if (string.IsNullOrWhiteSpace(currentNamespace))
                            ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("ProjectNamespace", @namespace);
                    }
                    else
                        newEntity = new EntityImpl(hClass.name);

                    if (entities.GetEntity(newEntity.Name) != null)
                        // This entity has already been added - the existing project probably has both HBM XML and Fluent mappings.
                        continue;

                    if (hClass.lazySpecified)
                        newEntity.SetEntityLazy(hClass.lazy);
                    else
                        newEntity.SetEntityLazy(hm.defaultlazy);

                    newEntity.SetEntitySqlWhereClause(hClass.where);
                    newEntity.SetEntityDynamicInsert(hClass.dynamicinsert);
                    newEntity.SetEntityDynamicUpdate(hClass.dynamicupdate);
                    newEntity.SetEntityMutable(hClass.mutable);
                    newEntity.SetEntityOptimisticLock((OptimisticLockModes)Enum.Parse(typeof(OptimisticLockModes), hClass.optimisticlock.ToString(), true));
                    newEntity.SetEntityProxy(hClass.proxy);
                    newEntity.SetEntitySelectBeforeUpdate(hClass.selectbeforeupdate);
                    newEntity.SetEntityBatchSize(hClass.batchsize);

                    if (hClass.abstractSpecified)
                        newEntity.IsAbstract = hClass.@abstract;

                    newEntity.SetEntityPersister(hClass.persister);
                    Mapping mapping = null;

                    if (!newEntity.IsAbstract)
                        mapping = CreateMappingFor(newEntity, hClass, database, hm.schema);

                    entities.AddEntity(newEntity);

                    if (mapping != null)
                        mappingSet.AddMapping(mapping);

                    #region Cache
                    if (hClass.cache != null)
                    {
                        newEntity.Cache = new Cache();

                        switch (hClass.cache.include)
                        {
                            case cacheInclude.all:
                                newEntity.Cache.Include = Cache.IncludeTypes.All;
                                break;
                            case cacheInclude.nonlazy:
                                newEntity.Cache.Include = Cache.IncludeTypes.Non_Lazy;
                                break;
                            default:
                                throw new NotImplementedException("Unexpected cache include value:" + hClass.cache.include.ToString());
                        }
                        newEntity.Cache.Region = hClass.cache.region;

                        switch (hClass.cache.usage)
                        {
                            case cacheUsage.nonstrictreadwrite:
                                newEntity.Cache.Usage = Cache.UsageTypes.NonStrict_Read_Write;
                                break;
                            case cacheUsage.@readonly:
                                newEntity.Cache.Usage = Cache.UsageTypes.Read_Only;
                                break;
                            case cacheUsage.readwrite:
                                newEntity.Cache.Usage = Cache.UsageTypes.Read_Write;
                                break;
                            case cacheUsage.transactional:
                                newEntity.Cache.Usage = Cache.UsageTypes.Transactional;
                                break;
                            default:
                                throw new NotImplementedException("Unexpected cache usage value:" + hClass.cache.usage.ToString());
                        }
                    }
                    #endregion

                    #region Discriminator
                    if (hClass.discriminator != null)
                    {
                        ArchAngel.Providers.EntityModel.Model.EntityLayer.Discriminator d = new Discriminator()
                        {
                            AllowNull = !hClass.discriminator.notnull,
                            ColumnName = hClass.discriminator.column,
                            DiscriminatorType = string.IsNullOrWhiteSpace(hClass.discriminator.column) ? ArchAngel.Providers.EntityModel.Model.Enums.DiscriminatorTypes.Formula : ArchAngel.Providers.EntityModel.Model.Enums.DiscriminatorTypes.Column,
                            Force = hClass.discriminator.force,
                            Formula = hClass.discriminator.formula,
                            Insert = hClass.discriminator.insert
                        };
                        newEntity.Discriminator = d;
                        newEntity.DiscriminatorValue = d.DiscriminatorType == Enums.DiscriminatorTypes.Column ? hClass.discriminator.column : hClass.discriminator.formula;

                        //string columnName = hClass.discriminator.column;

                        //throw new NotImplementedException("TODO: fixup discriminator stuff");
                        //Grouping g = new AndGrouping();
                        //IColumn column = newEntity.MappedTables().First().Columns.Single(c => c.Name == columnName);
                        //ArchAngel.Providers.EntityModel.Model.DatabaseLayer.Discrimination.Operator op = ArchAngel.Providers.EntityModel.Model.DatabaseLayer.Discrimination.Operator.Equal;
                        //string discriminatorValue = string.IsNullOrWhiteSpace(hClass.discriminatorvalue) ? "" : hClass.discriminatorvalue;

                        //ExpressionValue value = new ExpressionValueImpl(discriminatorValue);

                        //if (column != null && op != null && value != null)
                        //    g.AddCondition(new ConditionImpl(column, op, value));

                        //if (newEntity.Discriminator == null)
                        //    newEntity.Discriminator = new DiscriminatorImpl();

                        //newEntity.Discriminator.RootGrouping = g;
                    }
                    #endregion

                    ///////////////////////////////////////////////////
                    //foreach (var hProperty in hClass.Properties())
                    //{
                    //    var property = CreateProperty(newEntity, mapping, hProperty);
                    //    SetPropertyInfoFromParsedCode(property, parseResults, hm.@namespace, mapping.FromTable.Schema, hClass.name);
                    //}

                    //foreach (var hComponent in hClass.Components())
                    //{
                    //    ProcessComponent(hComponent, newEntity, mapping.FromTable, existingComponentSpecs, hm.@namespace, parseResults);
                    //}
                    ///////////////////////////////////////////////////
                    id hId = hClass.Id();

                    if (hId != null)
                    {
                        var idProperty = CreateProperty(newEntity, mapping, hId);
                        string schema = mapping == null ? null : mapping.FromTable.Schema;
                        SetPropertyInfoFromParsedCode(idProperty, parseResults, hm.@namespace, schema, hClass.name);
                        idProperty.IsKeyProperty = true;

                        if (hId.generator == null)
                            newEntity.Generator.ClassName = NHibernateHelper.MappingFiles.Version_2_2.GeneratorTypes.assigned.ToString();
                        else
                        {
                            newEntity.Generator.ClassName = hId.generator.@class;

                            if (hId.generator.param != null)
                                foreach (var param in hId.generator.param)
                                    newEntity.Generator.Parameters.Add(new EntityGenerator.Parameter(param.name, param.Text[0]));
                        }
                    }
                    else
                    {
                        compositeid hCompId = hClass.CompositeId();

                        if (hCompId != null)
                        {
                            // Check if this is a component. If so, we need to do some additional processing.
                            if (!string.IsNullOrEmpty(hCompId.@class))
                            {
                                bool keyResult = ProcessComponentKey(hCompId, newEntity, mapping.FromTable, existingComponentSpecs, hm.@namespace, parseResults);

                                if (keyResult == false)
                                {
                                    // Fallback to composite key generation, log failure.
                                    ProcessCompositeKey(hm, hClass, newEntity, mapping, parseResults, hCompId);
                                    log.ErrorFormat("Could not create a component for composite key {0}", hCompId.name);
                                }
                            }
                            else
                            {
                                // It is not a component.
                                ProcessCompositeKey(hm, hClass, newEntity, mapping, parseResults, hCompId);
                            }
                        }
                    }

                    foreach (var hProperty in hClass.Properties())
                    {
                        var property = CreateProperty(newEntity, mapping, hProperty);
                        string schema = mapping == null ? null : mapping.FromTable.Schema;
                        SetPropertyInfoFromParsedCode(property, parseResults, hm.@namespace, schema, hClass.name);

                        property.SetPropertyFormula(hProperty.formula);
                        property.SetPropertyGenerated((ArchAngel.Interfaces.NHibernateEnums.PropertyGeneratedTypes)Enum.Parse(typeof(ArchAngel.Interfaces.NHibernateEnums.PropertyGeneratedTypes), hProperty.generated.ToString()));

                        if (hProperty.insertSpecified)
                            property.SetPropertyInsert(hProperty.insert);

                        property.SetPropertyOptimisticLock(hProperty.optimisticlock);

                        if (hProperty.updateSpecified)
                            property.SetPropertyUpdate(hProperty.update);
                    }

                    foreach (var hComponent in hClass.Components())
                        ProcessComponent(hComponent, newEntity, mapping.FromTable, existingComponentSpecs, hm.@namespace, parseResults);

                    if (hClass.Version() != null)
                    {
                        // Create a property from the version node.
                        ProcessVersionProperty(hm, hClass, newEntity, mapping, parseResults);
                    }
                    ProcessSubclasses(mappingSet, database, entities, newEntity, hClass.SubClasses(), hClass.schema.UnBackTick(), hClass.table.UnBackTick(), parseResults, hm.@namespace);
                    ProcessJoinedSubclasses(mappingSet, database, entities, newEntity, hClass.JoinedSubClasses(), parseResults, hm.@namespace);
                    ProcessUnionSubclasses(hClass, mappingSet, database, entities, newEntity, hClass.UnionSubClasses(), parseResults, hm.@namespace);
                }
            }
            List<string> processedClassNames = new List<string>();

            // Second pass, to add missing foreign key columns and properties
            foreach (var hm in mappingFiles)
            {
                foreach (var hClass in hm.Classes())
                {
                    string className;

                    if (!IsNameFullyQualified(hClass.name, out className))
                        className = hClass.name;

                    if (processedClassNames.Contains(className))
                        continue;

                    processedClassNames.Add(className);

                    foreach (var hManyToOne in hClass.ManyToOnes())
                    {
                        var fkColumnNames = ReferenceLoader.GetColumnNames(hManyToOne.column, hManyToOne.Columns()).ToList();
                        Entity entity = entities.Entities.Single(e => e.Name == className);
                        bool found = false;

                        foreach (var prop in entity.Properties)
                        {
                            IColumn mappedColumn = prop.MappedColumn();

                            if (mappedColumn != null)
                            {
                                string mappedColumnName = null;

                                if (hManyToOne.column != null)
                                    mappedColumnName = hManyToOne.column;
                                else if (hManyToOne.Columns().Count > 0)
                                    mappedColumnName = hManyToOne.Columns()[0].name;

                                if (!string.IsNullOrEmpty(mappedColumnName) &&
                                    mappedColumn.Name == mappedColumnName.UnBackTick())
                                {
                                    found = true;
                                    break;
                                }
                            }
                            //else
                            //{
                            //    string gfh2 = string.Format("{0}.{1}", hClass.name, hManyToOne.column1.UnBackTick());
                            //    gfh2 = "";
                            //    // TODO: we should create a column for this property
                            //    Entity referencedEntity = entities.Entities.Single(e => e.Name == hManyToOne.@class);
                            //    Property referencedProperty = referencedEntity.Key.Properties.ElementAt(0);
                            //    IColumn tempColumn = referencedProperty.MappedColumn();

                            //    IColumn newColumn = ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor.CreateColumnFromProperty(referencedProperty);
                            //    newColumn.Name = hManyToOne.column1.UnBackTick();
                            //    ITable table = entity.MappedTables().First();
                            //    table.AddColumn(newColumn);
                            //    prop.SetMappedColumn(newColumn);
                            //}
                        }
                        if (!found)
                        {
                            string name;

                            string manyToOneClassName = hManyToOne.@class != null ? hManyToOne.@class : hManyToOne.name;
                            IsNameFullyQualified(manyToOneClassName, out name);
                            Entity referencedEntity = entities.Entities.Single(e => e.Name == name);
                            Property referencedProperty = referencedEntity.Key.Properties.ElementAt(0);
                            IColumn newColumn = null;

                            foreach (Table t in entity.MappedTables())
                            {
                                string colName = null;

                                if (hManyToOne.column != null)
                                    colName = hManyToOne.column;
                                else if (hManyToOne.Columns().Count > 0)
                                    colName = hManyToOne.Columns()[0].name;

                                newColumn = t.Columns.SingleOrDefault(c => !string.IsNullOrEmpty(colName) && c.Name == colName.UnBackTick());

                                if (newColumn != null)
                                    break;
                            }
                            if (newColumn == null)
                            {
                                newColumn = ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor.CreateColumnFromProperty(referencedProperty);
                                ITable table = entity.MappedTables().First();
                                table.AddColumn(newColumn);
                            }
                            Property newProperty = ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor.CreatePropertyFromColumn(newColumn);
                            //entity.Properties.SingleOrDefault(p => p.MappedColumn() ==
                            entity.AddProperty(newProperty);
                        }
                        //ITable table = entity.MappedTables().First();
                    }
                }
            }

            // Second pass, for references.
            var refProcessor = new ReferenceLoader();
            refProcessor.ProcessReferences(mappingFiles, mappingSet);

            processedClassNames.Clear();
            // Second pass, to add missing foreign key columns and properties
            foreach (var hm in mappingFiles)
            {
                foreach (var hClass in hm.Classes())
                {
                    string className;
                    IsNameFullyQualified(hClass.name, out className);

                    if (processedClassNames.Contains(className))
                        continue;

                    processedClassNames.Add(className);

                    foreach (var hManyToOne in hClass.ManyToOnes())
                    {
                        var fkColumnNames = ReferenceLoader.GetColumnNames(hManyToOne.column, hManyToOne.Columns()).ToList();
                        Entity entity = entities.Entities.Single(e => e.Name == className);

                        foreach (var prop in entity.Properties)
                        {
                            IColumn mappedColumn = prop.MappedColumn();

                            if (mappedColumn == null)
                            {
                                // TODO: we should create a column for this property
                                string manyToOneClassName;
                                IsNameFullyQualified(hManyToOne.@class, out manyToOneClassName);
                                Entity referencedEntity = entities.Entities.Single(e => e.Name == manyToOneClassName);
                                Property referencedProperty = referencedEntity.Key.Properties.ElementAt(0);
                                IColumn tempColumn = referencedProperty.MappedColumn();

                                IColumn newColumn = ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor.CreateColumnFromProperty(referencedProperty);

                                string newColName = "";

                                if (hManyToOne.column != null)
                                    newColName = hManyToOne.column;
                                else if (hManyToOne.Columns().Count > 0)
                                    newColName = hManyToOne.Columns()[0].name;

                                newColumn.Name = newColName.UnBackTick();
                                ITable table = entity.MappedTables().First();

                                if (table.Columns.Count(c => c.Name == newColumn.Name) == 0)
                                    table.AddColumn(newColumn);
                                else
                                    newColumn = table.Columns.First(c => c.Name == newColumn.Name);

                                prop.SetMappedColumn(newColumn);
                            }
                        }
                    }
                }
            }
            return mappingSet;
        }
        public static Reference GetReference()
        {
            Reference reference = new ReferenceImpl();

            var mappingSet = new MappingSetImpl();
            var entitySet = new EntitySetImpl();
            entitySet.AddReference(reference);
            mappingSet.EntitySet = entitySet;

            return reference;
        }
        public void The_Presenter_Fills_In_The_Form()
        {
            IMainPanel mainPanel = MockRepository.GenerateStub<IMainPanel>();
            IEntityForm form = MockRepository.GenerateMock<IEntityForm>();

            form.Expect(f => f.Mappings = null)
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Mapping>) action.Arguments[0]).Count(), Is.EqualTo(0)));
            form.Expect(f => f.SetAvailableTables(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<ITable>)action.Arguments[0]).Count(), Is.EqualTo(0)));

            form.Expect(f => f.SetProperties(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Property>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            form.Expect(f => f.SetAvailableEntities(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Entity>)action.Arguments[0]).Count(), Is.EqualTo(2)));

            form.Expect(f => f.SetChildEntities(null))
                .IgnoreArguments()
                .WhenCalled(action => Assert.That(((IEnumerable<Entity>)action.Arguments[0]).Count(), Is.EqualTo(1)));

            Entity parentEntity = new EntityImpl("Parent");
            Entity childEntity = new EntityImpl("Child");
            Property property = new PropertyImpl("Prop1");
            EntityKey key = new EntityKeyImpl();
            Entity entity = new EntityImpl("Entity1") { Key = key };
            entity.Parent = parentEntity;
            entity.AddChild(childEntity);
            entity.AddProperty(property);
            key.AddProperty(property);

            EntitySet es = new EntitySetImpl();
            es.AddEntity(parentEntity);
            es.AddEntity(entity);
            es.AddEntity(childEntity);
            MappingSet ms = new MappingSetImpl();
            ms.EntitySet = es;

            var presenter = new EntityPresenter(mainPanel, form);
            presenter.AttachToModel(entity);

            form.AssertWasCalled(f => f.EntityName = entity.Name);
            form.AssertWasCalled(f => f.Discriminator = entity.Discriminator);
            form.AssertWasCalled(f => f.ParentEntity = entity.Parent);
            form.AssertWasCalled(f => f.SetVirtualProperties(entity.Ex));
            form.VerifyAllExpectations();
        }
Esempio n. 30
0
        public MappingSet CreateOneToOneMapping(EntitySet entitySet)
        {
            IDatabase database = new Database("Database", ArchAngel.Providers.EntityModel.Controller.DatabaseLayer.DatabaseTypes.SQLServer2005);
            MappingSet set = new MappingSetImpl(database, entitySet);
            database.MappingSet = set;

            foreach (var entity in entitySet.Entities)
                ProcessEntity(set, entity);

            foreach (var entity in entitySet.Entities)
                PostProcessEntity(set, entity);

            foreach (var reference in entitySet.References)
                ProcessReference(set, reference);

            return set;
        }