private List <nHydrateGeneratorProject> BuildModelList(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData) { var genList = new List <nHydrateGeneratorProject>(); var genProject = new nHydrateGeneratorProject(); genList.Add(genProject); var root = CreatePOCOModel(model, diagram); root.SetKey(model.Id.ToString()); root.GeneratorProject = genProject; genProject.RootController.Object = root; var fi = new System.IO.FileInfo(docData.FileName); genProject.FileName = docData.FileName + ".generating"; var document = new System.Xml.XmlDocument(); document.LoadXml("<modelRoot guid=\"" + model.Id + "\" type=\"nHydrate.Generator.nHydrateGeneratorProject\" assembly=\"nHydrate.Generator.dll\"><ModelRoot></ModelRoot></modelRoot>"); ((nHydrate.Generator.Common.GeneratorFramework.IXMLable)root).XmlAppend(document.DocumentElement.ChildNodes[0]); System.IO.File.WriteAllText(genProject.FileName, document.ToIndentedString()); ProcessRenamed(genProject.FileName + ".sql.lastgen", root); root.RemovedTables.AddRange(model.RemovedTables); //NOTE: This caused diff scripts to be generated EVERY time so removed for now //Remove associative tables since they cause issues if they exist //root.RemovedTables.AddRange(model.Entities.Where(x => x.IsAssociative && x.IsGenerated).Select(x => x.Name)); root.RemovedViews.AddRange(model.RemovedViews); //Remove EnumOnly type-tables from the project root.RemovedTables.AddRange(model.Entities.Where(x => x.TypedEntity == TypedEntityConstants.EnumOnly).Select(x => x.Name)); return(genList); }
public TableExtendedPropertiesForm( Entity entity, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram) : this() { lblHeader.Text = entity.Name + " Entity"; //Child tables foreach (var child in entity.ChildEntities) { //if (child.IsDerivedFrom(entity)) lstChildTable.Items.Add(child.Name); } //Parent relationships var connectorList = diagram.NestedChildShapes.Where(x => x is EntityAssociationConnector).AsEnumerable <EntityAssociationConnector>(); foreach (var connector in connectorList) { var parentTable = connector.FromShape.ModelElement as Entity; var childTable = connector.ToShape.ModelElement as Entity; if (childTable == entity) { lstParentTable.Items.Add(parentTable.Name); } } }
public RelationCollectionForm( nHydrateModel model, EntityShape entityShape, Microsoft.VisualStudio.Modeling.Store store, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, nHydrateDocData docData) : this() { _model = model; _store = store; _diagram = diagram; _docData = docData; _entityShape = entityShape; lvwMembers.Columns.Clear(); lvwMembers.Columns.Add(new ColumnHeader() { Text = "Parent", Width = 200 }); lvwMembers.Columns.Add(new ColumnHeader() { Text = "Child", Width = 200 }); lvwMembers.Columns.Add(new ColumnHeader() { Text = "Role", Width = 200 }); lvwMembers.ListViewItemSorter = new nHydrate.Generator.Common.Forms.CommonLibrary.ListViewItemComparer(0, lvwMembers.Sorting); lvwMembers.Sort(); this.LoadList(); }
public void Generate(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData) { this.ErrorList = new List <string>(); GeneratedFileList = new List <nHydrate.Generator.Common.EventArgs.ProjectItemGeneratedEventArgs>(); try { #region Generation //Clean up delete tracking model.RemovedTables.Remove(x => model.Entities.Select(y => y.PascalName).Contains(x)); model.RemovedViews.Remove(x => model.Views.Select(y => y.PascalName).Contains(x)); var g = new nHydrate.Generator.Common.GeneratorFramework.GeneratorHelper(); g.ProjectItemGenerated += new nHydrate.Generator.Common.GeneratorFramework.ProjectItemGeneratedEventHandler(g_ProjectItemGenerated); var genList = BuildModelList(model, diagram, docData); var excludeList = new List <Type>(); var generatorTypeList = g.GetProjectGenerators(genList.First()); if (generatorTypeList.Count == 0) { return; //add message box } if (ChooseGenerators(model, genList, generatorTypeList, excludeList, g)) { //Perform actual generation if (genList.Count > 0) { PerformGeneration(model, genList, diagram.Store, docData, excludeList, g); } model.RemovedTables.Clear(); model.RemovedViews.Clear(); } #endregion //Remove temp file try { genList.ForEach(x => System.IO.File.Delete(x.FileName)); } catch { } #if DEBUG if (this.ErrorList.Count > 0) { var F = new nHydrate.DslPackage.Forms.ErrorForm(); F.SetErrors(this.ErrorList); F.ShowDialog(); } #endif } catch (Exception ex) { throw; } }
public void GenerateXmlFile(Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram) { foreach (Object o in diagram.ModelElement.GetElementLinks()) { if (o.GetType() == typeof(ISpySoft.FeatureModelLanguage.DomainModel.ActivityGraphHasElements)) { ISpySoft.FeatureModelLanguage.DomainModel.ActivityGraphHasElements element = (ISpySoft.FeatureModelLanguage.DomainModel.ActivityGraphHasElements)o; ISpySoft.FeatureModelLanguage.DomainModel.AbstractFeature abstractFeature = element.Elements; if (abstractFeature.GetType() == typeof(ISpySoft.FeatureModelLanguage.DomainModel.RootFeature)) { if (abstractFeature.GetElementLinks().Count > 0) { XmlDocument doc; doc = new XmlDocument(); XmlElement rootfeatureElement = doc.CreateElement("RootFeature"); rootfeatureElement.SetAttribute("name", abstractFeature.Name); doc.AppendChild(rootfeatureElement); foreach (Microsoft.VisualStudio.Modeling.ModelElement elem in abstractFeature.GetElementLinks()) { if (elem.GetType() == typeof(ISpySoft.FeatureModelLanguage.DomainModel.RelationshipFeature)) { ISpySoft.FeatureModelLanguage.DomainModel.RelationshipFeature relationshipFeature = (ISpySoft.FeatureModelLanguage.DomainModel.RelationshipFeature)elem; ISpySoft.FeatureModelLanguage.DomainModel.AbstractFeature childFeature = relationshipFeature.TransitionTo; GetSubFeatures(childFeature, ref doc, rootfeatureElement); } else if (elem.GetType() == typeof(ISpySoft.FeatureModelLanguage.DomainModel.RelationshipFeatureSet)) { ISpySoft.FeatureModelLanguage.DomainModel.RelationshipFeatureSet relationshipFeatureSet = (ISpySoft.FeatureModelLanguage.DomainModel.RelationshipFeatureSet)elem; ISpySoft.FeatureModelLanguage.DomainModel.AbstractFeature childFeature = relationshipFeatureSet.ObjectTransitionTo; GetSubFeatures(childFeature, ref doc, rootfeatureElement); } } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Feature Configuration Files (*.featureconfig)|*.featureconfig|All Files (*.*)|*.*"; saveFileDialog.FilterIndex = 1; if (saveFileDialog.ShowDialog() == DialogResult.OK) { doc.Save(saveFileDialog.FileName); } } } } } }
private nHydrate.Generator.Models.ModelRoot CreatePOCOModel(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram) { try { var root = new nHydrate.Generator.Models.ModelRoot(null); root.EnableCustomChangeEvents = model.EmitChangeScripts; root.CompanyName = model.CompanyName; root.EmitSafetyScripts = model.EmitSafetyScripts; root.DefaultNamespace = model.DefaultNamespace; root.ProjectName = model.ProjectName; root.SupportLegacySearchObject = false; root.UseUTCTime = model.UseUTCTime; root.Version = model.Version; 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.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; #region Load the entities foreach (var entity in model.Entities) { #region Table Info var newTable = root.Database.Tables.Add(); newTable.ResetKey(entity.Id.ToString()); newTable.ResetId(HashString(newTable.Key)); 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.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; #endregion #region Load the fields for this entity var fieldList = entity.Fields.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.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.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.Name = field.Name; newColumn.ParentTableRef = newTable.CreateRef(newTable.Key); newColumn.PrimaryKey = field.IsPrimaryKey; newColumn.Scale = field.Scale; newColumn.SortOrder = field.SortOrder; newColumn.Obsolete = field.Obsolete; newTable.Columns.Add(newColumn.CreateRef(newColumn.Key)); } #endregion #region Indexes var indexList = entity.Indexes.ToList(); foreach (var index in indexList) { var indexColumns = index.IndexColumns.Where(x => x.GetField() != null).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 Static Data //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.DataType.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()); } //Add the cell to the row rowEntry.CellEntries.Add(cellEntry); } } newTable.StaticData.Add(rowEntry); } #endregion } #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 (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; switch (relation.DeleteAction) { case DeleteActionConstants.Cascade: newRelation.DeleteAction = Relation.DeleteActionConstants.Cascade; break; case DeleteActionConstants.NoAction: newRelation.DeleteAction = Relation.DeleteActionConstants.NoAction; break; case DeleteActionConstants.SetNull: newRelation.DeleteAction = Relation.DeleteActionConstants.SetNull; break; } newRelation.Enforce = relation.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)); } } } } } } //inner block #endregion #region Views foreach (var view in model.Views) { 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.Name = view.Name; newView.SQL = view.SQL; newView.GeneratesDoubleDerived = view.GeneratesDoubleDerived; 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.IsPrimaryKey = field.IsPrimaryKey; 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 return(root); } catch (Exception ex) { throw; } }
/// <summary> /// Convert a new DSL model into a data import model /// </summary> /// <param name="model"></param> /// <param name="diagram"></param> /// <returns></returns> public static nHydrate.DataImport.Database Convert(nHydrateModel model, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram) { var database = new nHydrate.DataImport.Database(); #region Load the entities foreach (var entity in model.Entities) { var newEntity = new nHydrate.DataImport.Entity(); newEntity.ID = entity.Id; newEntity.Name = entity.Name; newEntity.Schema = entity.Schema; newEntity.AllowCreateAudit = entity.AllowCreateAudit; newEntity.AllowModifyAudit = entity.AllowModifyAudit; newEntity.AllowTimestamp = entity.AllowTimestamp; newEntity.IsTenant = entity.IsTenant; database.EntityList.Add(newEntity); #region Load the fields foreach (var field in entity.Fields) { var newField = new nHydrate.DataImport.Field(); newField.ID = field.Id; newField.Nullable = field.Nullable; newField.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString()); newField.DefaultValue = field.Default; newField.Identity = (field.Identity == IdentityTypeConstants.Database); newField.IsIndexed = field.IsIndexed; newField.IsReadOnly = field.IsReadOnly; newField.Length = field.Length; newField.Name = field.Name; newField.PrimaryKey = field.IsPrimaryKey; newField.Scale = field.Scale; newEntity.FieldList.Add(newField); } #endregion } #endregion #region Load Relations foreach (var shape in diagram.NestedChildShapes) { 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 parentTable = database.EntityList.FirstOrDefault(x => parent != null && x.Name == parent.Name); var childTable = database.EntityList.FirstOrDefault(x => child != null && x.Name == child.Name); //If we found both parent and child tables... if (parentTable != null && childTable != null) { var newRelation = new nHydrate.DataImport.Relationship(); newRelation.ID = shape.Id; newRelation.TargetEntity = childTable; newRelation.RoleName = ((EntityHasEntities)connector.ModelElement).RoleName; newRelation.SourceEntity = parentTable; parentTable.RelationshipList.Add(newRelation); //Create the column links var fieldList = model.RelationFields.Where(x => relation != null && x.RelationID == relation.Id); 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.FieldList.FirstOrDefault(x => field1 != null && x.Name == field1.Name); var column2 = childTable.FieldList.FirstOrDefault(x => field2 != null && x.Name == field2.Name); newRelation.RelationshipColumnList.Add(new nHydrate.DataImport.RelationshipDetail() { ParentField = column1, ChildField = column2, } ); } } } } #endregion #region Load Views foreach (var view in model.Views) { var newView = new nHydrate.DataImport.View(); newView.ID = view.Id; newView.Name = view.Name; newView.Schema = view.Schema; newView.SQL = view.SQL; database.ViewList.Add(newView); //Load the fields foreach (var field in view.Fields) { var newField = new nHydrate.DataImport.Field(); newField.ID = field.Id; newField.Nullable = field.Nullable; //newField.Collate = field.Collate; newField.DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), field.DataType.ToString()); newField.DefaultValue = field.Default; //newField.Identity = (field.Identity == IdentityTypeConstants.Database); //newField.IsIndexed = field.IsIndexed; newField.Length = field.Length; newField.Name = field.Name; //newField.PrimaryKey = field.IsPrimaryKey; newField.Scale = field.Scale; newView.FieldList.Add(newField); } } #endregion return(database); }
public static void ImportDatabase(nHydrate.Dsl.nHydrateModel model, Store store, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, nHydrate.DataImport.Database database) { ((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 diagramViews = model.Views.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)); //} //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 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 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.MakeCodeIdentifier(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; PopulateFields(model, 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 //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 (!connection.ChildEntity.Name.Match(relation.TargetEntity.Name) || !connection.ParentEntity.Name.Match(relation.SourceEntity.Name)) { 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 Views foreach (var view in database.ViewList.Where(x => x.ImportState == DataImport.ImportStateConstants.Added || x.ImportState == DataImport.ImportStateConstants.Modified)) { var newView = diagramViews.FirstOrDefault(x => x.Id == view.ID); 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.MakeCodeIdentifier(newView.Name, string.Empty); } } newView.Name = view.Name; 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 transaction.Commit(); } } catch (Exception ex) { throw; } finally { model.IsLoading = false; ProgressHelper.ProgressingComplete(pkey); ((nHydrate.Dsl.nHydrateDiagram)diagram).IsLoading = false; model.IsLoading = false; } }
public static Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement GetEntity(this Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, string entityName) { foreach (var item in diagram.NestedChildShapes) { if (item.ModelElement is Entity) { var e = item.ModelElement as Entity; if (e != null && e.Name == entityName) { return(item); } } } return(null); }
public ImportDatabaseForm( nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store, Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, nHydrate.DataImport.Database currentDatabase, Microsoft.VisualStudio.Modeling.Shell.ModelingDocData docData) : this() { _model = model; _store = store; _diagram = diagram; _docData = docData; this.CurrentDatabase = currentDatabase; this.DatabaseConnectionControl1.FileName = Path.Combine((new FileInfo(docData.FileName)).DirectoryName, "importconnection.cache"); tvwAdd.AfterCheck += new TreeViewEventHandler(treeView1_AfterCheck); tvwRefresh.AfterCheck += new TreeViewEventHandler(treeView1_AfterCheck); tvwDelete.AfterCheck += new TreeViewEventHandler(treeView1_AfterCheck); //tvwAdd.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect); //tvwRefresh.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect); //tvwDelete.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect); wizard1.BeforeSwitchPages += new nHydrate.Wizard.Wizard.BeforeSwitchPagesEventHandler(wizard1_BeforeSwitchPages); wizard1.AfterSwitchPages += new nHydrate.Wizard.Wizard.AfterSwitchPagesEventHandler(wizard1_AfterSwitchPages); wizard1.Finish += new EventHandler(wizard1_Finish); wizard1.FinishEnabled = false; chkSettingPK.CheckedChanged += new EventHandler(chkSettingPK_CheckedChanged); cmdTestConnection.Click += new EventHandler(cmdTestConnection_Click); this.Settings = new ImportModelSettings(); this.Settings.OverridePrimaryKey = chkSettingPK.Checked; DatabaseConnectionControl1.LoadSettings(); cboModule.Items.Add("(Choose One)"); model.Modules.ForEach(x => cboModule.Items.Add(x.Name)); cboModule.SelectedIndex = 0; cboModule.Enabled = model.UseModules; chkMergeModule.Visible = model.UseModules; EnableButtons(); }