// private void OnPostLoadModelAndDiagram(DslModeling::SerializationResult serializationResult, DslModeling::Partition modelPartition, string modelFileName, DslModeling::Partition diagramPartition, string diagramFileName, ModelRoot modelRoot, EFModelDiagram diagram)
        // private DslDiagrams::Diagram LoadDiagram(DslModeling::SerializationResult serializationResult, DslModeling::ModelElement modelRoot, DslModeling::Partition diagramPartition, global::System.IO.Stream diagramStream, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
        private DslDiagrams::Diagram LoadDiagram(DslModeling::SerializationResult serializationResult, DslModeling::Partition modelPartition, string modelFileName, string diagramFileName, DslModeling::ModelElement modelRoot, DslModeling::Partition diagramPartition, global::System.IO.Stream diagramStream, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
        {
            #region Check Parameters
            if (serializationResult == null)
            {
                throw new global::System.ArgumentNullException("serializationResult");
            }
            if (modelRoot == null)
            {
                throw new global::System.ArgumentNullException("modelRoot");
            }
            if (diagramPartition == null)
            {
                throw new global::System.ArgumentNullException("diagramPartition");
            }
            #endregion

            DslDiagrams::Diagram diagram = null;
            var diagramName = string.Empty;

            // Ensure there is an outer transaction spanning both model and diagram load, so moniker resolution works properly.
            if (!diagramPartition.Store.TransactionActive)
            {
                throw new global::System.InvalidOperationException(EFModelDomainModel.SingletonResourceManager.GetString("MissingTransaction"));
            }

            if (diagramStream == null || diagramStream == global::System.IO.Stream.Null || !diagramStream.CanRead || diagramStream.Length < 6)
            {
                // missing diagram file indicates we should create a new diagram.
                diagram = this.CreateDiagramHelper(diagramPartition, modelRoot);
            }
            else
            {
                var directory     = this.GetDirectory(diagramPartition.Store);
                var localName     = string.Empty;
                var localSettings = EFModelSerializationHelper.Instance.CreateXmlReaderSettings(null, false);
                try
                {
                    using (var reader = global::System.Xml.XmlReader.Create(diagramStream, localSettings))
                    {
                        reader.MoveToContent();
                        localName = reader.LocalName;
                        global::System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(reader.GetAttribute("name")), "One of diagram streams is not well-formed");
                        diagramName = reader.GetAttribute("name");
                    }
                    diagramStream.Seek(0, global::System.IO.SeekOrigin.Begin);
                }
                catch (global::System.Xml.XmlException xEx)
                {
                    DslModeling::SerializationUtilities.AddMessage(
                        new DslModeling::SerializationContext(directory),
                        DslModeling::SerializationMessageKind.Error,
                        xEx
                        );
                }

                var diagramSerializer = directory.GetSerializer(EFModelDiagram.DomainClassId) ?? this.GetSerializer(diagramPartition.Store, localName);
                global::System.Diagnostics.Debug.Assert(diagramSerializer != null, "Cannot find serializer for " + diagramName);

                if (diagramSerializer != null)
                {
                    DslModeling::SerializationContext serializationContext = new DslModeling::SerializationContext(directory, diagramName, serializationResult);
                    this.InitializeSerializationContext(diagramPartition, serializationContext, true);
                    DslModeling::TransactionContext transactionContext = new DslModeling::TransactionContext();
                    transactionContext.Add(DslModeling::SerializationContext.TransactionContextKey, serializationContext);


                    using (DslModeling::Transaction postT = diagramPartition.Store.TransactionManager.BeginTransaction("PostLoad Model and Diagram", true, transactionContext))
                    {
                        using (DslModeling::Transaction t = diagramPartition.Store.TransactionManager.BeginTransaction("LoadDiagram", true, transactionContext))
                        {
                            // Ensure there is some content in the file. Blank (or almost blank, to account for encoding header bytes, etc.)
                            // files will cause a new diagram to be created and returned
                            if (diagramStream.Length > 5)
                            {
                                global::System.Xml.XmlReaderSettings settings = EFModelSerializationHelper.Instance.CreateXmlReaderSettings(serializationContext, false);
                                try
                                {
                                    using (global::System.Xml.XmlReader reader = global::System.Xml.XmlReader.Create(diagramStream, settings))
                                    {
                                        reader.MoveToContent();
                                        diagram = diagramSerializer.TryCreateInstance(serializationContext, reader, diagramPartition) as DslDiagrams::Diagram;
                                        if (diagram != null)
                                        {
                                            this.ReadRootElement(serializationContext, diagramSerializer, diagram, reader, schemaResolver);
                                        }
                                    }
                                }
                                catch (global::System.Xml.XmlException xEx)
                                {
                                    DslModeling::SerializationUtilities.AddMessage(
                                        serializationContext,
                                        DslModeling::SerializationMessageKind.Error,
                                        xEx
                                        );
                                }
                                if (serializationResult.Failed)
                                {
                                    // Serialization error encountered, rollback the transaction.
                                    diagram = null;
                                    t.Rollback();
                                }
                            }

                            if (diagram == null && !serializationResult.Failed)
                            {
                                // Create diagram if it doesn't exist
                                diagram = this.CreateDiagramHelper(diagramPartition, modelRoot);
                            }

                            if (t.IsActive)
                            {
                                t.Commit();
                            }
                        }     // End inner Tx


                        // Fire PostLoad customization code whether Load succeeded or not
                        // Provide a method in a partial class with the following signature:

                        ///// <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, ModelRoot modelRoot, EFModelDiagram diagram)

                        this.OnPostLoadModelAndDiagram(serializationResult, modelPartition, modelFileName, diagramPartition, diagramFileName, (ModelRoot)modelRoot, (EFModelDiagram)diagram);
                        if (serializationResult.Failed)
                        {       // Serialization error encountered, rollback the middle transaction.
                            modelRoot = null;
                            postT.Rollback();
                        }
                        if (postT.IsActive)
                        {
                            postT.Commit();
                        }
                    }    // End MiddleTx
                    // Do load-time validation if a ValidationController is provided.
                    if (!serializationResult.Failed && validationController != null)
                    {
                        using (new SerializationValidationObserver(serializationResult, validationController))
                        {
                            validationController.Validate(diagramPartition, DslValidation::ValidationCategories.Load);
                        }
                    }
                }
            }

            if (diagram != null)
            {
                if (!serializationResult.Failed)
                {       // Succeeded.
                    diagram.ModelElement = diagram.ModelElement ?? modelRoot;
                    diagram.PostDeserialization(true);
                    this.CheckForOrphanedShapes(diagram, serializationResult);
                }
                else
                {       // Failed.
                    diagram.PostDeserialization(false);
                }
            }

            return(diagram);
        }
        public MetaModel LoadModel(DslModeling::SerializationResult serializationResult, DslModeling::Partition partition, string fileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator, bool bStartT, bool bIsTopMost)
        {
            #region Model
            #region Check Parameters
            if (serializationResult == null)
                throw new global::System.ArgumentNullException("serializationResult");
            if (partition == null)
                throw new global::System.ArgumentNullException("partition");
            if (string.IsNullOrEmpty(fileName))
                throw new global::System.ArgumentNullException("fileName");
            #endregion

            // Ensure there is a transaction for this model to Load in.
            if (!partition.Store.TransactionActive)
            {
                throw new global::System.InvalidOperationException(LanguageDSLDomainModel.SingletonResourceManager.GetString("MissingTransaction"));
            }

            MetaModel modelRoot = null;
            DslModeling::DomainXmlSerializerDirectory directory = this.GetDirectory(partition.Store);
            DslModeling::DomainClassXmlSerializer modelRootSerializer = directory.GetSerializer(MetaModel.DomainClassId);
            global::System.Diagnostics.Debug.Assert(modelRootSerializer != null, "Cannot find serializer for MetaModel!");
            if (modelRootSerializer != null)
            {
                using (global::System.IO.FileStream fileStream = global::System.IO.File.OpenRead(fileName))
                {
                    DslModeling::SerializationContext serializationContext = new DslModeling::SerializationContext(directory, fileStream.Name, serializationResult);
                    this.InitializeSerializationContext(partition, serializationContext, true);
                    DslModeling::TransactionContext transactionContext = new DslModeling::TransactionContext();
                    transactionContext.Add(DslModeling::SerializationContext.TransactionContextKey, serializationContext);

                    DslModeling::Transaction t = null;
                    if (bStartT)
                    {
                        t = partition.Store.TransactionManager.BeginTransaction("Load Model from " + fileName, true, transactionContext);
                    }

                    // Ensure there is some content in the file.  Blank (or almost blank, to account for encoding header bytes, etc.)
                    // files will cause a new root element to be created and returned. 
                    if (fileStream.Length > 5)
                    {
                        try
                        {
                            global::System.Xml.XmlReaderSettings settings = LanguageDSLSerializationHelper.Instance.CreateXmlReaderSettings(serializationContext, false);
                            using (global::System.Xml.XmlReader reader = global::System.Xml.XmlReader.Create(fileStream, settings))
                            {
                                // Attempt to read the encoding.
                                reader.Read(); // Move to the first node - will be the XmlDeclaration if there is one.
                                global::System.Text.Encoding encoding;
                                if (this.TryGetEncoding(reader, out encoding))
                                {
                                    serializationResult.Encoding = encoding;
                                }

                                // Load any additional domain models that are required
                                DslModeling::SerializationUtilities.ResolveDomainModels(reader, serializerLocator, partition.Store);

                                reader.MoveToContent();


                                modelRoot = modelRootSerializer.TryCreateInstance(serializationContext, reader, partition) as MetaModel;
                                if (modelRoot != null && !serializationResult.Failed)
                                {
                                    modelRoot.BaseDirectory = MetaModelLibraryBase.GetBaseDirectory(fileName);
                                    modelRoot.FilePath = fileName;
                                    this.ReadRootElement(serializationContext, modelRoot, reader, schemaResolver);
                                }
                            }

                        }
                        catch (global::System.Xml.XmlException xEx)
                        {
                            DslModeling::SerializationUtilities.AddMessage(
                                serializationContext,
                                DslModeling::SerializationMessageKind.Error,
                                xEx
                            );
                        }
                    }

                    if (modelRoot == null && !serializationResult.Failed)
                    {
                        // create model root if it doesn't exist.
                        modelRoot = this.CreateModelHelper(partition);
                        modelRoot.BaseDirectory = MetaModelLibraryBase.GetBaseDirectory(fileName);
                        modelRoot.FilePath = fileName;
                    }
                    if (bStartT)
                        if (t.IsActive)
                            t.Commit();

                    // Do load-time validation if a ValidationController is provided.
                    if (!serializationResult.Failed && validationController != null)
                    {
                        using (new SerializationValidationObserver(serializationResult, validationController))
                        {
                            validationController.Validate(partition, DslValidation::ValidationCategories.Load);
                        }
                    }
                }
            }

            #endregion

            MetaModel model = modelRoot;
            if (bIsTopMost)
                model.IsTopMost = true;

            #region Diagrams

            System.IO.FileInfo info = new System.IO.FileInfo(fileName);
            string fileNameDiagram = info.DirectoryName + "\\" + info.Name.Remove(info.Name.Length - info.Extension.Length, info.Extension.Length) + DiagramExtension;

            View view = null;
            if (System.IO.File.Exists(fileNameDiagram))
            {
                //DslModeling::DomainXmlSerializerDirectory directory = this.GetDirectory(partition.Store);
                DslModeling::DomainClassXmlSerializer viewSerializer = directory.GetSerializer(View.DomainClassId);
                global::System.Diagnostics.Debug.Assert(viewSerializer != null, "Cannot find serializer for View!");
                if (viewSerializer != null)
                {
                    using (global::System.IO.FileStream fileStream = global::System.IO.File.OpenRead(fileNameDiagram))
                    {
                        DslModeling::SerializationContext serializationContext = new DslModeling::SerializationContext(directory, fileStream.Name, serializationResult);
                        this.InitializeSerializationContext(partition, serializationContext, true);
                        DslModeling::TransactionContext transactionContext = new DslModeling::TransactionContext();
                        transactionContext.Add(DslModeling::SerializationContext.TransactionContextKey, serializationContext);

                        DslModeling::Transaction t = null;
                        if (bStartT)
                            t = partition.Store.TransactionManager.BeginTransaction("Load Model from " + fileNameDiagram, true, transactionContext);

                        // Ensure there is some content in the file.  Blank (or almost blank, to account for encoding header bytes, etc.)
                        // files will cause a new root element to be created and returned. 
                        if (fileStream.Length > 5)
                        {
                            try
                            {
                                global::System.Xml.XmlReaderSettings settings = LanguageDSLSerializationHelper.Instance.CreateXmlReaderSettings(serializationContext, false);
                                using (global::System.Xml.XmlReader reader = global::System.Xml.XmlReader.Create(fileStream, settings))
                                {
                                    // Attempt to read the encoding.
                                    reader.Read(); // Move to the first node - will be the XmlDeclaration if there is one.
                                    global::System.Text.Encoding encoding;
                                    if (this.TryGetEncoding(reader, out encoding))
                                    {
                                        serializationResult.Encoding = encoding;
                                    }
                                    reader.MoveToContent();

                                    view = viewSerializer.TryCreateInstance(serializationContext, reader, partition) as View;
                                    if (view != null && !serializationResult.Failed)
                                    {
                                        // Use a validating reader if possible
                                        viewSerializer.Read(serializationContext, view, reader);

                                        model.View = view;
                                    }
                                }
                            }

                            catch (global::System.Xml.XmlException xEx)
                            {
                                DslModeling::SerializationUtilities.AddMessage(
                                    serializationContext,
                                    DslModeling::SerializationMessageKind.Error,
                                    xEx
                                );
                            }
                        }

                        if (bStartT)
                            if (t.IsActive)
                                t.Commit();

                    }
                }
            }
            #endregion

            //if( bIsTopMost )
            SerializationPostProcessor.PostProcessModelLoad(model);

            return model;
        }