Example #1
0
        /// <summary>
        /// Add ValidationExtensionRegistrar to the ValidationController and handle related MEF Initialization operations
        /// </summary>
        partial void SetValidationExtensionRegistrar(DslValidation::ValidationController validationController)
        {
            if (validationController != null)
            {
                MEF::ICompositionService compositionService = this.CompositionService;
                if (compositionService != null)
                {
                    validationController.ValidationExtensionRegistrar = new DesignerExtensionEnablement::EFModelValidationExtensionRegistrar();

                    // ValidationExtensionRegistrar is not registered for MEF Recomposition notification. The default ValidationExtensionRegistrar does not handle the MEF Recomposition call.
                    compositionService.SatisfyImportsOnce(MEF::AttributedModelServices.CreatePart(validationController.ValidationExtensionRegistrar));
                }
            }
        }
Example #2
0
 /// <summary>
 /// Add ValidationExtensionRegistrar to the ValidationController and handle related MEF Initialization operations
 /// </summary>
 /// <param name="validationController"></param>
 partial void SetValidationExtensionRegistrar(DslValidation::ValidationController validationController);
			/// <summary>
			/// Unregister the observer on dispose.
			/// </summary>
			private void Dispose(bool disposing)
			{
				global::System.Diagnostics.Debug.Assert(disposing, "SerializationValidationObserver finalized without being disposed!");
				if (disposing && this.validationController != null)
				{
					this.validationController.RemoveObserver(this);
					this.validationController = null;
				}
				this.serializationResult = null;
			}
			/// <summary>
			/// Constructor
			/// </summary>
			internal SerializationValidationObserver(DslModeling::SerializationResult serializationResult, DslValidation::ValidationController validationController)
			{
				#region Check Parameters
				global::System.Diagnostics.Debug.Assert(serializationResult != null);
				global::System.Diagnostics.Debug.Assert(validationController != null);
				#endregion
	
				this.serializationResult = serializationResult;
				this.validationController = validationController;
	
				// Subscribe to validation messages.
				this.validationController.AddObserver(this);
			}
        public virtual ModelRoot LoadModelAndDiagrams(DslModeling::SerializationResult serializationResult, DslModeling::Partition modelPartition, string modelFileName, DslModeling::Partition diagramsPartition, string diagramsFileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
        {
            #region Check Parameters
            if (serializationResult == null)
            {
                throw new global::System.ArgumentNullException("serializationResult");
            }
            if (modelPartition == null)
            {
                throw new global::System.ArgumentNullException("modelPartition");
            }
            if (diagramsPartition == null)
            {
                throw new global::System.ArgumentNullException("diagramsPartition");
            }
            if (string.IsNullOrEmpty(diagramsFileName))
            {
                throw new global::System.ArgumentNullException("diagramsFileName");
            }
            #endregion

            ModelRoot modelRoot;

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

            modelRoot = this.LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator);
            ModelDiagramData data = null;

            if (serializationResult.Failed)
            {
                // don't try to deserialize diagram data if model load failed.
                return(modelRoot);
            }

            if (IsValid(diagramsFileName))
            {
                using (var pkgOutputDoc = global::System.IO.Packaging.Package.Open(diagramsFileName, global::System.IO.FileMode.Open, global::System.IO.FileAccess.Read))
                {
                    foreach (var packagePart in pkgOutputDoc.GetParts())
                    {
                        EFModelDiagram diagram = this.LoadDiagram(serializationResult
                                                                  , modelPartition
                                                                  , modelFileName
                                                                  , diagramsFileName
                                                                  , modelRoot
                                                                  , diagramsPartition
                                                                  , packagePart.GetStream(global::System.IO.FileMode.Open, global::System.IO.FileAccess.Read)
                                                                  , schemaResolver
                                                                  , validationController
                                                                  , serializerLocator) as EFModelDiagram;

                        if (diagram != null)
                        {
                            data = FixupDiagramData(diagram);
                        }

                        if (diagram.Name == Path.GetFileNameWithoutExtension(diagramsFileName).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries).First())
                        {
                            data.SetLocks(Locks.All);
                        }
                    }
                }
            }
            else
            {
                // missing diagram file indicates we should create a new diagram.
                EFModelDiagram diagram = this.LoadDiagram(serializationResult
                                                          , modelPartition
                                                          , modelFileName
                                                          , diagramsFileName
                                                          , modelRoot
                                                          , diagramsPartition
                                                          , global::System.IO.Stream.Null
                                                          , schemaResolver
                                                          , validationController
                                                          , serializerLocator) as EFModelDiagram;
                if (diagram != null)
                {
                    data = FixupDiagramData(diagram);
                }

                if (diagram.Name == Path.GetFileNameWithoutExtension(diagramsFileName))
                {
                    data.SetLocks(Locks.All);
                }
            }

            modelRoot.Store
            .GetAll <ModelDiagramData>()
            .Where(d => d.GetDiagram() == null)
            .ToList()
            .ForEach(d => modelRoot.Diagrams.Remove(d));

            return(modelRoot);

            ModelDiagramData FixupDiagramData(EFModelDiagram diagram)
            {
                ModelDiagramData diagramData = modelRoot.Store
                                               .GetAll <ModelDiagramData>()
                                               .FirstOrDefault(d => d.Name == diagram.Name);

                if (diagramData == null)
                {
                    modelRoot.Diagrams.Add(diagramData = new ModelDiagramData(modelRoot.Store.DefaultPartition
                                                                              , new DslModeling.PropertyAssignment(ModelDiagramData.NameDomainPropertyId, diagram.Name)));
                }

                diagramData.SetDiagram(diagram);
                return(diagramData);
            }
        }
 public virtual ModelRoot LoadModelAndDiagrams(DslModeling::Store store, string modelFileName, string diagramsFileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
 {
     return(this.LoadModelAndDiagrams(new DslModeling::SerializationResult(), store, modelFileName, diagramsFileName, schemaResolver, validationController, serializerLocator));
 }
        public virtual ModelRoot LoadModelAndDiagrams(DslModeling::SerializationResult serializationResult, DslModeling::Store store, string modelFileName, string diagramsFileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
        {
            #region Check Parameters
            if (store == null)
            {
                throw new global::System.ArgumentNullException("store");
            }
            #endregion

            DslModeling::Partition diagramsPartition = new DslModeling::Partition(store);
            return(this.LoadModelAndDiagrams(serializationResult, store.DefaultPartition, modelFileName, diagramsPartition, diagramsFileName, schemaResolver, validationController, serializerLocator));
        }
Example #8
0
        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);

            nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(modelRoot, mainInfo.DirectoryName, modelRoot.Partition.Store, mainInfo.Name);
            modelRoot.IsDirty = false;

            #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

            return(modelRoot);
        }
        // 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 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
                nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(modelRoot, mainInfo.DirectoryName, modelRoot.Partition.Store, modelName);

                #region Watch Folder
                //var modelFolder = nHydrate.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 = nHydrate.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 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);
        }
        /// <summary>
        /// Loads a MetaModel instance into the default partition of the given store.
        /// </summary>
        /// <param name="serializationResult">Stores serialization result from the load operation.</param>
        /// <param name="store">The new MetaModel instance will be created into the default partition of this store.</param>
        /// <param name="fileName">Name of the file from which the MetaModel instance will be deserialized.</param>
        /// <param name="schemaResolver">
        /// An ISchemaResolver that allows the serializer to do schema validation on the root element (and everything inside it).
        /// If null is passed, schema validation will not be performed.
        /// </param>
        /// <param name="validationController">
        /// A ValidationController that will be used to do load-time validation (validations with validation category "Load"). If null
        /// is passed, load-time validation will not be performed.
        /// </param>
        /// <param name="serializerLocator">
        /// An ISerializerLocator that will be used to locate any additional domain model types required to load the model. Can be null.
        /// </param>
        /// <returns>The loaded MetaModel instance.</returns>
        public virtual global::Tum.FamilyTreeDSL.FamilyTreeModel LoadModel(DslModeling::SerializationResult serializationResult, DslModeling::Store store, string fileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
        {
            #region Check Parameters
            if (store == null)
            {
                throw new global::System.ArgumentNullException("store");
            }
            #endregion

            return(this.LoadModelFamilyTreeModel(serializationResult, store.DefaultPartition, fileName, schemaResolver, validationController, serializerLocator));
        }
        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;
        }
 public MetaModel LoadModel(DslModeling::SerializationResult serializationResult, DslModeling::Partition partition, string fileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator, bool bStartT)
 {
     return LoadModel(serializationResult, partition, fileName, schemaResolver, validationController, serializerLocator, true, false);
 }
Example #14
0
        public virtual ModelRoot LoadModelAndDiagrams(DslModeling::SerializationResult serializationResult, DslModeling::Partition modelPartition, string modelFileName, DslModeling::Partition diagramsPartition, string diagramsFileName, DslModeling::ISchemaResolver schemaResolver, DslValidation::ValidationController validationController, DslModeling::ISerializerLocator serializerLocator)
        {
            #region Check Parameters
            if (serializationResult == null)
            {
                throw new global::System.ArgumentNullException("serializationResult");
            }
            if (modelPartition == null)
            {
                throw new global::System.ArgumentNullException("modelPartition");
            }
            if (diagramsPartition == null)
            {
                throw new global::System.ArgumentNullException("diagramsPartition");
            }
            if (string.IsNullOrEmpty(diagramsFileName))
            {
                throw new global::System.ArgumentNullException("diagramsFileName");
            }
            #endregion

            ModelRoot modelRoot;

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

            modelRoot = this.LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator);

            if (serializationResult.Failed)
            {
                // don't try to deserialize diagram data if model load failed.
                return(modelRoot);
            }

            if (IsValid(diagramsFileName))
            {
                using (var pkgOutputDoc = global::System.IO.Packaging.Package.Open(diagramsFileName, global::System.IO.FileMode.Open, global::System.IO.FileAccess.Read))
                {
                    foreach (var packagePart in pkgOutputDoc.GetParts())
                    {
                        this.LoadDiagram(serializationResult, modelPartition, modelFileName, diagramsFileName, modelRoot, diagramsPartition, packagePart.GetStream(global::System.IO.FileMode.Open, global::System.IO.FileAccess.Read), schemaResolver, validationController, serializerLocator);
                    }
                }
            }
            else
            {
                // missing diagram file indicates we should create a new diagram.
                this.LoadDiagram(serializationResult, modelPartition, modelFileName, diagramsFileName, modelRoot, diagramsPartition, global::System.IO.Stream.Null, schemaResolver, validationController, serializerLocator);
            }

            return(modelRoot);
        }