public RefactorCombineTableForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity1, Entity entity2)
			: this()
		{
			_store = store;
			_model = model;
			_diagram = diagram;
			_entity1 = entity1;
			_entity2 = entity2;

			lblEntity1.Text = entity1.Name;
			lblEntity2.Text = entity2.Name;

			var fieldList = new List<Field>();
			fieldList.AddRange(entity1.Fields);
			fieldList.AddRange(entity2.Fields);
			fieldList.Remove(x => entity2.PrimaryKeyFields.Contains(x));

			if (fieldList.Select(x => x.Name.ToLower()).Count() != fieldList.Select(x => x.Name.ToLower()).Distinct().Count())
			{
				cmdApply.Enabled = false;
				lblError.Text = "Duplicate field names are not allowed.";
				lblError.Visible = true;
			}

			fieldList.ForEach(x => lstField.Items.Add(x.Name));
		}
Beispiel #2
0
 public static void SaveToDisk(nHydrateModel modelRoot, string rootFolder, string modelName, nHydrateDiagram diagram)
 {
     modelRoot.IsSaving = true;
     try
     {
         var modelFolder = GetModelFolder(rootFolder, modelName);
         var generatedFileList = new List<string>();
         nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.ModelMetadata, modelFolder, diagram, generatedFileList);
         nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Modules, modelFolder, diagram, generatedFileList);
         nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Views, modelFolder, diagram, generatedFileList); //must come before entities (view relations)
         nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Entities, modelFolder, diagram, generatedFileList);
         nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.StoredProcedures, modelFolder, diagram, generatedFileList);
         nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Functions, modelFolder, diagram, generatedFileList);
         nHydrate.Dsl.Custom.SQLFileManagement.SaveDiagramFiles(modelFolder, diagram, generatedFileList);
         RemoveOrphans(modelFolder, generatedFileList);
     }
     catch (Exception ex)
     {
         throw;
     }
     finally
     {
         modelRoot.IsSaving = false;
     }
 }
 public ModelUtilitiesForm(nHydrateModel model, Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram)
     : this()
 {
     _model = model;
     _store = store;
     _diagram = diagram;
 }
		public RefactorPreviewCreateAssociativeForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity1, Entity entity2)
			: this()
		{
			_store = store;
			_model = model;
			_diagram = diagram;
			_entity1 = entity1;
			_entity2 = entity2;

			lblEntity1.Text = entity1.Name;
			lblEntity2.Text = entity2.Name;
			txtName.Text = _entity1.Name + _entity2.Name;
		}
		public RefactorSplitTableForm(Microsoft.VisualStudio.Modeling.Store store, nHydrateDiagram diagram, nHydrateModel model, Entity entity)
			: this()
		{
			_store = store;
			_model = model;
			_diagram = diagram;
			_entity = entity;
			wizard1.FinishEnabled = false;
			lblSourceEntity.Text = entity.Name;

			foreach (var field in entity.Fields.Where(x => !x.IsPrimaryKey).OrderBy(x => x.Name))
			{
				lstField1.Items.Add(new DisplayFieldItem() { Field = field });
			}
		}
Beispiel #6
0
        /// <summary>
        /// Saves Stored Procedures to disk
        /// </summary>
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<Entity> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            var folder = Path.Combine(rootFolder, FOLDER_ET);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            #region Save other parameter/field information
            foreach (var item in list)
            {
                var document = new XmlDocument();
                document.LoadXml(@"<configuration type=""entity"" name=""" + item.Name + @"""></configuration>");

                XmlHelper.AddLineBreak(document.DocumentElement);
                XmlHelper.AddCData(document.DocumentElement, "summary", item.Summary);
                XmlHelper.AddLineBreak(document.DocumentElement);

                XmlHelper.AddAttribute(document.DocumentElement, "id", item.Id);
                XmlHelper.AddAttribute(document.DocumentElement, "allowaudittracking", item.AllowAuditTracking);
                XmlHelper.AddAttribute(document.DocumentElement, "allowcreateaudit", item.AllowCreateAudit);
                XmlHelper.AddAttribute(document.DocumentElement, "allowmodifyaudit", item.AllowModifyAudit);
                XmlHelper.AddAttribute(document.DocumentElement, "allowtimestamp", item.AllowTimestamp);
                XmlHelper.AddAttribute(document.DocumentElement, "codefacade", item.CodeFacade);
                XmlHelper.AddAttribute(document.DocumentElement, "immutable", item.Immutable);
                XmlHelper.AddAttribute(document.DocumentElement, "enforceprimarykey", item.EnforcePrimaryKey);
                XmlHelper.AddAttribute(document.DocumentElement, "isassociative", item.IsAssociative);
                XmlHelper.AddAttribute(document.DocumentElement, "typedentity", item.TypedEntity.ToString());
                XmlHelper.AddAttribute(document.DocumentElement, "schema", item.Schema);
                XmlHelper.AddAttribute(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived);
                XmlHelper.AddAttribute(document.DocumentElement, "isgenerated", item.IsGenerated);
                XmlHelper.AddAttribute(document.DocumentElement, "isTenant", item.IsTenant);

                #region Fields
                {
                    var fieldsNodes = XmlHelper.AddElement(document.DocumentElement, "fieldset") as XmlElement;
                    XmlHelper.AddLineBreak((XmlElement)fieldsNodes);
                    foreach (var field in item.Fields.OrderBy(x => x.Name))
                    {
                        var fieldNode = XmlHelper.AddElement(fieldsNodes, "field");

                        XmlHelper.AddLineBreak((XmlElement)fieldNode);
                        XmlHelper.AddCData((XmlElement)fieldNode, "summary", field.Summary);
                        XmlHelper.AddLineBreak((XmlElement)fieldNode);

                        XmlHelper.AddAttribute(fieldNode, "id", field.Id);
                        XmlHelper.AddAttribute(fieldNode, "name", field.Name);
                        XmlHelper.AddAttribute(fieldNode, "nullable", field.Nullable);
                        XmlHelper.AddAttribute(fieldNode, "datatype", field.DataType.ToString());
                        XmlHelper.AddAttribute(fieldNode, "identity", field.Identity.ToString());
                        XmlHelper.AddAttribute(fieldNode, "codefacade", field.CodeFacade);
                        XmlHelper.AddAttribute(fieldNode, "dataformatstring", field.DataFormatString);
                        XmlHelper.AddAttribute(fieldNode, "default", field.Default);
                        XmlHelper.AddAttribute(fieldNode, "defaultisfunc", field.DefaultIsFunc);
                        XmlHelper.AddAttribute(fieldNode, "formula", field.Formula);
                        XmlHelper.AddAttribute(fieldNode, "isgenerated", field.IsGenerated);
                        XmlHelper.AddAttribute(fieldNode, "isindexed", field.IsIndexed);
                        XmlHelper.AddAttribute(fieldNode, "isprimarykey", field.IsPrimaryKey);
                        XmlHelper.AddAttribute(fieldNode, "Iscalculated", field.IsCalculated);
                        XmlHelper.AddAttribute(fieldNode, "isunique", field.IsUnique);
                        XmlHelper.AddAttribute(fieldNode, "length", field.Length);
                        XmlHelper.AddAttribute(fieldNode, "scale", field.Scale);
                        XmlHelper.AddAttribute(fieldNode, "sortorder", field.SortOrder);
                        XmlHelper.AddAttribute(fieldNode, "isreadonly", field.IsReadOnly);
                        XmlHelper.AddAttribute(fieldNode, "category", field.Category);
                        XmlHelper.AddAttribute(fieldNode, "collate", field.Collate);
                        XmlHelper.AddAttribute(fieldNode, "friendlyname", field.FriendlyName);
                        XmlHelper.AddAttribute(fieldNode, "isbrowsable", field.IsBrowsable);
                        XmlHelper.AddAttribute(fieldNode, "max", field.Max);
                        XmlHelper.AddAttribute(fieldNode, "min", field.Min);
                        XmlHelper.AddAttribute(fieldNode, "validationexpression", field.ValidationExpression);
                        XmlHelper.AddAttribute(fieldNode, "obsolete", field.Obsolete);

                        XmlHelper.AddLineBreak((XmlElement)fieldsNodes);
                    }
                    XmlHelper.AddLineBreak((XmlElement)document.DocumentElement);
                }
                #endregion

                #region Security

                if (item.SecurityFunction != null)
                {
                    var secNode = XmlHelper.AddElement(document.DocumentElement, "security") as XmlElement;

                    XmlHelper.AddAttribute(secNode, "id", item.SecurityFunction.Id);

                    var ff = Path.Combine(folder, item.Name + ".security.sql");
                    WriteFileIfNeedBe(ff, item.SecurityFunction.SQL, generatedFileList);

                    //Parameters
                    var secParamNodes = XmlHelper.AddElement(secNode, "parameterset") as XmlElement;
                    XmlHelper.AddLineBreak((XmlElement)secParamNodes);
                    foreach (var parameter in item.SecurityFunction.SecurityFunctionParameters.OrderBy(x => x.Name))
                    {
                        var parameterNode = XmlHelper.AddElement(secParamNodes, "field");

                        XmlHelper.AddLineBreak((XmlElement)parameterNode);
                        XmlHelper.AddCData((XmlElement)parameterNode, "summary", parameter.Summary);
                        XmlHelper.AddLineBreak((XmlElement)parameterNode);

                        XmlHelper.AddAttribute(parameterNode, "id", parameter.Id);
                        XmlHelper.AddAttribute(parameterNode, "name", parameter.Name);
                        XmlHelper.AddAttribute(parameterNode, "nullable", parameter.Nullable);
                        XmlHelper.AddAttribute(parameterNode, "datatype", parameter.DataType.ToString());
                        XmlHelper.AddAttribute(parameterNode, "codefacade", parameter.CodeFacade);
                        XmlHelper.AddAttribute(parameterNode, "default", parameter.Default);
                        XmlHelper.AddAttribute(parameterNode, "isgenerated", parameter.IsGenerated);
                        XmlHelper.AddAttribute(parameterNode, "length", parameter.Length);
                        XmlHelper.AddAttribute(parameterNode, "scale", parameter.Scale);
                    }
                }

                #endregion

                XmlHelper.AddLineBreak(document.DocumentElement);
                var f = Path.Combine(folder, item.Name + ".configuration.xml");
                WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);

                //Save other files
                SaveEntityIndexes(folder, item, generatedFileList);
                SaveModules(folder, item, generatedFileList);
                SaveRelations(folder, item, generatedFileList);
                SaveEntityStaticData(folder, item, generatedFileList);
                SaveEntityMetaData(folder, item, generatedFileList);
                SaveEntityComposites(folder, item, generatedFileList);

            }
            #endregion

            WriteReadMeFile(folder, generatedFileList);
        }
Beispiel #7
0
        /// <summary>
        /// Saves Functions to disk
        /// </summary>
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<Function> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            var folder = Path.Combine(rootFolder, FOLDER_FC);
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
            foreach (var item in list)
            {
                var f = Path.Combine(folder, item.Name + ".sql");
                WriteFileIfNeedBe(f, item.SQL, generatedFileList);
            }

            #region Save other parameter/field information
            foreach (var item in list)
            {
                var document = new XmlDocument();
                document.LoadXml(@"<configuration type=""function"" name=""" + item.Name + @"""></configuration>");

                XmlHelper.AddLineBreak(document.DocumentElement);
                XmlHelper.AddCData(document.DocumentElement, "summary", item.Summary);
                XmlHelper.AddLineBreak(document.DocumentElement);

                XmlHelper.AddAttribute(document.DocumentElement, "id", item.Id);
                XmlHelper.AddAttribute(document.DocumentElement, "precedenceorder", item.PrecedenceOrder);
                XmlHelper.AddAttribute(document.DocumentElement, "codefacade", item.CodeFacade);
                XmlHelper.AddAttribute(document.DocumentElement, "isgenerated", item.IsGenerated);
                XmlHelper.AddAttribute(document.DocumentElement, "schema", item.Schema);
                XmlHelper.AddAttribute(document.DocumentElement, "istable", item.IsTable);
                XmlHelper.AddAttribute(document.DocumentElement, "returnvariable", item.ReturnVariable);

                var fieldsNodes = XmlHelper.AddElement(document.DocumentElement, "fieldset") as XmlElement;
                XmlHelper.AddLineBreak((XmlElement)fieldsNodes);

                foreach (var field in item.Fields.OrderBy(x => x.Name))
                {
                    var fieldNode = XmlHelper.AddElement(fieldsNodes, "field");

                    XmlHelper.AddLineBreak((XmlElement)fieldNode);
                    XmlHelper.AddCData((XmlElement)fieldNode, "summary", field.Summary);
                    XmlHelper.AddLineBreak((XmlElement)fieldNode);

                    XmlHelper.AddAttribute(fieldNode, "id", field.Id);
                    XmlHelper.AddAttribute(fieldNode, "name", field.Name);
                    XmlHelper.AddAttribute(fieldNode, "nullable", field.Nullable);
                    XmlHelper.AddAttribute(fieldNode, "datatype", field.DataType.ToString());
                    XmlHelper.AddAttribute(fieldNode, "codefacade", field.CodeFacade);
                    XmlHelper.AddAttribute(fieldNode, "default", field.Default);
                    XmlHelper.AddAttribute(fieldNode, "isgenerated", field.IsGenerated);
                    XmlHelper.AddAttribute(fieldNode, "length", field.Length);
                    XmlHelper.AddAttribute(fieldNode, "scale", field.Scale);

                    XmlHelper.AddLineBreak((XmlElement)fieldsNodes);
                }

                var parametersNodes = XmlHelper.AddElement(document.DocumentElement, "parameterset") as XmlElement;
                XmlHelper.AddLineBreak((XmlElement)parametersNodes);

                foreach (var parameter in item.Parameters.OrderBy(x => x.Name))
                {
                    var parameterNode = XmlHelper.AddElement(parametersNodes, "parameter");

                    XmlHelper.AddLineBreak((XmlElement)parameterNode);
                    XmlHelper.AddCData((XmlElement)parameterNode, "summary", parameter.Summary);
                    XmlHelper.AddLineBreak((XmlElement)parameterNode);

                    XmlHelper.AddAttribute(parameterNode, "id", parameter.Id);
                    XmlHelper.AddAttribute(parameterNode, "name", parameter.Name);
                    XmlHelper.AddAttribute(parameterNode, "nullable", parameter.Nullable);
                    XmlHelper.AddAttribute(parameterNode, "datatype", parameter.DataType.ToString());
                    XmlHelper.AddAttribute(parameterNode, "codefacade", parameter.CodeFacade);
                    XmlHelper.AddAttribute(parameterNode, "default", parameter.Default);
                    XmlHelper.AddAttribute(parameterNode, "isgenerated", parameter.IsGenerated);
                    XmlHelper.AddAttribute(parameterNode, "length", parameter.Length);
                    XmlHelper.AddAttribute(parameterNode, "scale", parameter.Scale);

                    XmlHelper.AddLineBreak((XmlElement)parametersNodes);
                }

                XmlHelper.AddLineBreak(document.DocumentElement);
                var f = Path.Combine(folder, item.Name + ".configuration.xml");
                WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);

                //Save other files
                SaveModules(folder, item, generatedFileList);

            }
            #endregion

            WriteReadMeFile(folder, generatedFileList);
        }
Beispiel #8
0
 private static void SaveDiagramFiles(string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
 {
     var fileName = Path.Combine(rootFolder, "diagram.xml");
     var document = new XmlDocument();
     document.LoadXml(@"<configuration type=""diagram""></configuration>");
     foreach (var shape in diagram.NestedChildShapes)
     {
         if (shape is EntityShape)
         {
             var item = ((shape as EntityShape).ModelElement as Entity);
             var node = XmlHelper.AddElement(document.DocumentElement, "element");
             XmlHelper.AddAttribute(node, "id", shape.ModelElement.Id);
             XmlHelper.AddAttribute(node, "bounds", shape.AbsoluteBoundingBox.ToXmlValue());
         }
         else if (shape is ViewShape)
         {
             var item = ((shape as ViewShape).ModelElement as View);
             var node = XmlHelper.AddElement(document.DocumentElement, "element");
             XmlHelper.AddAttribute(node, "id", shape.ModelElement.Id);
             XmlHelper.AddAttribute(node, "bounds", shape.AbsoluteBoundingBox.ToXmlValue());
         }
         else if (shape is StoredProcedureShape)
         {
             var item = ((shape as StoredProcedureShape).ModelElement as StoredProcedure);
             var node = XmlHelper.AddElement(document.DocumentElement, "element");
             XmlHelper.AddAttribute(node, "id", shape.ModelElement.Id);
             XmlHelper.AddAttribute(node, "bounds", shape.AbsoluteBoundingBox.ToXmlValue());
         }
         else if (shape is FunctionShape)
         {
             var item = ((shape as FunctionShape).ModelElement as Function);
             var node = XmlHelper.AddElement(document.DocumentElement, "element");
             XmlHelper.AddAttribute(node, "id", shape.ModelElement.Id);
             XmlHelper.AddAttribute(node, "bounds", shape.AbsoluteBoundingBox.ToXmlValue());
         }
     }
     WriteFileIfNeedBe(fileName, document.ToIndentedString(), generatedFileList);
 }
		internal global::System.IO.MemoryStream InternalSaveDiagram(DslModeling::SerializationResult serializationResult, nHydrateDiagram diagram, string diagramFileName, global::System.Text.Encoding encoding, bool writeOptionalPropertiesWithDefaultValue)
		{
			#region Check Parameters
			global::System.Diagnostics.Debug.Assert(serializationResult != null);
			global::System.Diagnostics.Debug.Assert(diagram != null);
			global::System.Diagnostics.Debug.Assert(!serializationResult.Failed);
			#endregion
	
			DslModeling::DomainXmlSerializerDirectory directory = this.GetDirectory(diagram.Store);
	
			
			global::System.IO.MemoryStream newFileContent = new global::System.IO.MemoryStream();
			
			DslModeling::SerializationContext serializationContext = new DslModeling::SerializationContext(directory, diagramFileName, serializationResult);
			this.InitializeSerializationContext(diagram.Partition, serializationContext, false);
			// MonikerResolver shouldn't be required in Save operation, so not calling SetupMonikerResolver() here.
			serializationContext.WriteOptionalPropertiesWithDefaultValue = writeOptionalPropertiesWithDefaultValue;
			global::System.Xml.XmlWriterSettings settings = nHydrateSerializationHelper.Instance.CreateXmlWriterSettings(serializationContext, true, encoding);
			using (global::System.Xml.XmlWriter writer = global::System.Xml.XmlWriter.Create(newFileContent, settings))
			{
				this.WriteRootElement(serializationContext, diagram, writer);
			}
	
			return newFileContent;
		}
Beispiel #10
0
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<ModelMetadata> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            if (!list.Any())
                return;

            var document = new XmlDocument();
            document.LoadXml(@"<configuration type=""model.metadata""></configuration>");

            XmlHelper.AddLineBreak((XmlElement)document.DocumentElement);
            foreach (var metadata in list)
            {
                var metaDataNode = XmlHelper.AddElement(document.DocumentElement, "metadata");
                XmlHelper.AddAttribute(metaDataNode, "key", metadata.Key);
                XmlHelper.AddAttribute(metaDataNode, "value", metadata.Value);
                XmlHelper.AddLineBreak((XmlElement)document.DocumentElement);
            }

            var f = Path.Combine(rootFolder, "metadata.configuration.xml");
            WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);
        }
Beispiel #11
0
 private void OnPostLoadModelAndDiagram(DslModeling::SerializationResult serializationResult, DslModeling::Partition modelPartition, string modelFileName, DslModeling::Partition diagramPartition, string diagramFileName, nHydrateModel modelRoot, nHydrateDiagram diagram)
 {
 }
        /// <summary>
        /// Customize Model and Diagram Loading.
        /// </summary>
        /// <param name="serializationResult">Stores serialization result from the load operation.</param>
        /// <param name="modelPartition">Partition in which the new DslLibrary instance will be created.</param>
        /// <param name="modelFileName">Name of the file from which the DslLibrary instance will be deserialized.</param>
        /// <param name="diagramPartition">Partition in which the new DslDesignerDiagram instance will be created.</param>
        /// <param name="diagramFileName">Name of the file from which the DslDesignerDiagram instance will be deserialized.</param>
        /// <param name="modelRoot">The root of the file that was loaded.</param>
        /// <param name="diagram">The diagram matching the modelRoot.</param>
        private void OnPostLoadModelAndDiagram(DslModeling::SerializationResult serializationResult, DslModeling::Partition modelPartition, string modelFileName, DslModeling::Partition diagramPartition, string diagramFileName, nHydrateModel modelRoot, nHydrateDiagram diagram)
        {

        }
Beispiel #13
0
        /// <summary>
        /// Saves Modules to disk
        /// </summary>
        private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<Module> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList)
        {
            var folder = rootFolder;
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

            var document = new XmlDocument();
            document.LoadXml(@"<configuration type=""module""></configuration>");

            foreach (var item in list)
            {
                var moduleNode = XmlHelper.AddElement(document.DocumentElement, "module") as XmlElement;
                XmlHelper.AddLineBreak(moduleNode);
                XmlHelper.AddCData(moduleNode, "summary", item.Summary);
                XmlHelper.AddAttribute(moduleNode, "id", item.Id);
                XmlHelper.AddAttribute(moduleNode, "name", item.Name);
                XmlHelper.AddLineBreak(moduleNode);

                var rulesNodes = XmlHelper.AddElement(moduleNode, "ruleset") as XmlElement;
                XmlHelper.AddLineBreak((XmlElement)rulesNodes);

                foreach (var rule in item.ModuleRules.OrderBy(x => x.Name))
                {
                    var fieldNode = XmlHelper.AddElement(rulesNodes, "rule");

                    XmlHelper.AddLineBreak((XmlElement)fieldNode);
                    XmlHelper.AddCData((XmlElement)fieldNode, "summary", rule.Summary);
                    XmlHelper.AddLineBreak((XmlElement)fieldNode);

                    XmlHelper.AddAttribute(fieldNode, "status", rule.Status.ToString("d"));
                    XmlHelper.AddAttribute(fieldNode, "dependentmodule", rule.DependentModule);
                    XmlHelper.AddAttribute(fieldNode, "name", rule.Name);
                    XmlHelper.AddAttribute(fieldNode, "inclusion", rule.Inclusion);
                    XmlHelper.AddAttribute(fieldNode, "enforced", rule.Enforced);

                    XmlHelper.AddLineBreak((XmlElement)rulesNodes);
                }

            }

            var f = Path.Combine(folder, "modules.configuration.xml");
            WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList);
            WriteReadMeFile(folder, generatedFileList);
        }
		internal protected virtual nHydrateDiagram CreateDiagramHelper(DslModeling::Partition diagramPartition, DslModeling::ModelElement modelRoot)
		{
			nHydrateDiagram diagram = new nHydrateDiagram(diagramPartition);
			return diagram;
		}
		public virtual void SaveModelAndDiagram(DslModeling::SerializationResult serializationResult, nHydrateModel modelRoot, string modelFileName, nHydrateDiagram diagram, string diagramFileName, global::System.Text.Encoding encoding, bool writeOptionalPropertiesWithDefaultValue)
		{
			#region Check Parameters
			if (serializationResult == null)
				throw new global::System.ArgumentNullException("serializationResult");
			if (string.IsNullOrEmpty(modelFileName))
				throw new global::System.ArgumentNullException("modelFileName");
			if (diagram == null)
				throw new global::System.ArgumentNullException("diagram");
			if (string.IsNullOrEmpty(diagramFileName))
				throw new global::System.ArgumentNullException("diagramFileName");
			#endregion
	
			if (serializationResult.Failed)
				return;
	
			// Save the model file first
			using (global::System.IO.MemoryStream modelFileContent = this.InternalSaveModel(serializationResult, modelRoot, modelFileName, encoding, writeOptionalPropertiesWithDefaultValue))
			{
				if (serializationResult.Failed)
					return;
	
				using (global::System.IO.MemoryStream diagramFileContent = this.InternalSaveDiagram(serializationResult, diagram, diagramFileName, encoding, writeOptionalPropertiesWithDefaultValue))
				{
					if (!serializationResult.Failed)
					{
						// Only write the contents if there's no error encountered during serialization.
						if (modelFileContent != null)
						{
							using (global::System.IO.FileStream fileStream = new global::System.IO.FileStream(modelFileName, global::System.IO.FileMode.Create, global::System.IO.FileAccess.Write, global::System.IO.FileShare.None))
							{
								using (global::System.IO.BinaryWriter writer = new global::System.IO.BinaryWriter(fileStream, encoding))
								{
									writer.Write(modelFileContent.ToArray());
								}
							}
						}
						if (diagramFileContent != null)
						{
							using (global::System.IO.FileStream fileStream = new global::System.IO.FileStream(diagramFileName, global::System.IO.FileMode.Create, global::System.IO.FileAccess.Write, global::System.IO.FileShare.None))
							{
								using (global::System.IO.BinaryWriter writer = new global::System.IO.BinaryWriter(fileStream, encoding))
								{
									writer.Write(diagramFileContent.ToArray());
								}
							}
						}
					}
				}
			}
		}
		/// <summary>
		/// Saves the given diagram to the given file, with default encoding (UTF-8).
		/// </summary>
		/// <param name="serializationResult">Stores serialization result from the save operation.</param>
		/// <param name="modelRoot">nHydrateModel instance to be saved.</param>
		/// <param name="modelFileName">Name of the file in which the CanonicalSampleRoot instance will be saved.</param>
		/// <param name="diagram">nHydrateDiagram to be saved.</param>
		/// <param name="diagramFileName">Name of the file in which the diagram will be saved.</param>
		/// <param name="writeOptionalPropertiesWithDefaultValue">Whether optional properties with default value will be saved.</param>
		public virtual void SaveModelAndDiagram(DslModeling::SerializationResult serializationResult, nHydrateModel modelRoot, string modelFileName, nHydrateDiagram diagram, string diagramFileName, bool writeOptionalPropertiesWithDefaultValue)
		{
			this.SaveModelAndDiagram(serializationResult, modelRoot, modelFileName, diagram, diagramFileName, global::System.Text.Encoding.UTF8, writeOptionalPropertiesWithDefaultValue);
		}
		/// <summary>
		/// Saves the given diagram to the given file, with default encoding (UTF-8), and optional properties with default value will not
		/// be written out.
		/// </summary>
		/// <param name="serializationResult">Stores serialization result from the save operation.</param>
		/// <param name="modelRoot">nHydrateModel instance to be saved.</param>
		/// <param name="modelFileName">Name of the file in which the CanonicalSampleRoot instance will be saved.</param>
		/// <param name="diagram">nHydrateDiagram to be saved.</param>
		/// <param name="diagramFileName">Name of the file in which the diagram will be saved.</param>
		public virtual void SaveModelAndDiagram(DslModeling::SerializationResult serializationResult, nHydrateModel modelRoot, string modelFileName, nHydrateDiagram diagram, string diagramFileName)
		{
			this.SaveModelAndDiagram(serializationResult, modelRoot, modelFileName, diagram, diagramFileName, global::System.Text.Encoding.UTF8, false);
		}
Beispiel #18
0
        public override void SaveModelAndDiagram(Microsoft.VisualStudio.Modeling.SerializationResult serializationResult, nHydrateModel modelRoot, string modelFileName, nHydrateDiagram diagram, string diagramFileName, Encoding encoding,
                                                 bool writeOptionalPropertiesWithDefaultValue)
        {
            var mainInfo = new FileInfo(modelFileName);

            modelRoot.ModelFileName = modelFileName;
            nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, mainInfo.DirectoryName, mainInfo.Name, diagram);
            base.SaveModelAndDiagram(serializationResult, modelRoot, modelFileName, diagram, diagramFileName, encoding, writeOptionalPropertiesWithDefaultValue);

            //Model File
            if (modelRoot.ModelToDisk)
            {
                var document = new XmlDocument();
                document.Load(modelFileName);

                //Remove entire node for Views, Stored Procedures, and Functions
                for (var ii = document.DocumentElement.ChildNodes.Count - 1; ii >= 0; ii--)
                {
                    var n = document.DocumentElement.ChildNodes[ii];
                    document.DocumentElement.RemoveChild(n);
                }

                document.Save(modelFileName);
            }

            //Diagram File
            //Now gut the diagram file
            var diagramFile = modelFileName + ".diagram";

            if (modelRoot.ModelToDisk)
            {
                if (File.Exists(diagramFile))
                {
                    var document = new XmlDocument();
                    document.Load(diagramFile);

                    //Remove all child nodes
                    var n = document.DocumentElement.SelectSingleNode("nestedChildShapes");
                    if (n != null)
                    {
                        document.DocumentElement.RemoveChild(n);
                        document.Save(diagramFile);
                    }
                }
            }
            else
            {
                //strip out all the colors from the diagram file
                if (File.Exists(diagramFile))
                {
                    var document = new XmlDocument();
                    document.Load(diagramFile);
                    var list = document.DocumentElement.SelectNodes("//elementListCompartment");
                    foreach (XmlNode n in list)
                    {
                        n.Attributes.RemoveNamedItem("fillColor");
                        n.Attributes.RemoveNamedItem("outlineColor");
                        n.Attributes.RemoveNamedItem("textColor");
                        n.Attributes.RemoveNamedItem("titleTextColor");
                        n.Attributes.RemoveNamedItem("itemTextColor");
                    }

                    document.Save(diagramFile);
                }
            }
        }
        public override void SaveModelAndDiagram(Microsoft.VisualStudio.Modeling.SerializationResult serializationResult, nHydrateModel modelRoot, string modelFileName, nHydrateDiagram diagram, string diagramFileName, Encoding encoding, bool writeOptionalPropertiesWithDefaultValue)
        {
            var mainInfo = new FileInfo(modelFileName);

            modelRoot.ModelFileName = modelFileName;
            var modelName = mainInfo.Name.Replace(".nhydrate", ".model");

            if (modelRoot.ModelToDisk)
            {
                nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, mainInfo.DirectoryName, modelName, diagram);
            }
            else
            {
                try
                {
                    var f = nHydrate.Dsl.Custom.SQLFileManagement.GetModelFolder(mainInfo.DirectoryName, modelName);
                    if (Directory.Exists(f))
                    {
                        Directory.Delete(f, true);
                    }
                }
                catch
                {
                }
            }

            base.SaveModelAndDiagram(serializationResult, modelRoot, modelFileName, diagram, diagramFileName, encoding, writeOptionalPropertiesWithDefaultValue);

            //Model File
            if (modelRoot.ModelToDisk)
            {
                var document = new XmlDocument();
                document.Load(modelFileName);

                //Remove entire node for Views, Stored Procedures, and Functions
                for (var ii = document.DocumentElement.ChildNodes.Count - 1; ii >= 0; ii--)
                {
                    var n = document.DocumentElement.ChildNodes[ii];
                    document.DocumentElement.RemoveChild(n);
                }

                document.Save(modelFileName);
            }

            //Diagram File
            //Now gut the diagram file
            var diagramFile = modelFileName + ".diagram";

            if (modelRoot.ModelToDisk)
            {
                if (File.Exists(diagramFile))
                {
                    var document = new XmlDocument();
                    document.Load(diagramFile);

                    //Remove all child nodes
                    var n = document.DocumentElement.SelectSingleNode("nestedChildShapes");
                    if (n != null)
                    {
                        document.DocumentElement.RemoveChild(n);
                        document.Save(diagramFile);
                    }

                    ////Reset position attributes
                    //var nlist = document.DocumentElement.SelectNodes("//entityShape");
                    //foreach (XmlElement node in nlist)
                    //{
                    //  //XmlHelper.RemoveAttribute(node, "absoluteBounds");
                    //  XmlHelper.AddAttribute(node, "absoluteBounds", "0, 0, 0, 0");
                    //  var clist = node.SelectNodes("nestedChildShapes/elementListCompartment");
                    //  foreach (XmlElement node2 in clist)
                    //  {
                    //    //XmlHelper.RemoveAttribute(node2, "absoluteBounds");
                    //    XmlHelper.AddAttribute(node2, "absoluteBounds", "0, 0, 0, 0");
                    //  }
                    //}
                    //document.Save(diagramFile);
                }
            }
            else
            {
                //strip out all the colors from the diagram file
                if (File.Exists(diagramFile))
                {
                    var document = new XmlDocument();
                    document.Load(diagramFile);
                    var list = document.DocumentElement.SelectNodes("//elementListCompartment");
                    foreach (XmlNode n in list)
                    {
                        n.Attributes.RemoveNamedItem("fillColor");
                        n.Attributes.RemoveNamedItem("outlineColor");
                        n.Attributes.RemoveNamedItem("textColor");
                        n.Attributes.RemoveNamedItem("titleTextColor");
                        n.Attributes.RemoveNamedItem("itemTextColor");
                    }
                    document.Save(diagramFile);
                }
            }

            //Save the refactorizations
            if (modelRoot.Refactorizations.Count > 0)
            {
                var document = new XmlDocument();
                document.Load(modelFileName);
                var refactorList = XmlHelper.AddElement(document.DocumentElement, "refactorizations");
                foreach (var item in modelRoot.Refactorizations)
                {
                    var n = XmlHelper.AddElement((XmlElement)refactorList, "refactor");
                    item.ToXML((XmlElement)n);
                }
                document.Save(modelFileName);
            }
        }
        public override void SaveModelAndDiagram(Microsoft.VisualStudio.Modeling.SerializationResult serializationResult, nHydrateModel modelRoot, string modelFileName, nHydrateDiagram diagram, string diagramFileName, Encoding encoding, bool writeOptionalPropertiesWithDefaultValue)
        {
            var mainInfo = new FileInfo(modelFileName);
            modelRoot.ModelFileName = modelFileName;
            var modelName = mainInfo.Name.Replace(".nhydrate", ".model");

            if (modelRoot.ModelToDisk)
            {
                nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, mainInfo.DirectoryName, modelName, diagram);
            }
            else
            {
                try
                {
                    var f = nHydrate.Dsl.Custom.SQLFileManagement.GetModelFolder(mainInfo.DirectoryName, modelName);
                    if (Directory.Exists(f)) Directory.Delete(f, true);
                }
                catch
                {
                }
            }

            base.SaveModelAndDiagram(serializationResult, modelRoot, modelFileName, diagram, diagramFileName, encoding, writeOptionalPropertiesWithDefaultValue);

            //Model File
            if (modelRoot.ModelToDisk)
            {
                var document = new XmlDocument();
                document.Load(modelFileName);

                //Remove entire node for Views, Stored Procedures, and Functions
                for (var ii = document.DocumentElement.ChildNodes.Count - 1; ii >= 0; ii--)
                {
                    var n = document.DocumentElement.ChildNodes[ii];
                    document.DocumentElement.RemoveChild(n);
                }

                document.Save(modelFileName);
            }

            //Diagram File
            //Now gut the diagram file
            var diagramFile = modelFileName + ".diagram";
            if (modelRoot.ModelToDisk)
            {
                if (File.Exists(diagramFile))
                {
                    var document = new XmlDocument();
                    document.Load(diagramFile);

                    //Remove all child nodes
                    var n = document.DocumentElement.SelectSingleNode("nestedChildShapes");
                    if (n != null)
                    {
                        document.DocumentElement.RemoveChild(n);
                        document.Save(diagramFile);
                    }

                    ////Reset position attributes
                    //var nlist = document.DocumentElement.SelectNodes("//entityShape");
                    //foreach (XmlElement node in nlist)
                    //{
                    //  //XmlHelper.RemoveAttribute(node, "absoluteBounds");
                    //  XmlHelper.AddAttribute(node, "absoluteBounds", "0, 0, 0, 0");
                    //  var clist = node.SelectNodes("nestedChildShapes/elementListCompartment");
                    //  foreach (XmlElement node2 in clist)
                    //  {
                    //    //XmlHelper.RemoveAttribute(node2, "absoluteBounds");
                    //    XmlHelper.AddAttribute(node2, "absoluteBounds", "0, 0, 0, 0");
                    //  }
                    //}
                    //document.Save(diagramFile);
                }
            }
            else
            {
                //strip out all the colors from the diagram file
                if (File.Exists(diagramFile))
                {
                    var document = new XmlDocument();
                    document.Load(diagramFile);
                    var list = document.DocumentElement.SelectNodes("//elementListCompartment");
                    foreach (XmlNode n in list)
                    {
                        n.Attributes.RemoveNamedItem("fillColor");
                        n.Attributes.RemoveNamedItem("outlineColor");
                        n.Attributes.RemoveNamedItem("textColor");
                        n.Attributes.RemoveNamedItem("titleTextColor");
                        n.Attributes.RemoveNamedItem("itemTextColor");
                    }
                    document.Save(diagramFile);
                }
            }

            //Save the refactorizations
            if (modelRoot.Refactorizations.Count > 0)
            {
                var document = new XmlDocument();
                document.Load(modelFileName);
                var refactorList = XmlHelper.AddElement(document.DocumentElement, "refactorizations");
                foreach (var item in modelRoot.Refactorizations)
                {
                    var n = XmlHelper.AddElement((XmlElement)refactorList, "refactor");
                    item.ToXML((XmlElement)n);
                }
                document.Save(modelFileName);
            }

        }
Beispiel #21
0
        public static void LoadDiagramFiles(nHydrateModel model, string rootFolder, string modelName, nHydrateDiagram diagram)
        {
            if (!model.ModelToDisk)
                return;

            var fileName = Path.Combine(GetModelFolder(rootFolder, modelName), "diagram.xml");
            if (!File.Exists(fileName)) return;
            using (var transaction = model.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
            {
                var document = new XmlDocument();
                var id = Guid.Empty;
                try
                {
                    document.Load(fileName);
                    if (document.DocumentElement == null) throw new Exception("No Root"); //this is thrown away

                    foreach (XmlNode node in document.DocumentElement.ChildNodes)
                    {
                        id = XmlHelper.GetAttributeValue(node, "id", Guid.Empty);
                        var shape = diagram.NestedChildShapes.FirstOrDefault(x => x.ModelElement.Id == id) as Microsoft.VisualStudio.Modeling.Diagrams.NodeShape;
                        if (shape != null)
                            shape.Bounds = Extensions.ConvertRectangleDFromXmlValue(XmlHelper.GetAttributeValue(node, "bounds", string.Empty));
                    }
                }
                catch (Exception ex) { return; }
                transaction.Commit();
            }

        }
Beispiel #22
0
        protected override void OnDocumentLoaded()
        {
            base.OnDocumentLoaded();

            var modelRoot = this.RootElement as global::nHydrate.Dsl.nHydrateModel;

            nHydrate.Dsl.nHydrateDiagram diagram = null;
            if (modelRoot != null)
            {
                diagram = Microsoft.VisualStudio.Modeling.Diagrams.PresentationViewsSubject.GetPresentation(modelRoot).FirstOrDefault() as nHydrate.Dsl.nHydrateDiagram;
                if (diagram != null)
                {
                    diagram.ShapeDoubleClick += new EventHandler <nHydrate.Dsl.ModelElementEventArgs>(diagram_ShapeDoubleClick);
                    diagram.ShapeConfiguring += new EventHandler <nHydrate.Dsl.ModelElementEventArgs>(diagram_ShapeConfiguring);
                }
            }

            if (diagram != null)
            {
                var mainInfo  = new FileInfo(this.FileName);
                var modelName = mainInfo.Name.Replace(".nhydrate", ".model");
                nHydrate.Dsl.Custom.SQLFileManagement.LoadDiagramFiles(modelRoot, mainInfo.DirectoryName, modelName, diagram);
            }

            #region Load the delete tracking file
            var fi        = new FileInfo(this.FileName);
            var cacheFile = Path.Combine(fi.DirectoryName, fi.Name + ".deletetracking");
            if (File.Exists(cacheFile))
            {
                var document = new XmlDocument();
                try
                {
                    document.Load(cacheFile);
                }
                catch (Exception ex)
                {
                    //Do Nothing, there is a file error
                    return;
                }

                //Tables
                foreach (XmlNode node in document.DocumentElement.SelectNodes("tables/table"))
                {
                    modelRoot.RemovedTables.Add(node.InnerText);
                }

                //Views
                foreach (XmlNode node in document.DocumentElement.SelectNodes("views/view"))
                {
                    modelRoot.RemovedViews.Add(node.InnerText);
                }
            }
            #endregion

            modelRoot.IsDirty   = false;
            modelRoot.IsLoading = false;
            this.SetDocDataDirty(0);

            var package = this.ServiceProvider.GetService(typeof(nHydratePackage)) as Microsoft.VisualStudio.Modeling.Shell.ModelingPackage;
            if (package != null)
            {
                this.FindWindow = package.GetToolWindow(typeof(FindWindow), true) as FindWindow;
                this.ModelExplorerToolWindow = package.GetToolWindow(typeof(nHydrateExplorerToolWindow), true) as nHydrateExplorerToolWindow;
            }
        }
        public static void ImportLegacyModel(nHydrateModel model, Store store, nHydrateDiagram diagram, string legacyFileName)
        {
            diagram.IsLoading = true;
            model.IsLoading = true;
            try
            {
                var addedElements = new List<ModelElement>();
                using (var transaction = store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    //The loading assemblies have changed names, so we must manually intervene
                    var newFile = legacyFileName + ".converting";
                    nHydrate.Generator.nHydrateGeneratorProject project = null;
                    try
                    {
                        File.Copy(legacyFileName, newFile);
                        var fileText = File.ReadAllText(newFile);
                        fileText = fileText.Replace("Widgetsphere.Generator.", "nHydrate.Generator.");
                        fileText = fileText.Replace("WidgetsphereGeneratorProject", "nHydrateGeneratorProject");
                        File.WriteAllText(newFile, fileText);
                        System.Threading.Thread.Sleep(500);
                        project = nHydrate.Generator.Common.GeneratorFramework.GeneratorHelper.OpenModel(newFile) as nHydrate.Generator.nHydrateGeneratorProject;
                    }
                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show("An error occurred while importing the legacy modelRoot.", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                    finally
                    {
                        if (File.Exists(newFile))
                            File.Delete(newFile);
                    }

                    try
                    {
                        var oldModel = project.Model as nHydrate.Generator.Models.ModelRoot;

                        model.TransformNames = oldModel.TransformNames;
                        model.CompanyName = oldModel.CompanyName;
                        model.ProjectName = oldModel.ProjectName;
                        model.Copyright = oldModel.Copyright;
                        model.CreatedByColumnName = oldModel.Database.CreatedByColumnName;
                        model.CreatedDateColumnName = oldModel.Database.CreatedDateColumnName;
                        model.DefaultNamespace = oldModel.DefaultNamespace;
                        model.ModifiedByColumnName = oldModel.Database.ModifiedByColumnName;
                        model.ModifiedDateColumnName = oldModel.Database.ModifiedDateColumnName;
                        model.SQLServerType = (DatabaseTypeConstants)Enum.Parse(typeof(DatabaseTypeConstants), oldModel.SQLServerType.ToString());
                        model.StoredProcedurePrefix = oldModel.StoredProcedurePrefix;
                        model.TenantPrefix = oldModel.TenantPrefix;
                        model.AllowMocks = oldModel.AllowMocks;
                        model.TimestampColumnName = oldModel.Database.TimestampColumnName;
                        model.UseUTCTime = oldModel.UseUTCTime;
                        model.Version = oldModel.Version;

                        #region Load Tables
                        foreach (var table in oldModel.Database.Tables.ToList())
                        {
                            var newEntity = new Entity(model.Partition);
                            model.Entities.Add(newEntity);
                            addedElements.Add(newEntity);
                            newEntity.AllowAuditTracking = table.AllowAuditTracking;
                            newEntity.AllowCreateAudit = table.AllowCreateAudit;
                            newEntity.AllowModifyAudit = table.AllowModifiedAudit;
                            newEntity.AllowTimestamp = table.AllowTimestamp;
                            newEntity.CodeFacade = table.CodeFacade;
                            newEntity.Summary = table.Description;
                            newEntity.Immutable = table.Immutable;
                            newEntity.IsAssociative = table.AssociativeTable;
                            newEntity.IsGenerated = table.Generated;
                            newEntity.TypedEntity = (TypedEntityConstants)Enum.Parse(typeof(TypedEntityConstants), table.TypedTable.ToString(), true);
                            newEntity.Name = table.Name;
                            newEntity.Schema = table.DBSchema;
                            //DO NOT IMPORT METADATA

                            #region Load the columns
                            var maxSortOrder = 1;
                            foreach (var column in table.GetColumns())
                            {
                                var newField = new Field(model.Partition);
                                newEntity.Fields.Add(newField);
                                newField.CodeFacade = column.CodeFacade;
                                newField.Collate = column.Collate;
                                newField.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), column.DataType.ToString());
                                newField.Default = column.Default;
                                newField.Summary = column.Description;
                                newField.Formula = column.Formula;
                                newField.FriendlyName = column.FriendlyName;
                                newField.Identity = (IdentityTypeConstants)Enum.Parse(typeof(IdentityTypeConstants), column.Identity.ToString());
                                newField.IsCalculated = column.ComputedColumn;
                                newField.IsGenerated = column.Generated;
                                newField.IsPrimaryKey = column.PrimaryKey;
                                newField.SortOrder = maxSortOrder++;

                                //Do not reset as it creates 2 indexes with PK
                                if (!newField.IsPrimaryKey)
                                    newField.IsIndexed = column.IsIndexed;

                                newField.IsReadOnly = column.IsReadOnly;
                                newField.IsUnique = column.IsUnique;
                                newField.Length = column.Length;
                                newField.Max = column.Max;
                                newField.Min = column.Min;
                                newField.Name = column.Name;
                                newField.Nullable = column.AllowNull;
                                newField.Scale = column.Scale;
                                newField.IsBrowsable = column.IsBrowsable;
                                newField.ValidationExpression = column.ValidationExpression;
                            }
                            #endregion

                            #region Composites
                            foreach (var component in table.ComponentList.ToList())
                            {
                                var newComposite = new Composite(model.Partition);
                                newEntity.Composites.Add(newComposite);
                                addedElements.Add(newComposite);
                                newComposite.CodeFacade = component.CodeFacade;
                                newComposite.Summary = component.Description;
                                newComposite.Name = component.Name;
                                newComposite.IsGenerated = component.Generated;

                                //Add the fields by looking them up in the new table
                                foreach (var column in component.GetColumns())
                                {
                                    var checkColumn = table.GetColumns().FirstOrDefault(x => x.Key == column.Key);
                                    if (checkColumn != null)
                                    {
                                        var tableField = newEntity.Fields.FirstOrDefault(x => x.Name == checkColumn.Name);
                                        if (tableField != null)
                                        {
                                            var newField = new CompositeField(model.Partition);
                                            newComposite.Fields.Add(newField);
                                            newField.FieldId = tableField.Id;
                                        }
                                    }
                                }

                            }
                            #endregion

                            #region Load Static Data
                            var index = 1;
                            foreach (nHydrate.Generator.Models.RowEntry data in table.StaticData)
                            {
                                var isProcessed = false;
                                foreach (nHydrate.Generator.Models.CellEntry cellEntry in data.CellEntries)
                                {
                                    var column = cellEntry.ColumnRef.Object as nHydrate.Generator.Models.Column;
                                    if (column != null)
                                    {
                                        var newColumn = newEntity.Fields.FirstOrDefault(x => x.Name == column.Name);
                                        if (newColumn != null)
                                        {
                                            var newData = new StaticData(model.Partition);
                                            newEntity.StaticDatum.Add(newData);
                                            newData.ColumnKey = newColumn.Id;
                                            newData.Value = cellEntry.Value;
                                            newData.OrderKey = index;
                                            isProcessed = true;
                                        }
                                    }
                                }
                                if (isProcessed)
                                    index++;
                            }
                            #endregion

                        }

                        foreach (var table in oldModel.Database.Tables.ToList())
                        {
                            if (table.ParentTable != null)
                            {
                                var child = model.Entities.FirstOrDefault(x => x.Name == table.Name);
                                var parent = model.Entities.FirstOrDefault(x => x.Name == table.ParentTable.Name);
                                child.ParentInheritedEntity = parent;
                            }
                        }

                        #endregion

                        #region Load Relations
                        foreach (nHydrate.Generator.Models.Table table in oldModel.Database.Tables)
                        {
                            foreach (nHydrate.Generator.Models.Relation relation in table.GetRelations())
                            {
                                var entity1 = model.Entities.First(x => x.Name == relation.ParentTable.Name);
                                var entity2 = model.Entities.First(x => x.Name == relation.ChildTable.Name);
                                if (entity2.ParentInheritedEntity != entity1)
                                {
                                    entity1.ChildEntities.Add(entity2);
                                    var newRelation = entity1.RelationshipList.First(x =>
                                        x.SourceEntity == entity1 &&
                                        x.TargetEntity == entity2 &&
                                        !x.FieldMapList().Any());
                                    newRelation.RoleName = relation.RoleName;

                                    foreach (nHydrate.Generator.Models.ColumnRelationship relationColumn in relation.ColumnRelationships)
                                    {
                                        var column1 = entity1.Fields.First(x => x.Name == relationColumn.ParentColumn.Name);
                                        var column2 = entity2.Fields.First(x => x.Name == relationColumn.ChildColumn.Name);
                                        var newRelationField = new RelationField(model.Partition);
                                        model.RelationFields.Add(newRelationField);
                                        newRelationField.SourceFieldId = column1.Id;
                                        newRelationField.TargetFieldId = column2.Id;
                                        newRelationField.RelationID = newRelation.Id;
                                    }
                                }
                            }
                        }
                        #endregion

                        #region Load Views
                        foreach (nHydrate.Generator.Models.CustomView item in oldModel.Database.CustomViews)
                        {
                            var newitem = new nHydrate.Dsl.View(model.Partition);
                            model.Views.Add(newitem);
                            addedElements.Add(newitem);
                            newitem.CodeFacade = item.CodeFacade;
                            newitem.Summary = item.Description;
                            newitem.IsGenerated = item.Generated;
                            newitem.Name = item.Name;
                            newitem.Schema = item.DBSchema;
                            newitem.SQL = item.SQL;

                            foreach (var column in item.GetColumns())
                            {
                                var newColumn = new ViewField(model.Partition);
                                newitem.Fields.Add(newColumn);
                                newColumn.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), column.DataType.ToString());
                                newColumn.Default = column.Default;
                                newColumn.Summary = column.Description;
                                newColumn.FriendlyName = column.FriendlyName;
                                newColumn.Length = column.Length;
                                newColumn.IsGenerated = column.Generated;
                                //newColumn.Max = column.ma;
                                //newColumn.Min = column.;
                                newColumn.Name = column.Name;
                                newColumn.Nullable = column.AllowNull;
                                newColumn.Scale = column.Scale;
                            }
                        }
                        #endregion

                        #region Load Stored Procedures
                        foreach (nHydrate.Generator.Models.CustomStoredProcedure item in oldModel.Database.CustomStoredProcedures)
                        {
                            var newitem = new StoredProcedure(model.Partition);
                            model.StoredProcedures.Add(newitem);
                            addedElements.Add(newitem);
                            newitem.CodeFacade = item.CodeFacade;
                            newitem.Summary = item.Description;
                            newitem.IsGenerated = item.Generated;
                            newitem.IsExisting = item.IsExisting;
                            newitem.Name = item.Name;
                            newitem.Schema = item.DBSchema;
                            newitem.SQL = item.SQL;
                            newitem.DatabaseObjectName = item.DatabaseObjectName;

                            foreach (var parameter in item.GetParameters())
                            {
                                var newParameter = new StoredProcedureParameter(model.Partition);
                                newitem.Parameters.Add(newParameter);
                                newParameter.Nullable = parameter.AllowNull;
                                newParameter.DataType = (nHydrate.Dsl.DataTypeConstants)Enum.Parse(typeof(nHydrate.Dsl.DataTypeConstants), parameter.DataType.ToString());
                                newParameter.Default = parameter.Default;
                                newParameter.Summary = parameter.Description;
                                newParameter.IsGenerated = parameter.Generated;
                                newParameter.IsOutputParameter = parameter.IsOutputParameter;
                                newParameter.Length = parameter.Length;
                                newParameter.Scale = parameter.Scale;
                                newParameter.Name = parameter.Name;
                            }

                            foreach (var column in item.GetColumns())
                            {
                                var newColumn = new StoredProcedureField(model.Partition);
                                newitem.Fields.Add(newColumn);
                                newColumn.DataType = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), column.DataType.ToString());
                                newColumn.Default = column.Default;
                                newColumn.Summary = column.Description;
                                newColumn.FriendlyName = column.FriendlyName;
                                newColumn.Length = column.Length;
                                //newColumn.Max = column.ma;
                                //newColumn.Min = column.;
                                newColumn.Name = column.Name;
                                newColumn.Nullable = column.AllowNull;
                                newColumn.Scale = column.Scale;
                            }

                        }
                        #endregion

                        nHydrateSerializationHelper.LoadInitialIndexes(model);

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }

                }

                using (var transaction = store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    diagram.AutoLayoutShapeElements(
                        diagram.NestedChildShapes.Where(x => addedElements.Contains(x.ModelElement)).ToList(),
                        Microsoft.VisualStudio.Modeling.Diagrams.GraphObject.VGRoutingStyle.VGRouteTreeNS,
                        Microsoft.VisualStudio.Modeling.Diagrams.GraphObject.PlacementValueStyle.VGPlaceNS,
                        true);
                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                diagram.IsLoading = false;
                model.IsLoading = false;
            }

        }