public static void LoadInitialIndexes(nHydrateModel modelRoot)
        {
            //Setup primary keys
            foreach (var entity in modelRoot.Entities)
            {
                if (entity.Indexes.Count(x => x.IndexType == IndexTypeConstants.PrimaryKey) == 0 && entity.PrimaryKeyFields.Count > 0)
                {
                    var newIndex = new Index(entity.Partition);
                    newIndex.ParentEntityID = entity.Id;
                    newIndex.IndexType = IndexTypeConstants.PrimaryKey;
                    newIndex.Clustered = true;
                    entity.Indexes.Add(newIndex);

                    foreach (var field in entity.PrimaryKeyFields)
                    {
                        var newColumn = new IndexColumn(field.Partition);
                        newColumn.FieldID = field.Id;
                        newColumn.IsInternal = true;
                        newIndex.IndexColumns.Add(newColumn);
                    }
                }
            }

            var allIndexedField = modelRoot.Entities.SelectMany(x => x.Fields).Where(x => x.IsIndexed && !x.IsPrimaryKey);
            var allIndexes = modelRoot.Entities.SelectMany(x => x.Indexes);
            foreach (var field in allIndexedField)
            {
                var index = allIndexes.FirstOrDefault(x =>
                                                      x.IndexColumns.Count == 1 &&
                                                      x.IndexColumns.First().FieldID == field.Id &&
                                                      x.IndexColumns.First().Ascending);

                if (index == null)
                {
                    var newIndex = new Index(modelRoot.Partition);
                    newIndex.ParentEntityID = field.Entity.Id;
                    newIndex.IndexType = IndexTypeConstants.IsIndexed;
                    field.Entity.Indexes.Add(newIndex);

                    var newColumn = new IndexColumn(modelRoot.Partition);
                    newColumn.FieldID = field.Id;
                    newColumn.IsInternal = true;
                    newIndex.IndexColumns.Add(newColumn);
                }
            }
        }
		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);
		}
		/// <summary>
		/// Helper method to create and initialize a new nHydrateModel.
		/// </summary>
		internal protected virtual nHydrateModel CreateModelHelper(DslModeling::Partition modelPartition)
		{
			nHydrateModel model = new nHydrateModel(modelPartition);
			return model;
		}
		internal global::System.IO.MemoryStream InternalSaveModel(DslModeling::SerializationResult serializationResult, nHydrateModel modelRoot, string fileName, global::System.Text.Encoding encoding, bool writeOptionalPropertiesWithDefaultValue)
		{
			#region Check Parameters
			global::System.Diagnostics.Debug.Assert(serializationResult != null);
			global::System.Diagnostics.Debug.Assert(modelRoot != null);
			global::System.Diagnostics.Debug.Assert(!serializationResult.Failed);
			#endregion
	
			serializationResult.Encoding = encoding;
	
			DslModeling::DomainXmlSerializerDirectory directory = this.GetDirectory(modelRoot.Store);
	
			
			global::System.IO.MemoryStream newFileContent = new global::System.IO.MemoryStream();
			
			DslModeling::SerializationContext serializationContext = new DslModeling::SerializationContext(directory, fileName, serializationResult);
			this.InitializeSerializationContext(modelRoot.Partition, serializationContext, false);
			// MonikerResolver shouldn't be required in Save operation, so not calling SetupMonikerResolver() here.
			serializationContext.WriteOptionalPropertiesWithDefaultValue = writeOptionalPropertiesWithDefaultValue;
			global::System.Xml.XmlWriterSettings settings = nHydrate2SerializationHelper.Instance.CreateXmlWriterSettings(serializationContext, false, encoding);
			using (global::System.Xml.XmlWriter writer = global::System.Xml.XmlWriter.Create(newFileContent, settings))
			{
				this.WriteRootElement(serializationContext, modelRoot, writer);
			}
				
			return newFileContent;
		}
		/// <summary>
		/// Saves the given model root 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="fileName">Name of the file in which the nHydrateModel instance will be saved.</param>
		public virtual void SaveModel(DslModeling::SerializationResult serializationResult, nHydrateModel modelRoot, string fileName)
		{
			this.SaveModel(serializationResult, modelRoot, fileName, global::System.Text.Encoding.UTF8, false);
		}
 /// <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)
 {
 }
 /// <summary>
 /// Customize Model Loading.
 /// </summary>
 /// <param name="serializationResult">Stores serialization result from the load operation.</param>
 /// <param name="partition">Partition in which the new nHydrateModel instance will be created.</param>
 /// <param name="fileName">Name of the file from which the nHydrateModel instance will be deserialized.</param>
 /// <param name="modelRoot">The root of the file that was loaded.</param>
 private void OnPostLoadModel(DslModeling::SerializationResult serializationResult, DslModeling::Partition partition, string fileName, nHydrateModel modelRoot)
 {
     //this.LoadModelAndDiagram
 }
        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)
            {
                nHydrate2.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, mainInfo.DirectoryName, modelName, diagram);
            }
            else
            {
                try
                {
                    var f = nHydrate2.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 nHydrateModel LoadModelAndDiagram(DslModeling::SerializationResult serializationResult, DslModeling::Partition modelPartition, string modelFileName, DslModeling::Partition diagramPartition, string diagramFileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
        {
            var modelRoot = base.LoadModelAndDiagram(serializationResult, modelPartition, modelFileName, diagramPartition, diagramFileName, schemaResolver, validationController, serializerLocator);
            _model = modelRoot;

            //Verify that we can open the model
            var thisAssem = System.Reflection.Assembly.GetExecutingAssembly();
            var thisAssemName = thisAssem.GetName();
            var toolVersion = thisAssemName.Version;
            var modelVersion = new Version(0, 0);
            var dslVersion = new Version(0, 0);

            if (!string.IsNullOrEmpty(modelRoot.ModelVersion))
                modelVersion = new Version(modelRoot.ModelVersion);

            if (toolVersion < modelVersion)
                throw new Exception("This model was created with newer version of the modeler. Please install version '" + modelVersion.ToString() + "' or higher.");

            try
            {
                var document = new XmlDocument();
                document.LoadXml(File.ReadAllText(modelFileName));
                var attr = document.DocumentElement.Attributes["dslVersion"];
                if (attr != null)
                {
                    dslVersion = new Version(attr.Value);
                }
            }
            catch { }

            //When saved the new version will be this tool version
            modelRoot.ModelVersion = LAST_MODEL_MODEL_COMPATIBLE;
            modelRoot.ModelFileName = modelFileName;

            modelRoot.IsDirty = false;

            var mainInfo = new FileInfo(modelFileName);
            var modelName = mainInfo.Name.Replace(".nhydrate", ".model");

            if (modelRoot.ModelToDisk)
            {
                //Load from disk store
                nHydrate2.Dsl.Custom.SQLFileManagement.LoadFromDisk(modelRoot, mainInfo.DirectoryName, modelRoot.Partition.Store, modelName);

                #region Watch Folder
                //var modelFolder = nHydrate2.Dsl.Custom.SQLFileManagement.GetModelFolder(mainInfo.DirectoryName, modelName);
                //_watchFolder.Path = modelFolder;
                //_watchFolder.IncludeSubdirectories = true;
                //_watchFolder.NotifyFilter = System.IO.NotifyFilters.FileName |
                //	NotifyFilters.LastWrite |
                //	NotifyFilters.Size |
                //	NotifyFilters.CreationTime |
                //	NotifyFilters.DirectoryName;

                //_watchFolder.Changed += new FileSystemEventHandler(FolderChangedEvent);
                //_watchFolder.Created += new FileSystemEventHandler(FolderChangedEvent);
                //_watchFolder.Deleted += new FileSystemEventHandler(FolderChangedEvent);
                //_watchFolder.Renamed += new System.IO.RenamedEventHandler(FolderFileRenamedEvent);

                //try
                //{
                //	_watchFolder.EnableRaisingEvents = true;
                //}
                //catch (ArgumentException)
                //{
                //	//Do Nothing
                //}
                #endregion

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

            modelRoot.IsDirty = false;

            //SyncServer
            //var syncServerFile = modelFileName + ".syncserver";
            //modelRoot.SyncServerURL = nHydrate.SyncServer.Client.SyncDomain.LoadSyncServerConfig(syncServerFile);

            //Alphabetized columns if need be
            //foreach (var entity in modelRoot.Entities)
            //{
            //  entity.Fields.Sort((x, y) => x.Name.CompareTo(y.Name));
            //}

            #region Load Indexes

            //For now load the indexes into the REAL indexes collection
            //This should only happens the first time
            using (var transaction = modelRoot.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
            {
                LoadInitialIndexes(modelRoot);
                transaction.Commit();
            }

            #endregion

            #region Handle the Precedence

            if (modelRoot.StoredProcedures.Count > 0)
                modelRoot.MaxPrecedenceOrder = Math.Max(modelRoot.StoredProcedures.Max(x => x.PrecedenceOrder), modelRoot.MaxPrecedenceOrder);
            if (modelRoot.Views.Count > 0)
                modelRoot.MaxPrecedenceOrder = Math.Max(modelRoot.Views.Max(x => x.PrecedenceOrder), modelRoot.MaxPrecedenceOrder);
            if (modelRoot.Functions.Count > 0)
                modelRoot.MaxPrecedenceOrder = Math.Max(modelRoot.Functions.Max(x => x.PrecedenceOrder), modelRoot.MaxPrecedenceOrder);

            modelRoot.StoredProcedures.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++modelRoot.MaxPrecedenceOrder);
            modelRoot.Views.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++modelRoot.MaxPrecedenceOrder);
            modelRoot.Functions.Where(x => x.PrecedenceOrder == 0).ToList().ForEach(x => x.PrecedenceOrder = ++modelRoot.MaxPrecedenceOrder);

            #endregion

            #region Load the refactorizations

            if (File.Exists(modelFileName))
            {
                var fi = new FileInfo(modelFileName);
                if (fi.Length > 5)
                {
                    var document = new XmlDocument();
                    document.Load(modelFileName);
                    if (document.DocumentElement != null)
                    {
                        var refactorList = document.DocumentElement.SelectSingleNode("refactorizations");
                        if (refactorList != null)
                        {
                            foreach (XmlNode n in refactorList.ChildNodes)
                            {
                                //if (XmlHelper.GetAttributeValue(n, "type", string.Empty) == "guidtoid")
                                //{
                                //  modelRoot.Refactorizations.Add(new RefactorChangeGuidToID((XmlElement)n));
                                //}
                                //else if (XmlHelper.GetAttributeValue(n, "type", string.Empty) == "guidtoididtoguid")
                                //{
                                //  modelRoot.Refactorizations.Add(new RefactorChangeIDToGuid((XmlElement)n));
                                //}
                                if (XmlHelper.GetAttributeValue(n, "type", string.Empty) == "splittable")
                                {
                                    modelRoot.Refactorizations.Add(new RefactorTableSplit((XmlElement)n));
                                }
                                else if (XmlHelper.GetAttributeValue(n, "type", string.Empty) == "combinetable")
                                {
                                    modelRoot.Refactorizations.Add(new RefactorTableCombine((XmlElement)n));
                                }
                            }
                        }
                    }
                }
            }

            #endregion

            #if MYSQL
            //Do Nothing
            #else
            modelRoot.SupportedPlatforms = DatabasePlatformConstants.SQLServer;
            #endif

            //If using modules from a previous model version then perform this one time action of
            //assigning the indexes to all modules  so user will not be confronted with a a huge action to perform after upgrade
            if (dslVersion <= new Version(5, 1, 2, 118) && modelRoot.UseModules)
            {
                using (var transaction = modelRoot.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
                {
                    foreach (var module in modelRoot.Modules)
                    {
                        var contained = module.GetEntities().ToList();
                        foreach (var index in modelRoot.Entities.Where(x => contained.Contains(x)).SelectMany(x => x.IndexList))
                        {
                            _model.IndexModules.Add(new IndexModule(_model.Partition) { IndexID = index.Id, ModuleId = module.Id });
                        }
                    }
                    transaction.Commit();
                }
            }

            return modelRoot;
        }