Exemplo n.º 1
0
		void IModuleLink.AddModule(Module module)
		{
			var modules = ((IModuleLink)this).Modules.ToList();
			if (!modules.Contains(module))
			{
				this.ParentEntity.nHydrateModel.RelationModules.Add(new RelationModule(this.Partition) { RelationID = this.Id, ModuleId = module.Id });
			}
		}
Exemplo n.º 2
0
		void IModuleLink.RemoveModule(Module module)
		{
			var modules = ((IModuleLink)this).Modules.ToList();
			if (modules.Contains(module))
			{
				var o = this.ParentEntity.nHydrateModel.RelationModules.FirstOrDefault(x => x.RelationID == this.Id && x.ModuleId == module.Id);
				if (o != null)
					this.ParentEntity.nHydrateModel.RelationModules.Remove(o);
			}
		}
Exemplo n.º 3
0
		void IModuleLink.RemoveModule(Module module)
		{
			if (this.Modules.Contains(module))
				this.Modules.Remove(module);
		}
Exemplo n.º 4
0
		void IModuleLink.AddModule(Module module)
		{
			var modules = ((IModuleLink)this).Modules.ToList();
			if (!modules.Contains(module))
			{
				this.Entity.nHydrateModel.IndexModules.Add(new IndexModule(this.Partition) { IndexID = this.Id, ModuleId = module.Id });
			}
		}
Exemplo n.º 5
0
		void IModuleLink.AddModule(Module module)
		{
			if (!this.Modules.Contains(module))
				this.Modules.Add(module);
		}
Exemplo n.º 6
0
        private static void LoadFromDisk(IEnumerable<Module> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store)
        {
            var folder = rootFolder;
            if (!Directory.Exists(folder)) return;

            #region Load other parameter/field information
            var fileName = Path.Combine(folder, "modules.configuration.xml");
            if (!File.Exists(fileName)) return;
            XmlDocument document = null;
            try
            {
                document = new XmlDocument();
                document.Load(fileName);
            }
            catch (Exception ex)
            {
                //Do Nothing
                MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (XmlNode n in document.DocumentElement.ChildNodes)
            {
                var id = XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid());
                var item = model.Modules.FirstOrDefault(x => x.Id == id);
                if (item == null)
                {
                    item = new Module(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) });
                    model.Modules.Add(item);
                }

                item.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                item.Name = XmlHelper.GetAttributeValue(n, "name", item.Name);
                item.Summary = XmlHelper.GetNodeValue(n, "summary", item.Summary);
                item.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);

                //Rules
                var rulesNodes = n.SelectSingleNode("ruleset");
                if (rulesNodes != null)
                {
                    var nameList = new List<string>();
                    foreach (XmlNode m in rulesNodes.ChildNodes)
                    {
                        var rule = new ModuleRule(item.Partition);
                        item.ModuleRules.Add(rule);
                        rule.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                        rule.Name = XmlHelper.GetAttributeValue(m, "name", rule.Name);
                        rule.Status = (ModuleRuleStatusTypeConstants)int.Parse(XmlHelper.GetAttributeValue(m, "status", rule.Status.ToString("d")));
                        rule.DependentModule = XmlHelper.GetAttributeValue(m, "dependentmodule", rule.DependentModule);
                        rule.Inclusion = XmlHelper.GetAttributeValue(m, "inclusion", rule.Inclusion);
                        rule.Enforced = XmlHelper.GetAttributeValue(m, "enforced", rule.Enforced);
                        rule.Summary = XmlHelper.GetNodeValue(m, "summary", rule.Summary);
                        rule.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(FieldParameter_PropertyChanged);
                    }
                }

            }
            #endregion

        }
Exemplo n.º 7
0
        private nHydrate.Generator.Models.ModelRoot CreatePOCOModel(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, Module ownerModule)
        {
            try
            {
                var root = new nHydrate.Generator.Models.ModelRoot(null);
                root.TransformNames = model.TransformNames;
                root.EnableCustomChangeEvents = model.EmitChangeScripts;
                root.CompanyName = model.CompanyName;
                root.EmitSafetyScripts = model.EmitSafetyScripts;
                root.Copyright = model.Copyright;
                root.DefaultNamespace = model.DefaultNamespace;
                root.ProjectName = model.ProjectName;
                root.SQLServerType = (SQLServerTypeConstants)Enum.Parse(typeof(SQLServerTypeConstants), model.SQLServerType.ToString());
                root.EFVersion = (nHydrate.Generator.Common.GeneratorFramework.EFVersionConstants)Enum.Parse(typeof(nHydrate.Generator.Common.GeneratorFramework.EFVersionConstants), model.EFVersion.ToString());
                root.SupportLegacySearchObject = false;
                root.UseUTCTime = model.UseUTCTime;
                root.Version = model.Version;
                root.Database.UseGeneratedCRUD = model.UseGeneratedCRUD;
                root.Database.ResetKey(model.Id.ToString());
                root.OutputTarget = string.Empty; //model.OutputTarget;
                //These have the same mapping values flags so we need convert to int and then convert to the other enumeration
                root.TenantColumnName = model.TenantColumnName;
                root.TenantPrefix = model.TenantPrefix;
                root.AllowMocks = model.AllowMocks;

                foreach (var md in model.ModelMetadata)
                {
                    var newmd = new Generator.Models.MetadataItem();
                    newmd.Key = md.Key;
                    newmd.Value = md.Value;
                    root.MetaData.Add(newmd);
                }

                #region Set Refactorizations
                foreach (var r in model.Refactorizations)
                {
                    if (r is nHydrate.Dsl.Objects.RefactorTableSplit)
                    {
                        var newR = new nHydrate.Generator.Common.GeneratorFramework.RefactorTableSplit();
                        newR.EntityKey1 = (r as nHydrate.Dsl.Objects.RefactorTableSplit).EntityKey1;
                        newR.EntityKey2 = (r as nHydrate.Dsl.Objects.RefactorTableSplit).EntityKey2;
                        var flist = (r as nHydrate.Dsl.Objects.RefactorTableSplit).ReMappedFieldIDList;
                        foreach (var k in flist.Keys)
                            newR.ReMappedFieldIDList.Add(k, flist[k]);
                        root.Refactorizations.Add(newR);
                    }
                    else if (r is nHydrate.Dsl.Objects.RefactorTableCombine)
                    {
                        var newR = new nHydrate.Generator.Common.GeneratorFramework.RefactorTableCombine();
                        newR.EntityKey1 = (r as nHydrate.Dsl.Objects.RefactorTableCombine).EntityKey1;
                        newR.EntityKey2 = (r as nHydrate.Dsl.Objects.RefactorTableCombine).EntityKey2;
                        var flist = (r as nHydrate.Dsl.Objects.RefactorTableCombine).ReMappedFieldIDList;
                        foreach (var k in flist.Keys)
                            newR.ReMappedFieldIDList.Add(k, flist[k]);
                        root.Refactorizations.Add(newR);
                    }
                }
                #endregion

                if (ownerModule != null)
                    root.ModuleName = ownerModule.Name;

                root.Database.CreatedByColumnName = model.CreatedByColumnName;
                root.Database.CreatedDateColumnName = model.CreatedDateColumnName;
                root.Database.ModifiedByColumnName = model.ModifiedByColumnName;
                root.Database.ModifiedDateColumnName = model.ModifiedDateColumnName;
                root.Database.TimestampColumnName = model.TimestampColumnName;
                root.Database.GrantExecUser = model.GrantUser;
                root.Database.Collate = model.Collate;

                root.Database.PrecedenceOrderList = PrecedenceUtil.GetAllPrecedenceItems(model)
                    .Select(x => x.ID)
                    .ToList();

                var inheritanceConnectors = diagram.NestedChildShapes.Where(x => x is EntityInheritanceConnector).Cast<EntityInheritanceConnector>().ToList();

                #region Load the entities
                foreach (var entity in model.Entities.Where(x => x.IsGenerated).Where(x => ownerModule == null || x.Modules.Contains(ownerModule)))
                {
                    #region Table Info
                    var newTable = root.Database.Tables.Add();
                    newTable.ResetKey(entity.Id.ToString());
                    newTable.ResetId(HashString(newTable.Key));
                    newTable.AllowAuditTracking = entity.AllowAuditTracking;
                    newTable.AllowCreateAudit = entity.AllowCreateAudit;
                    newTable.AllowModifiedAudit = entity.AllowModifyAudit;
                    newTable.AllowTimestamp = entity.AllowTimestamp;
                    newTable.AssociativeTable = entity.IsAssociative;
                    newTable.CodeFacade = entity.CodeFacade;
                    newTable.DBSchema = entity.Schema;
                    newTable.Description = entity.Summary;
                    newTable.EnforcePrimaryKey = entity.EnforcePrimaryKey;
                    newTable.Generated = entity.IsGenerated;
                    newTable.Immutable = entity.Immutable;
                    newTable.TypedTable = (nHydrate.Generator.Models.TypedTableConstants)Enum.Parse(typeof(nHydrate.Generator.Models.TypedTableConstants), entity.TypedEntity.ToString(), true);
                    newTable.Name = entity.Name;
                    newTable.GeneratesDoubleDerived = entity.GeneratesDoubleDerived;
                    newTable.IsTenant = entity.IsTenant;

                    //Add metadata
                    foreach (var md in entity.EntityMetadata)
                    {
                        newTable.MetaData.Add(new nHydrate.Generator.Models.MetadataItem() { Key = md.Key, Value = md.Value });
                    }

                    if (entity.SecurityFunction != null)
                    {
                        newTable.Security.ResetKey(entity.SecurityFunction.Id.ToString());
                        newTable.Security.SQL = entity.SecurityFunction.SQL;

                        //Just in case these are ordered get all sort-ordered parameters first then take on all unordred alphabetized parmameters
                        var orderedParameters = entity.SecurityFunction.SecurityFunctionParameters.Where(x => x.SortOrder > 0).OrderBy(x => x.SortOrder).ToList();
                        orderedParameters.AddRange(entity.SecurityFunction.SecurityFunctionParameters.Where(x => x.SortOrder == 0).OrderBy(x => x.Name).ToList());
                        foreach (var parameter in orderedParameters)
                        {
                            var newParameter = root.Database.FunctionParameters.Add();
                            newParameter.ResetKey(parameter.Id.ToString());
                            newParameter.ResetId(HashString(newParameter.Key));
                            newParameter.ParentTableRef = newTable.CreateRef(newTable.Key);
                            newParameter.AllowNull = parameter.Nullable;
                            newParameter.CodeFacade = parameter.CodeFacade;
                            newParameter.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), parameter.DataType.ToString());
                            newParameter.Default = parameter.Default;
                            newParameter.Description = parameter.Summary;
                            newParameter.Generated = parameter.IsGenerated;
                            newParameter.Length = parameter.Length;
                            newParameter.Name = parameter.Name;
                            newParameter.Scale = parameter.Scale;
                            newParameter.SortOrder = parameter.SortOrder;

                            var r = newParameter.CreateRef(newParameter.Key);
                            r.RefType = nHydrate.Generator.Models.ReferenceType.FunctionParameter;
                            newTable.Security.Parameters.Add(r);
                        }

                    }

                    #endregion

                    #region Load the fields for this entity
                    var fieldList = entity.Fields.Where(x => x.IsGenerated).Where(x => ownerModule == null || x.Modules.Contains(ownerModule)).ToList();
                    foreach (var field in fieldList.OrderBy(x => x.SortOrder))
                    {
                        var newColumn = root.Database.Columns.Add();
                        newColumn.ResetKey(field.Id.ToString());
                        newColumn.ResetId(HashString(newColumn.Key));
                        newColumn.AllowNull = field.Nullable;
                        newColumn.Collate = field.Collate;
                        newColumn.CodeFacade = field.CodeFacade;
                        newColumn.ComputedColumn = field.IsCalculated;
                        newColumn.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString());
                        newColumn.Default = field.Default;
                        newColumn.DefaultIsFunc = field.DefaultIsFunc;
                        newColumn.Description = field.Summary;
                        newColumn.Formula = field.Formula;
                        newColumn.FriendlyName = field.FriendlyName;
                        newColumn.Generated = field.IsGenerated;
                        newColumn.Identity = (nHydrate.Generator.Models.IdentityTypeConstants)Enum.Parse(typeof(nHydrate.Generator.Models.IdentityTypeConstants), field.Identity.ToString());
                        newColumn.IsIndexed = field.IsIndexed;
                        newColumn.IsReadOnly = field.IsReadOnly;
                        newColumn.IsUnique = field.IsUnique;
                        newColumn.Length = field.Length;
                        newColumn.Max = field.Max;
                        newColumn.Min = field.Min;
                        newColumn.Name = field.Name;
                        newColumn.ParentTableRef = newTable.CreateRef(newTable.Key);
                        newColumn.PrimaryKey = field.IsPrimaryKey;
                        newColumn.Scale = field.Scale;
                        newColumn.ValidationExpression = field.ValidationExpression;
                        newColumn.IsBrowsable = field.IsBrowsable;
                        newColumn.Category = field.Category;
                        newColumn.SortOrder = field.SortOrder;
                        newColumn.Mask = field.DataFormatString;
                        newColumn.UIDataType = (System.ComponentModel.DataAnnotations.DataType)Enum.Parse(typeof(System.ComponentModel.DataAnnotations.DataType), field.UIDataType.ToString(), true);
                        newColumn.Obsolete = field.Obsolete;
                        newTable.Columns.Add(newColumn.CreateRef(newColumn.Key));

                        //Add metadata
                        foreach (var md in field.FieldMetadata)
                        {
                            newColumn.MetaData.Add(new nHydrate.Generator.Models.MetadataItem() { Key = md.Key, Value = md.Value });
                        }

                    }
                    #endregion

                    #region Indexes

                    //Find all index for this entity in module
                    List<Index> indexList = null;
                    if (ownerModule != null)
                    {
                        indexList = new List<Index>();
                        indexList.AddRange(entity.Indexes.Where(x => x.IndexType == IndexTypeConstants.PrimaryKey).ToList());
                        foreach (var im in model.IndexModules.Where(x => x.ModuleId == ownerModule.Id))
                        {
                            indexList.AddRange(entity.Indexes.Where(x => x.IndexType != IndexTypeConstants.PrimaryKey && x.Id == im.IndexID));
                        }
                    }
                    else
                    {
                        indexList = entity.Indexes.ToList();
                    }

                    foreach (var index in indexList)
                    {
                        var indexColumns = index.IndexColumns.Where(x => x.GetField() != null && (ownerModule == null || x.GetField().Modules.Contains(ownerModule))).ToList();
                        if (indexColumns.Count > 0)
                        {
                            var newIndex = new nHydrate.Generator.Models.TableIndex(newTable.Root)
                            {
                                Description = index.Summary,
                                IsUnique = index.IsUnique,
                                Clustered = index.Clustered,
                                PrimaryKey = (index.IndexType == IndexTypeConstants.PrimaryKey)
                            };
                            newTable.TableIndexList.Add(newIndex);
                            newIndex.ResetKey(index.Id.ToString());
                            newIndex.ResetId(HashString(newIndex.Key));
                            newIndex.ImportedName = index.ImportedName;

                            //Add index columns
                            foreach (var ic in indexColumns.OrderBy(x => x.SortOrder).ThenBy(x => x.GetField().Name))
                            {
                                var field = ic.GetField();
                                var newColumn = new nHydrate.Generator.Models.TableIndexColumn(newTable.Root) { Ascending = ic.Ascending, FieldID = field.Id };
                                newIndex.IndexColumnList.Add(newColumn);
                            }
                        }
                    }

                    #endregion

                    #region Composites
                    foreach (var composite in entity.Composites.Where(x => x.IsGenerated))
                    {
                        var newComponent = new nHydrate.Generator.Models.TableComponent(newTable.ComponentList.Root, newTable.ComponentList.Parent);
                        newComponent.ResetKey(composite.Id.ToString());
                        //newComponent.ResetId(HashString(newComponent.Key));
                        newComponent.CodeFacade = composite.CodeFacade;
                        newComponent.Description = composite.Summary;
                        newComponent.Generated = composite.IsGenerated;
                        newComponent.Name = composite.Name;
                        newTable.ComponentList.Add(newComponent);

                        foreach (var column in composite.Fields)
                        {
                            var oldColumn = entity.Fields.FirstOrDefault(x => x.Id == column.Id);
                            if (oldColumn != null)
                            {
                                var newColumn = newTable.GetColumns().FirstOrDefault(x => x.Name == oldColumn.Name);
                                if (newColumn != null)
                                {
                                    newColumn.ResetKey(column.Id.ToString());
                                    newColumn.ResetId(HashString(newColumn.Key));
                                    newComponent.Columns.Add(newColumn.CreateRef(newColumn.Key));
                                }
                            }
                        }
                    }
                    #endregion

                    #region Static Data
                    //if (entity.TypedEntity != TypedEntityConstants.None)
                    //{
                    //Determine how many rows there are
                    var orderKeyList = entity.StaticDatum.Select(x => x.OrderKey).Distinct().ToList();
                    var rowCount = orderKeyList.Count();

                    //Create a OLD static data row for each one
                    for (var ii = 0; ii < rowCount; ii++)
                    {
                        //For each row create N cells one for each column
                        var rowEntry = new nHydrate.Generator.Models.RowEntry(newTable.Root);
                        var staticDataFieldList = fieldList.Where(x => !x.IsBinaryType() && x.DataType != DataTypeConstants.Timestamp).ToList();
                        for (var jj = 0; jj < staticDataFieldList.Count; jj++)
                        {
                            var cellEntry = new nHydrate.Generator.Models.CellEntry(newTable.Root);
                            var column = newTable.GetColumns().ToList()[jj];
                            cellEntry.ColumnRef = column.CreateRef(column.Key);

                            var currentColumn = fieldList.FirstOrDefault(x => x.Id == new Guid(column.Key));
                            if (currentColumn != null)
                            {
                                var dataum = entity.StaticDatum.FirstOrDefault(x =>
                                    x.ColumnKey == currentColumn.Id &&
                                    x.OrderKey == orderKeyList[ii]);

                                if (dataum != null)
                                {
                                    cellEntry.Value = dataum.Value;
                                    cellEntry.ResetKey(dataum.Id.ToString());
                                    //cellEntry.ResetId(HashString(cellEntry.Key));
                                }

                                //Add the cell to the row
                                rowEntry.CellEntries.Add(cellEntry);
                            }

                        }
                        newTable.StaticData.Add(rowEntry);
                    }
                    //}
                    #endregion
                }

                //Setup inheritance
                foreach (var connector in inheritanceConnectors)
                {
                    var d = connector.FromShape.ModelElement as Entity;
                    var b = connector.ToShape.ModelElement as Entity;
                    var baseTable = root.Database.Tables.FirstOrDefault(x => x.Name == b.Name);
                    var derivedTable = root.Database.Tables.FirstOrDefault(x => x.Name == d.Name);
                    if (d != null && b != null && derivedTable != null && baseTable != null)
                    {
                        derivedTable.ParentTable = baseTable;
                    }
                }

                #endregion

                #region Relations
                {
                    var relationConnectors = diagram.NestedChildShapes.Where(x => x is EntityAssociationConnector).Cast<EntityAssociationConnector>().ToList();
                    foreach (var shape in relationConnectors)
                    {
                        if (shape is EntityAssociationConnector)
                        {
                            var connector = shape as EntityAssociationConnector;
                            var parent = connector.FromShape.ModelElement as Entity;
                            var child = connector.ToShape.ModelElement as Entity;

                            var relation = connector.ModelElement as EntityHasEntities;
                            var fieldList = model.RelationFields.Where(x => x.RelationID == relation.Id);

                            var parentTable = root.Database.Tables.FirstOrDefault(x => x.Name == parent.Name);
                            var childTable = root.Database.Tables.FirstOrDefault(x => x.Name == child.Name);

                            //If we found both parent and child tables...
                            if (parentTable != null && childTable != null && !childTable.IsInheritedFrom(parentTable))
                            {
                                var isValidRelation = true;
                                if (ownerModule != null)
                                {
                                    isValidRelation = ((IModuleLink)relation).Modules.Contains(ownerModule);
                                }

                                if (model.UseModules && isValidRelation)
                                {
                                    //If using modules then check that this relation's fields are in this module
                                    foreach (var columnSet in fieldList)
                                    {
                                        var field1 = parent.Fields.FirstOrDefault(x => x.Id == columnSet.SourceFieldId);
                                        var field2 = child.Fields.FirstOrDefault(x => x.Id == columnSet.TargetFieldId);
                                        if (!field1.Modules.Contains(ownerModule)) isValidRelation = false;
                                        if (!field2.Modules.Contains(ownerModule)) isValidRelation = false;
                                    }

                                }

                                if (isValidRelation)
                                {
                                    var newRelation = root.Database.Relations.Add();
                                    newRelation.ResetKey((connector.ModelElement as nHydrate.Dsl.EntityHasEntities).InternalId.ToString());
                                    newRelation.ResetId(HashString(newRelation.Key));
                                    newRelation.ParentTableRef = parentTable.CreateRef(parentTable.Key);
                                    newRelation.ChildTableRef = childTable.CreateRef(childTable.Key);
                                    newRelation.RoleName = ((EntityHasEntities)connector.ModelElement).RoleName;
                                    if (ownerModule == null)
                                    {
                                        newRelation.Enforce = relation.IsEnforced;
                                    }
                                    else
                                    {
                                        var relationModule = model.RelationModules.FirstOrDefault(x => x.RelationID == relation.Id && x.ModuleId == ownerModule.Id);
                                        if (relationModule == null)
                                        {
                                            //I do not think this should ever happen??
                                            newRelation.Enforce = false;
                                        }
                                        else
                                        {
                                            newRelation.Enforce = relationModule.IsEnforced;
                                        }
                                    }

                                    //Create the column links
                                    foreach (var columnSet in fieldList)
                                    {
                                        var field1 = parent.Fields.FirstOrDefault(x => x.Id == columnSet.SourceFieldId);
                                        var field2 = child.Fields.FirstOrDefault(x => x.Id == columnSet.TargetFieldId);

                                        var column1 = parentTable.GetColumnsFullHierarchy().FirstOrDefault(x => x.Name == field1.Name);
                                        var column2 = childTable.GetColumnsFullHierarchy().FirstOrDefault(x => x.Name == field2.Name);

                                        newRelation.ColumnRelationships.Add(new nHydrate.Generator.Models.ColumnRelationship(root)
                                        {
                                            ParentColumnRef = column1.CreateRef(column1.Key),
                                            ChildColumnRef = column2.CreateRef(column2.Key),
                                        }
                                        );
                                    }

                                    //Actually add the relation to the collection
                                    if (newRelation.ColumnRelationships.Count > 0)
                                        parentTable.Relationships.Add(newRelation.CreateRef(newRelation.Key));
                                }
                                else
                                {
                                    System.Diagnostics.Debug.Write(string.Empty);
                                }

                            }
                            else
                            {
                                System.Diagnostics.Debug.Write(string.Empty);
                            }

                        }
                    }

                    //Setup inheritance relationships
                    foreach (var connector in inheritanceConnectors)
                    {
                        var b = connector.ToShape.ModelElement as Entity;
                        var d = connector.FromShape.ModelElement as Entity;
                        var baseTable = root.Database.Tables.FirstOrDefault(x => x.Name == b.Name);
                        var derivedTable = root.Database.Tables.FirstOrDefault(x => x.Name == d.Name);
                        if (derivedTable != null && baseTable != null)
                        {
                            var newRelation = root.Database.Relations.Add();
                            newRelation.ResetKey((connector.ModelElement as EntityInheritsEntity).InternalId.ToString());
                            newRelation.ParentTableRef = baseTable.CreateRef(baseTable.Key);
                            newRelation.ChildTableRef = derivedTable.CreateRef(derivedTable.Key);
                            newRelation.Enforce = true; //Hard-wired for now

                            //Loop through the primary keys of each table and map
                            foreach (var pk in baseTable.PrimaryKeyColumns)
                            {
                                var fk = derivedTable.GetColumns().FirstOrDefault(x => x.Name == pk.Name);
                                if (fk != null)
                                {
                                    newRelation.ColumnRelationships.Add(new nHydrate.Generator.Models.ColumnRelationship(root)
                                    {
                                        ParentColumnRef = pk.CreateRef(pk.Key),
                                        ChildColumnRef = fk.CreateRef(fk.Key),
                                    });
                                }
                            }
                        }
                    }
                } //inner block

                #endregion

                #region Views
                foreach (var view in model.Views.Where(x => x.IsGenerated).Where(x => ownerModule == null || x.Modules.Contains(ownerModule)))
                {
                    var newView = root.Database.CustomViews.Add();
                    newView.ResetKey(view.Id.ToString());
                    newView.ResetId(HashString(newView.Key));
                    newView.CodeFacade = view.CodeFacade;
                    newView.DBSchema = view.Schema;
                    newView.Description = view.Summary;
                    newView.Generated = view.IsGenerated;
                    newView.Name = view.Name;
                    newView.SQL = view.SQL;
                    newView.GeneratesDoubleDerived = view.GeneratesDoubleDerived;
                    newView.PrecedenceOrder = view.PrecedenceOrder;

                    foreach (var field in view.Fields)
                    {
                        var newField = root.Database.CustomViewColumns.Add();
                        newField.ResetKey(field.Id.ToString());
                        newField.ResetId(HashString(newField.Key));
                        newField.AllowNull = field.Nullable;
                        newField.CodeFacade = field.CodeFacade;
                        newField.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString());
                        newField.Default = field.Default;
                        newField.Description = field.Summary;
                        newField.FriendlyName = field.FriendlyName;
                        newField.IsPrimaryKey = field.IsPrimaryKey;
                        newField.Generated = field.IsGenerated;
                        newField.Length = field.Length;
                        newField.Name = field.Name;
                        newField.Scale = field.Scale;
                        newView.Columns.Add(newField.CreateRef(newField.Key));
                        newField.ParentViewRef = newView.CreateRef(newView.Key);
                    }

                }
                #endregion

                #region View Relations
                {
                    var relationConnectors = diagram.NestedChildShapes.Where(x => x is EntityViewAssociationConnector).Cast<EntityViewAssociationConnector>().ToList();
                    foreach (var shape in relationConnectors)
                    {
                        if (shape is EntityViewAssociationConnector)
                        {
                            var connector = shape as EntityViewAssociationConnector;
                            var parent = connector.FromShape.ModelElement as Entity;
                            var child = connector.ToShape.ModelElement as nHydrate.Dsl.View;

                            var relation = connector.ModelElement as EntityHasViews;
                            var fieldList = model.RelationFields.Where(x => x.RelationID == relation.Id);

                            var parentTable = root.Database.Tables.FirstOrDefault(x => x.Name == parent.Name);
                            var childTable = root.Database.CustomViews.FirstOrDefault(x => x.Name == child.Name);

                            //If we found both parent and child tables...
                            if (parentTable != null && childTable != null)
                            {
                                var isValidRelation = true;
                                if (ownerModule != null)
                                {
                                    isValidRelation = ((IModuleLink)relation).Modules.Contains(ownerModule);
                                }

                                if (model.UseModules && isValidRelation)
                                {
                                    //If using modules then check that this relation's fields are in this module
                                    foreach (var columnSet in fieldList)
                                    {
                                        var field1 = parent.Fields.FirstOrDefault(x => x.Id == columnSet.SourceFieldId);
                                        var field2 = child.Fields.FirstOrDefault(x => x.Id == columnSet.TargetFieldId);
                                        if (!field1.Modules.Contains(ownerModule)) isValidRelation = false;
                                    }

                                }

                                if (isValidRelation)
                                {
                                    var newRelation = root.Database.ViewRelations.Add();
                                    newRelation.ParentTableRef = parentTable.CreateRef(parentTable.Key);
                                    newRelation.ChildViewRef = childTable.CreateRef(childTable.Key);
                                    newRelation.RoleName = ((EntityHasViews)connector.ModelElement).RoleName;

                                    //Create the column links
                                    foreach (var columnSet in fieldList)
                                    {
                                        var field1 = parent.Fields.FirstOrDefault(x => x.Id == columnSet.SourceFieldId);
                                        var field2 = child.Fields.FirstOrDefault(x => x.Id == columnSet.TargetFieldId);

                                        var column1 = parentTable.GetColumnsFullHierarchy().FirstOrDefault(x => x.Name == field1.Name);
                                        var column2 = childTable.GetColumns().FirstOrDefault(x => x.Name == field2.Name);

                                        newRelation.ColumnRelationships.Add(new nHydrate.Generator.Models.ViewColumnRelationship(root)
                                        {
                                            ParentColumnRef = column1.CreateRef(column1.Key),
                                            ChildColumnRef = column2.CreateRef(column2.Key),
                                        }
                                        );
                                    }

                                    //Actually add the relation to the collection
                                    if (newRelation.ColumnRelationships.Count > 0)
                                        parentTable.ViewRelationships.Add(newRelation.CreateRef(newRelation.Key));
                                }
                                else
                                {
                                    System.Diagnostics.Debug.Write(string.Empty);
                                }

                            }
                            else
                            {
                                System.Diagnostics.Debug.Write(string.Empty);
                            }

                        }
                    }

                } //inner block

                #endregion

                #region Stored Procedures
                foreach (var storedProc in model.StoredProcedures.Where(x => x.IsGenerated).Where(x => ownerModule == null || x.Modules.Contains(ownerModule)))
                {
                    var newStoredProc = root.Database.CustomStoredProcedures.Add();
                    newStoredProc.ResetKey(storedProc.Id.ToString());
                    newStoredProc.ResetId(HashString(newStoredProc.Key));
                    newStoredProc.CodeFacade = storedProc.CodeFacade;
                    newStoredProc.DatabaseObjectName = storedProc.DatabaseObjectName;
                    newStoredProc.DBSchema = storedProc.Schema;
                    newStoredProc.Description = storedProc.Summary;
                    newStoredProc.Generated = storedProc.IsGenerated;
                    newStoredProc.Name = storedProc.Name;
                    newStoredProc.SQL = storedProc.SQL;
                    newStoredProc.GeneratesDoubleDerived = storedProc.GeneratesDoubleDerived;
                    newStoredProc.PrecedenceOrder = storedProc.PrecedenceOrder;
                    newStoredProc.IsExisting = storedProc.IsExisting;

                    foreach (var field in storedProc.Fields)
                    {
                        var newField = root.Database.CustomStoredProcedureColumns.Add();
                        newField.ResetKey(field.Id.ToString());
                        newField.ResetId(HashString(newField.Key));
                        newField.AllowNull = field.Nullable;
                        newField.CodeFacade = field.CodeFacade;
                        newField.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString());
                        newField.Default = field.Default;
                        newField.Description = field.Summary;
                        newField.FriendlyName = field.FriendlyName;
                        newField.Generated = field.IsGenerated;
                        newField.Length = field.Length;
                        newField.Name = field.Name;
                        newField.Scale = field.Scale;
                        newStoredProc.Columns.Add(newField.CreateRef(newField.Key));
                        newField.ParentRef = newStoredProc.CreateRef(newStoredProc.Key);
                    }

                    //Just in case these are ordered get all sort-ordered parameters first then take on all unordred alphabetized parmameters
                    var orderedParameters = storedProc.Parameters.Where(x => x.SortOrder > 0).OrderBy(x => x.SortOrder).ToList();
                    orderedParameters.AddRange(storedProc.Parameters.Where(x => x.SortOrder == 0).OrderBy(x => x.Name).ToList());
                    foreach (var parameter in orderedParameters)
                    {
                        var newParameter = root.Database.CustomRetrieveRuleParameters.Add();
                        newParameter.ResetKey(parameter.Id.ToString());
                        newParameter.ResetId(HashString(newParameter.Key));
                        newParameter.AllowNull = parameter.Nullable;
                        newParameter.CodeFacade = parameter.CodeFacade;
                        newParameter.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), parameter.DataType.ToString());
                        newParameter.Default = parameter.Default;
                        newParameter.Description = parameter.Summary;
                        newParameter.Generated = parameter.IsGenerated;
                        newParameter.IsOutputParameter = parameter.IsOutputParameter;
                        newParameter.Length = parameter.Length;
                        newParameter.Name = parameter.Name;
                        newParameter.Scale = parameter.Scale;
                        newParameter.SortOrder = parameter.SortOrder;
                        newStoredProc.Parameters.Add(newParameter.CreateRef(newParameter.Key));
                        newParameter.ParentTableRef = newStoredProc.CreateRef(newStoredProc.Key);
                    }

                }
                #endregion

                #region Functions
                foreach (var function in model.Functions.Where(x => x.IsGenerated).Where(x => ownerModule == null || x.Modules.Contains(ownerModule)))
                {
                    var newFunction = root.Database.Functions.Add();
                    newFunction.ResetKey(function.Id.ToString());
                    newFunction.ResetId(HashString(newFunction.Key));
                    newFunction.CodeFacade = function.CodeFacade;
                    newFunction.DBSchema = function.Schema;
                    newFunction.Description = function.Summary;
                    newFunction.Generated = function.IsGenerated;
                    newFunction.Name = function.Name;
                    newFunction.SQL = function.SQL;
                    newFunction.IsTable = function.IsTable;
                    newFunction.ReturnVariable = function.ReturnVariable;
                    newFunction.PrecedenceOrder = function.PrecedenceOrder;

                    foreach (var field in function.Fields)
                    {
                        var newField = root.Database.FunctionColumns.Add();
                        newField.ResetKey(field.Id.ToString());
                        newField.ResetId(HashString(newField.Key));
                        newField.AllowNull = field.Nullable;
                        newField.CodeFacade = field.CodeFacade;
                        newField.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString());
                        newField.Default = field.Default;
                        newField.Description = field.Summary;
                        newField.FriendlyName = field.FriendlyName;
                        newField.Generated = field.IsGenerated;
                        newField.Length = field.Length;
                        newField.Name = field.Name;
                        newField.Scale = field.Scale;
                        newFunction.Columns.Add(newField.CreateRef(newField.Key));
                        newField.ParentRef = newFunction.CreateRef(newFunction.Key);
                    }

                    //Just in case these are ordered get all sort-ordered parameters first then take on all unordred alphabetized parmameters
                    var orderedParameters = function.Parameters.Where(x => x.SortOrder > 0).OrderBy(x => x.SortOrder).ToList();
                    orderedParameters.AddRange(function.Parameters.Where(x => x.SortOrder == 0).OrderBy(x => x.Name).ToList());
                    foreach (var parameter in orderedParameters)
                    {
                        var newParameter = root.Database.FunctionParameters.Add();
                        newParameter.ResetKey(parameter.Id.ToString());
                        newParameter.ResetId(HashString(newParameter.Key));
                        newParameter.AllowNull = parameter.Nullable;
                        newParameter.CodeFacade = parameter.CodeFacade;
                        newParameter.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), parameter.DataType.ToString());
                        newParameter.Default = parameter.Default;
                        newParameter.Description = parameter.Summary;
                        newParameter.Generated = parameter.IsGenerated;
                        newParameter.Length = parameter.Length;
                        newParameter.Name = parameter.Name;
                        newParameter.Scale = parameter.Scale;
                        newParameter.SortOrder = parameter.SortOrder;

                        var r = newParameter.CreateRef(newParameter.Key);
                        r.RefType = nHydrate.Generator.Models.ReferenceType.FunctionParameter;
                        newFunction.Parameters.Add(r);
                        newParameter.ParentTableRef = newFunction.CreateRef(newFunction.Key);
                    }

                }
                #endregion

                return root;

            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 8
0
        public static void PopulateFields(nHydrate.Dsl.nHydrateModel model, Module module, DataImport.Entity importItem, Entity targetItem)
        {
            foreach (var field in importItem.FieldList)
            {
                var newField = targetItem.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                if (newField == null)
                    newField = new nHydrate.Dsl.Field(model.Partition);

                //Add module if necessary
                if (module != null && !newField.Modules.Contains(module))
                {
                    newField.Modules.Add(module);
                }

                if (!targetItem.Fields.Contains(newField))
                    targetItem.Fields.Add(newField);

                newField.SortOrder = field.SortOrder;
                newField.Name = field.Name;
                newField.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), field.DataType.ToString());
                newField.Length = field.Length;
                newField.Nullable = field.Nullable;
                newField.IsCalculated = field.IsComputed;
                newField.Default = field.DefaultValue;
                newField.IsUnique = field.IsUnique;
                newField.Formula = field.Formula;
                newField.Identity = (field.Identity ? IdentityTypeConstants.Database : IdentityTypeConstants.None);
                newField.IsPrimaryKey = field.PrimaryKey;
                newField.Scale = field.Scale;
                newField.ImportedDefaultName = field.ImportedDefaultName;
                //DO NOT IMPORT METADATA

                //Correct for invalid identifiers
                //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newField.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newField.Name))
                if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newField.Name))
                {
                    newField.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newField.Name, string.Empty);
                }
            }
            var removedFields = targetItem.Fields.Remove(x => !importItem.FieldList.Select(y => y.Name.ToLower()).Contains(x.Name.ToLower()));
        }
Exemplo n.º 9
0
        public static void ImportDatabase(nHydrate.Dsl.nHydrateModel model, Store store, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, nHydrate.DataImport.Database database, Module module)
        {

            try
            {
                //Find Stored procs with no loaded columns
                var noColumList = new List<string>();
                database.StoredProcList
                        .Where(x => (x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified) && x.ColumnFailure)
                        .ToList()
                        .ForEach(x => noColumList.Add(x.Name));

                if (noColumList.Count > 0)
                {
                    MessageBox.Show("The output fields could not be determined for the following stored procedures. The fields collection of each will not be modified.\r\n\r\n" + string.Join("\r\n", noColumList.ToArray()), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            ((nHydrate.Dsl.nHydrateDiagram)diagram).IsLoading = true;
            model.IsLoading = true;
            var pkey = ProgressHelper.ProgressingStarted("Processing Import...", true);
            model.IsLoading = true;
            try
            {
                var addedEntities = new List<Entity>();
                var diagramEntities = model.Entities.ToList();
                var diagramStoredProcs = model.StoredProcedures.ToList();
                var diagramViews = model.Views.ToList();
                var diagramFunctions = model.Functions.ToList();
                using (var transaction = store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    #region TEMP TEMP - RESET THE PARAMETERS AND FIELDS OF ALL NON-ENTITY OBJECTS - USED FOR DEBUGGING

                    //foreach (var entity in model.Entities)
                    //{
                    //  var table = database.EntityList.FirstOrDefault(x => x.Name == entity.Name);
                    //  if (table != null)
                    //  {
                    //    foreach (var field in entity.Fields)
                    //    {
                    //      var column = table.FieldList.FirstOrDefault(x => x.Name == field.Name);
                    //      if (column != null)
                    //      {
                    //        field.SortOrder = column.SortOrder;
                    //      }
                    //    }
                    //  }
                    //  entity.Fields.Sort((x, y) => (x.SortOrder < y.SortOrder ? -1 : 0));
                    //}

                    //var spList = database.StoredProcList.Where(x => x.ParameterList.Count(z => z.IsOutputParameter) > 0).ToList();
                    //foreach (var sp in spList)
                    //{
                    //  var newSP = model.StoredProcedures.FirstOrDefault(x => x.Name == sp.Name);
                    //  if (newSP != null)
                    //  {
                    //    foreach (var p in sp.ParameterList.Where(x => x.IsOutputParameter))
                    //    {
                    //      var newParameter = newSP.Parameters.FirstOrDefault(x => x.Name == p.Name);
                    //      if (newParameter != null)
                    //      {
                    //        newParameter.IsOutputParameter = true;
                    //      }
                    //    }
                    //  }
                    //}

                    //int paramCount = 0;
                    //int fieldCount = 0;
                    //foreach (var storedProc in database.StoredProcList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    //{
                    //  var newStoredProc = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == storedProc.Name.ToLower());
                    //  if (newStoredProc != null)
                    //  {
                    //    //Fields
                    //    foreach (var field in storedProc.FieldList)
                    //    {
                    //      var newField = newStoredProc.Fields.FirstOrDefault(x => x.Name == field.Name);
                    //      if (newField == null)
                    //      {
                    //        newField = new nHydrate.Dsl.StoredProcedureField(model.Partition);
                    //        newStoredProc.Fields.Add(newField);
                    //        newField.Name = field.Name;
                    //        newField.Length = field.Length;
                    //        newField.Nullable = field.Nullable;
                    //        newField.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), field.DataType.ToString());
                    //        newField.Default = field.DefaultValue;
                    //        newField.Scale = field.Scale;
                    //        fieldCount++;
                    //      }

                    //    }

                    //    //Parameters
                    //    foreach (var parameter in storedProc.ParameterList)
                    //    {
                    //      var newParameter = newStoredProc.Parameters.FirstOrDefault(x => x.Name == parameter.Name);
                    //      if (newParameter == null)
                    //      {
                    //        newParameter = new nHydrate.Dsl.StoredProcedureParameter(model.Partition);
                    //        newStoredProc.Parameters.Add(newParameter);
                    //        newParameter.Name = parameter.Name;
                    //        newParameter.SortOrder = parameter.SortOrder;
                    //        newParameter.Length = parameter.Length;
                    //        newParameter.Nullable = parameter.Nullable;
                    //        newParameter.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), parameter.DataType.ToString());
                    //        newParameter.Default = parameter.DefaultValue;
                    //        newParameter.Scale = parameter.Scale;
                    //        newParameter.IsOutputParameter = parameter.IsOutputParameter;
                    //        paramCount++;
                    //      }

                    //    }
                    //  }
                    //}

                    //foreach (var storedProc in database.StoredProcList)
                    //{
                    //  var newStoredProc = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == storedProc.Name.ToLower());
                    //  if (newStoredProc != null)
                    //  {
                    //    foreach (var field in storedProc.FieldList)
                    //    {
                    //      var newField = newStoredProc.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                    //      if (newField != null) newField.Nullable = field.Nullable;
                    //    }

                    //    foreach (var parameter in storedProc.ParameterList)
                    //    {
                    //      var newParameter = newStoredProc.Parameters.FirstOrDefault(x => x.Name.ToLower() == parameter.Name.ToLower());
                    //      if (newParameter != null) newParameter.Nullable = parameter.Nullable;
                    //    }
                    //  }
                    //}

                    //foreach (var view in database.ViewList)
                    //{
                    //  var newView = diagramViews.FirstOrDefault(x => x.Name.ToLower() == view.Name.ToLower());
                    //  if (newView != null)
                    //  {
                    //    foreach (var field in view.FieldList)
                    //    {
                    //      var newField = newView.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                    //      if (newField != null) newField.Nullable = field.Nullable;
                    //    }
                    //  }
                    //}

                    //foreach (var function in database.FunctionList)
                    //{
                    //  var newFunction = diagramFunctions.FirstOrDefault(x => x.Name.ToLower() == function.Name.ToLower());
                    //  if (newFunction != null)
                    //  {
                    //    foreach (var field in function.FieldList)
                    //    {
                    //      var newField = newFunction.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());
                    //      if (newField != null) newField.Nullable = field.Nullable;
                    //    }

                    //    foreach (var parameter in function.ParameterList)
                    //    {
                    //      var newParameter = newFunction.Parameters.FirstOrDefault(x => x.Name.ToLower() == parameter.Name.ToLower());
                    //      if (newParameter != null) newParameter.Nullable = parameter.Nullable;
                    //    }
                    //  }
                    //}

                    //foreach (var index in database.IndexList.Where(x => x.FieldList.Count == 1 && !x.FieldList.First().IsDescending))
                    //{
                    //  var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                    //  if (entity != null)
                    //  {
                    //    var field = entity.Fields.FirstOrDefault(x => x.Name == index.FieldList.First().Name);
                    //    if (field != null)
                    //    {
                    //      field.IsIndexed = true;
                    //    }
                    //  }
                    //}

                    //transaction.Commit();
                    //return;

                    #endregion

                    #region Load Entities

                    #region Merge Module
                    foreach (var item in database.EntityList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramEntities.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }

                        foreach (var field in item.FieldList)
                        {
                            var newField = modelItem.Fields.FirstOrDefault(x => x.Name.ToLower() == field.Name.ToLower());

                            //Add module if necessary
                            if (module != null && newField != null && !newField.Modules.Contains(module))
                            {
                                newField.Modules.Add(module);
                            }
                        }

                    }
                    #endregion

                    var addedChangedEntities = database.EntityList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified).ToList();

                    #region Entities

                    foreach (var entity in addedChangedEntities)
                    {
                        var newEntity = diagramEntities.FirstOrDefault(x => x.Id == entity.ID);
                        if (newEntity == null) newEntity = diagramEntities.FirstOrDefault(x => x.Name.ToLower() == entity.Name.ToLower());
                        if (newEntity == null)
                        {
                            newEntity = new Entity(model.Partition) { Name = entity.Name };
                            model.Entities.Add(newEntity);
                            addedEntities.Add(newEntity);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newEntity.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newEntity.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newEntity.Name))
                            {
                                newEntity.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newEntity.Name, string.Empty);
                            }
                        }
                        newEntity.AllowCreateAudit = entity.AllowCreateAudit;
                        newEntity.AllowModifyAudit = entity.AllowModifyAudit;
                        newEntity.AllowTimestamp = entity.AllowTimestamp;
                        newEntity.IsTenant = entity.IsTenant;
                        newEntity.Name = entity.Name;
                        newEntity.Schema = entity.Schema;

                        //Add module if necessary
                        if (module != null && !newEntity.Modules.Contains(module))
                        {
                            newEntity.Modules.Add(module);
                        }

                        PopulateFields(model, module, entity, newEntity);

                        //Order columns by database
                        //newEntity.Fields.Sort((x, y) => x.Name.CompareTo(y.Name));
                        newEntity.Fields.Sort((x, y) => (x.SortOrder < y.SortOrder ? -1 : 0));
                    }

                    #endregion

                    //Find all fields in the removed entities
                    var removalFieldIdList = model.Entities
                        .Where(x => database.EntityList
                            .Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted)
                            .Select(a => a.Name)
                            .ToList()
                            .Contains(x.Name)).ToList()
                            .SelectMany(x => x.Fields).Select(x => x.Id);

                    ////Remove these fields from the relation field map collection
                    //model.RelationFields.Remove(x => removalFieldIdList.Contains(x.SourceFieldId) || removalFieldIdList.Contains(x.TargetFieldId));

                    //Remove the ones that need to be remove
                    model.Entities.Remove(x => database.EntityList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    #region Load Relations
                    if (!database.IgnoreRelations)
                    {
                        var allRelationElementList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements
                            .ToList()
                            .Where(x => x is EntityHasEntities)
                            .ToList()
                            .Cast<EntityHasEntities>()
                            .ToList();

                        foreach (var entity in database.EntityList)
                        {
                            foreach (var relation in entity.RelationshipList)
                            {
                                var isNewConnection = false;
                                var connection = allRelationElementList.FirstOrDefault(x => x.ImportData == relation.ImportData);

                                //Now verify that this is the table has not been renamed
                                if (connection != null)
                                {
                                    //If the table names no longer match then create a new relation
                                    if (string.Compare(connection.ChildEntity.Name, relation.TargetEntity.Name, true) != 0 ||
                                        string.Compare(connection.ParentEntity.Name, relation.SourceEntity.Name, true) != 0)
                                    {
                                        connection.ImportData = string.Empty;
                                        connection = null;
                                    }
                                }

                                if (connection == null)
                                {
                                    //try to find this relation by table/fields/role
                                    connection = allRelationElementList.FirstOrDefault(x => x.GetCorePropertiesHash() == relation.CorePropertiesHash);
                                }
                                var parent = model.Entities.FirstOrDefault(x => x.Name == relation.SourceEntity.Name);
                                var child = model.Entities.FirstOrDefault(x => x.Name == relation.TargetEntity.Name);
                                if (connection == null)
                                {
                                    var existingRelation = diagram.NestedChildShapes.FirstOrDefault(x => x.Id == relation.ID);
                                    if (existingRelation == null)
                                    {
                                        if (child != null && parent != null)
                                        {

                                            //var currentList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
                                            //parent.ChildEntities.Add(child);
                                            //var updatedList = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.ToList();
                                            //var last = updatedList.Last();
                                            //updatedList.RemoveAll(x => currentList.Contains(x));
                                            //connection = updatedList.First() as EntityHasEntities;
                                            //if (connection != last) System.Diagnostics.Debug.Write("");

                                            parent.ChildEntities.Add(child);
                                            connection = store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.Last() as EntityHasEntities;

                                            isNewConnection = true;
                                            connection.ImportData = relation.ImportData;
                                        }
                                    }
                                } //Relation does not exist

                                //Add the relation fields
                                if (parent != null && child != null)
                                {
                                    foreach (var ritem in relation.RelationshipColumnList)
                                    {
                                        var parentField = parent.Fields.FirstOrDefault(x => x.Name == ritem.ParentField.Name);
                                        var childField = child.Fields.FirstOrDefault(x => x.Name == ritem.ChildField.Name);
                                        if (parentField != null && childField != null)
                                        {
                                            //Do not import the role name again.
                                            if (isNewConnection)
                                            {
                                                connection.RoleName = relation.RoleName;
                                                connection.ImportedConstraintName = relation.ConstraintName;
                                            }

                                            var currentRelationField = model.RelationFields.FirstOrDefault(x =>
                                                x.SourceFieldId == parentField.Id &&
                                                x.TargetFieldId == childField.Id &&
                                                x.RelationID == connection.Id);

                                            //Only add if not there already
                                            if (currentRelationField == null)
                                            {
                                                model.RelationFields.Add(
                                                    new RelationField(model.Partition)
                                                    {
                                                        SourceFieldId = parentField.Id,
                                                        TargetFieldId = childField.Id,
                                                        RelationID = connection.Id,
                                                    }
                                                    );
                                            }
                                        }
                                    } //Relation Columns
                                }

                            }
                        }
                    }
                    #endregion

                    #region Process Indexes

                    //Only get the single column indexes ascending
                    var isIndexedList = database.IndexList.Where(x => x.FieldList.Count == 1 && !x.FieldList.First().IsDescending).ToList();
                    var allIndexList = database.IndexList.Where(x => addedChangedEntities.Select(z => z.Name.ToLower()).Contains(x.TableName.ToLower())).ToList();

                    //Delete existing indexes by name. These will be recreated.
                    foreach (var index in allIndexList)
                    {
                        var existing = model.Entities.SelectMany(x => x.Indexes).FirstOrDefault(x => x.ImportedName == index.IndexName);
                        if (existing != null)
                        {
                            existing.Delete();
                        }
                    }

                    //Delete existing IsIndexed indexes with no import names as they will be recreated
                    var existingIsIndexedList = model.Entities.Where(x => addedChangedEntities.Select(z => z.Name.ToLower()).Contains(x.Name.ToLower())).SelectMany(x => x.Indexes).Where(x => x.IsIndexedType).ToList();
                    foreach (var index in isIndexedList)
                    {
                        foreach (var existing in existingIsIndexedList)
                        {
                            if (index.IsMatch(existing))
                                existing.Delete();
                        }
                    }

                    //Create all indexes
                    foreach (var index in allIndexList)
                    {
                        var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                        if (entity != null)
                        {
                            var realFields = entity.Fields.Where(x => index.FieldList.Select(z => z.Name).Contains(x.Name)).ToList();
                            if (realFields.Count > 0)
                            {
                                //Try to get the PK if one exists
                                var isNew = true;
                                Index newIndex = null;
                                if (index.IsPrimaryKey)
                                {
                                    newIndex = entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey);
                                    if (newIndex != null)
                                    {
                                        isNew = false;
                                        newIndex.IndexColumns.Clear();
                                    }
                                }

                                //Create an index
                                if (newIndex == null)
                                    newIndex = new Index(entity.Partition);

                                newIndex.ParentEntityID = entity.Id;
                                newIndex.ImportedName = index.IndexName;
                                newIndex.Clustered = index.Clustered;
                                newIndex.IsUnique = index.IsUnique;

                                if (index.IsPrimaryKey)
                                    newIndex.IndexType = IndexTypeConstants.PrimaryKey;
                                else if (isIndexedList.Contains(index))
                                    newIndex.IndexType = IndexTypeConstants.IsIndexed;
                                else
                                    newIndex.IndexType = IndexTypeConstants.User;

                                if (isNew)
                                    entity.Indexes.Add(newIndex);

                                foreach (var ic in index.FieldList)
                                {
                                    var field = realFields.FirstOrDefault(x => x.Name == ic.Name);
                                    if (field != null)
                                    {
                                        var newIndexColumn = new IndexColumn(entity.Partition);
                                        newIndexColumn.Ascending = !ic.IsDescending;
                                        newIndexColumn.FieldID = field.Id;
                                        newIndexColumn.IsInternal = true;
                                        newIndexColumn.SortOrder = ic.OrderIndex;
                                        newIndex.IndexColumns.Add(newIndexColumn);
                                    }
                                }
                            }

                        }
                    }

                    //Create the special IsIndexed settings
                    //This will not create a new index since it was created above
                    foreach (var index in isIndexedList)
                    {
                        var entity = model.Entities.FirstOrDefault(x => x.Name == index.TableName);
                        if ((entity != null) && addedChangedEntities.Select(z => z.Name.ToLower()).Contains(entity.Name.ToLower()))
                        {
                            var field = entity.Fields.FirstOrDefault(x => x.Name == index.FieldList.First().Name);
                            if (field != null)
                            {
                                field.IsIndexed = true;
                            }
                        }
                    }

                    #endregion

                    #region Add Stored Procedures

                    #region Merge Module
                    foreach (var item in database.StoredProcList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }
                    }
                    #endregion

                    foreach (var storedProc in database.StoredProcList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    {
                        var newStoredProc = diagramStoredProcs.Where(x => x.Id == storedProc.ID).FirstOrDefault();
                        if (newStoredProc == null) newStoredProc = diagramStoredProcs.FirstOrDefault(x => x.Name.ToLower() == storedProc.Name.ToLower());
                        if (newStoredProc == null)
                        {
                            newStoredProc = new StoredProcedure(model.Partition) { Name = storedProc.Name };
                            model.StoredProcedures.Add(newStoredProc);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newStoredProc.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newStoredProc.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newStoredProc.Name))
                            {
                                newStoredProc.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newStoredProc.Name, string.Empty);
                            }
                        }
                        newStoredProc.Name = storedProc.Name;
                        newStoredProc.DatabaseObjectName = newStoredProc.Name; //Ensures the "gen_" prefix is not prepended

                        //Add module if necessary
                        if (module != null && !newStoredProc.Modules.Contains(module))
                        {
                            newStoredProc.Modules.Add(module);
                        }

                        newStoredProc.Schema = storedProc.Schema;
                        newStoredProc.SQL = storedProc.SQL;

                        PopulateFields(model, storedProc, newStoredProc);
                        PopulateParameters(model, storedProc, newStoredProc);
                    }

                    //Remove the ones that need to be remove
                    model.StoredProcedures.Remove(x => database.StoredProcList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    #region Add Views

                    #region Merge Module
                    foreach (var item in database.ViewList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramViews.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }
                    }
                    #endregion

                    foreach (var view in database.ViewList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    {
                        var newView = diagramViews.Where(x => x.Id == view.ID).FirstOrDefault();
                        if (newView == null) newView = diagramViews.FirstOrDefault(x => x.Name.ToLower() == view.Name.ToLower());
                        if (newView == null)
                        {
                            newView = new nHydrate.Dsl.View(model.Partition) { Name = view.Name };
                            model.Views.Add(newView);

                            //Correct for invalid identifiers
                            //if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newView.Name) && !nHydrate.Dsl.ValidationHelper.IsReservedWord(newView.Name))
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newView.Name))
                            {
                                newView.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newView.Name, string.Empty);
                            }
                        }
                        newView.Name = view.Name;

                        //Add module if necessary
                        if (module != null && !newView.Modules.Contains(module))
                        {
                            newView.Modules.Add(module);
                        }

                        newView.Schema = view.Schema;
                        newView.SQL = view.SQL;

                        PopulateFields(model, view, newView);

                    }

                    //Remove the ones that need to be remove
                    model.Views.Remove(x => database.ViewList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));

                    #endregion

                    #region Add Functions

                    #region Merge Module
                    foreach (var item in database.FunctionList.Where(x => x.ImportState == DataImport.ImportStateConstants.Merge))
                    {
                        //Add module if necessary
                        var modelItem = diagramFunctions.FirstOrDefault(x => x.Name.ToLower() == item.Name.ToLower());
                        if (module != null && !modelItem.Modules.Contains(module))
                        {
                            modelItem.Modules.Add(module);
                        }
                    }
                    #endregion

                    foreach (var function in database.FunctionList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified))
                    {
                        var newFunction = diagramFunctions.Where(x => x.Id == function.ID).FirstOrDefault();
                        if (newFunction == null) newFunction = diagramFunctions.FirstOrDefault(x => x.Name.ToLower() == function.Name.ToLower());
                        if (newFunction == null)
                        {
                            newFunction = new Function(model.Partition) { Name = function.Name };
                            model.Functions.Add(newFunction);

                            //Correct for invalid identifiers
                            if (!nHydrate.Dsl.ValidationHelper.ValidCodeIdentifier(newFunction.Name))
                            {
                                newFunction.CodeFacade = nHydrate.Dsl.ValidationHelper.MakeCodeIdentifer(newFunction.Name, string.Empty);
                            }
                        }
                        newFunction.Name = function.Name;
                        newFunction.ReturnVariable = function.ReturnVariable;

                        newFunction.IsTable = function.IsTable;

                        //Add module if necessary
                        if (module != null && !newFunction.Modules.Contains(module))
                        {
                            newFunction.Modules.Add(module);
                        }

                        newFunction.Schema = function.Schema;
                        newFunction.SQL = function.SQL;

                        PopulateFields(model, function, newFunction);
                        PopulateParameters(model, function, newFunction);

                    }

                    //Remove the ones that need to be remove
                    model.Functions.Remove(x => database.FunctionList.Where(z => z.ImportState == DataImport.ImportStateConstants.Deleted).Select(a => a.Name).ToList().Contains(x.Name));
                    #endregion

                    //Reset Precedense if necessary
                    model.StoredProcedures.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++model.MaxPrecedenceOrder);
                    model.Views.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++model.MaxPrecedenceOrder);
                    model.Functions.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++model.MaxPrecedenceOrder);

                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                model.IsLoading = false;

                ProgressHelper.ProgressingComplete(pkey);
                ((nHydrate.Dsl.nHydrateDiagram)diagram).IsLoading = false;
                model.IsLoading = false;
            }

        }