/// <summary> /// Creates a relationship based on the given data. /// </summary> /// <param name="info">Info specifying the relationship to create.</param> /// <param name="shapeToCreate">Type of the relationship shape</param> public override void CreateRelationship(DslEditorViewDiagrams::ViewModelRelationshipCreationInfo info, System.Guid shapeToCreate) { if (shapeToCreate == global::Tum.PDE.ModelingDSL.ReferenceShape.DomainClassId) { using (DslModeling::Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add global::Tum.VModellXT.Dynamik.UebergangShape ")) { CreateRelationship <global::Tum.PDE.ModelingDSL.ReferenceRelationship>(info.Source.ShapeElement.Element, info.Target.ShapeElement.Element); transaction.Commit(); } } if (shapeToCreate == global::Tum.PDE.ModelingDSL.EmbeddingShape.DomainClassId) { using (DslModeling::Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add global::Tum.VModellXT.Dynamik.UebergangShape ")) { System.Collections.ObjectModel.ReadOnlyCollection <global::Tum.PDE.ModelingDSL.EmbeddingRelationship> allInstances = DslModeling::DomainRoleInfo.GetElementLinks <global::Tum.PDE.ModelingDSL.EmbeddingRelationship>(info.Source.Element, global::Tum.PDE.ModelingDSL.EmbeddingRelationship.ChildDomainRoleId); if (allInstances.Count > 0) { allInstances[0].Delete(); } CreateRelationship <global::Tum.PDE.ModelingDSL.EmbeddingRelationship>(info.Source.ShapeElement.Element, info.Target.ShapeElement.Element); transaction.Commit(); } } foreach (DslEditorViewDiagrams::DiagramSurfaceViewModel vm in this.IncludedSurfaceViewModels) { vm.CreateRelationship(info, shapeToCreate); } }
public override void OpenView(global::System.Guid logicalView, object viewContext) { MexModeling::ViewContext modelingViewContext = viewContext as MexModeling::ViewContext; if (modelingViewContext == null) { base.OpenView(logicalView, viewContext); return; } if (string.IsNullOrEmpty(modelingViewContext.DiagramName)) { throw new global::System.ArgumentException("the name of the diagram to open cannot be empty."); } DslDiagrams::Diagram diagram = this.GetDiagram(modelingViewContext); if (diagram == null) { if (modelingViewContext.DiagramType == null) { throw new global::System.ArgumentException("the type of the diagram to open must be specified."); } if (!(modelingViewContext.DiagramType.IsSubclassOf(typeof(DslDiagrams::Diagram)))) { throw new global::System.ArgumentException("the type of the diagram to open must inherit from Microsoft.VisualStudio.Modeling.Diagrams.Diagram class."); } // No diagram associated with specified name, so create and set the name DslModeling::ModelElement rootElement = modelingViewContext.RootElement ?? this.RootElement; using (DslModeling::Transaction t1 = this.Store.TransactionManager.BeginTransaction("DocData:OpenView:CreateDiagram", true)) { diagram = (DslDiagrams::Diagram)global::System.Activator.CreateInstance(modelingViewContext.DiagramType, this.PartitionMapper.PartitionForClass(this.Store.DefaultPartition, DslDiagrams::Diagram.DomainClassId), new DslModeling::PropertyAssignment(DslDiagrams::Diagram.NameDomainPropertyId, modelingViewContext.DiagramName)); // Set the ModelElement associated with the newly created diagram. diagram.ModelElement = rootElement; Store.GetAll <ModelDiagramData>().FirstOrDefault(d => d.Name == diagram.Name)?.SetDiagram((EFModelDiagram)diagram); t1.Commit(); } } EFModelDocView existingView = DocViews.OfType <EFModelDocView>().FirstOrDefault(v => v.Diagram.Name == diagram.Name); if (existingView != null) { existingView.Show(); } else { base.OpenView(logicalView, viewContext); } }
public override void OpenView(global::System.Guid logicalView, object viewContext) { MexModeling::ViewContext modelingViewContext = viewContext as MexModeling::ViewContext; if (modelingViewContext == null) { base.OpenView(logicalView, viewContext); return; } if (string.IsNullOrEmpty(modelingViewContext.DiagramName)) { throw new global::System.ArgumentException("the name of the diagram to open cannot be empty."); } //TODO: don't fetch the default diagram. It's already showing DslDiagrams::Diagram diagram = this.GetDiagram(modelingViewContext); if (diagram == null) { if (modelingViewContext.DiagramType == null) { throw new global::System.ArgumentException("the type of the diagram to open must be specified."); } if (!(modelingViewContext.DiagramType.IsSubclassOf(typeof(DslDiagrams::Diagram)))) { throw new global::System.ArgumentException("the type of the diagram to open must inherit from Microsoft.VisualStudio.Modeling.Diagrams.Diagram class."); } // No diagram associated with specified name, so create and set the name DslModeling::ModelElement rootElement = modelingViewContext.RootElement ?? this.RootElement; using (DslModeling::Transaction t1 = this.Store.TransactionManager.BeginTransaction("DocData:OpenView:CreateDiagram", true)) { diagram = (DslDiagrams::Diagram)global::System.Activator.CreateInstance(modelingViewContext.DiagramType, this.PartitionMapper.PartitionForClass(this.Store.DefaultPartition, DslDiagrams::Diagram.DomainClassId), new DslModeling::PropertyAssignment(DslDiagrams::Diagram.NameDomainPropertyId, modelingViewContext.DiagramName)); // Set the ModelElement associated with the newly created diagram. diagram.ModelElement = rootElement; if (diagram is global::Sawczyn.EFDesigner.EFModel.EFModelDiagram eFModelDiagram) { EFModelSynchronizationHelper.FixUp(eFModelDiagram); //foreach (DslDiagrams::ShapeElement childShape in eFModelDiagram.NestedChildShapes) // childShape.Hide(); } t1.Commit(); } } base.OpenView(logicalView, viewContext); }
/// <summary> /// Creates a relationship based on the given data. /// </summary> /// <param name="info">Info specifying the relationship to create.</param> /// <param name="shapeToCreate">Type of the relationship shape</param> public override void CreateRelationship(DslEditorViewDiagrams::ViewModelRelationshipCreationInfo info, System.Guid shapeToCreate) { if (shapeToCreate == global::Tum.StateMachineDSL.TransitionShape.DomainClassId) { using (DslModeling::Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add global::Tum.VModellXT.Dynamik.UebergangShape ")) { CreateRelationship <global::Tum.StateMachineDSL.Transition>(info.Source.ShapeElement.Element, info.Target.ShapeElement.Element); transaction.Commit(); } } foreach (DslEditorViewDiagrams::DiagramSurfaceViewModel vm in this.IncludedSurfaceViewModels) { vm.CreateRelationship(info, shapeToCreate); } }
/// <summary> /// Loads the model from the given file path and sets it to its appropriate element. /// </summary> /// <param name="filePath">File path to load the model from. Can be null to indicate that there is no referenced domain model.</param> protected override void SetReferencedModel(string filePath) { using (new Tum.PDE.ToolFramework.Modeling.Visualization.ViewModel.UI.WaitCursor()) { global::Tum.VModellXT.Musterbibliothek model = this.Elements[0] as global::Tum.VModellXT.Musterbibliothek; string file = filePath; DslEditorModeling::IParentModelElement parent = model.GetDomainModelServices().ElementParentProvider.GetParentModelElement(model); if (parent == null) { throw new System.ArgumentNullException("Parent of element " + model.ToString() + " can not be null"); } string path = parent.DomainFilePath; string vModellDirectory = new System.IO.FileInfo(path).DirectoryName; //string curPath = Tum.PDE.ToolFramework.Modeling.Visualization.VMXExtensions.Path.PathHelper.EvaluateRelativePath( // vModellDirectory, file); // load model try { if (!System.IO.File.Exists(file)) { System.IO.FileStream s = System.IO.File.Create(file); s.Close(); } using (DslModeling::Transaction transaction = this.Store.TransactionManager.BeginTransaction("Set referenced model")) { global::Tum.VModellXT.VModellXTDocumentData data = this.ViewModelStore.ModelData as global::Tum.VModellXT.VModellXTDocumentData; global::Tum.VModellXT.VModell referenceModel = data.ModelContextVModellXT.LoadInternal(file) as global::Tum.VModellXT.VModell; model.VModell = referenceModel; transaction.Commit(); } } catch (System.Exception ex) { DslEditorViewModelServices::IMessageBoxService messageBox = this.GlobalServiceProvider.Resolve <DslEditorViewModelServices::IMessageBoxService>(); messageBox.ShowError(ex.Message); } this.ModelData.FlushUndoRedoStacks(); } }
/// <summary> /// Loads the domain model from a specified file. /// </summary> /// <param name="fileName">Filename to load the domain model from.</param> /// <param name="isReload"></param> protected override void LoadDocument(string fileName, bool isReload) { this.rootModelElement = null; serializationResult = new DslEditorModeling::SerializationResult(); DslModeling::SerializationResult result = new DslModeling.SerializationResult(); global::Tum.PDE.VSPluginDSL.DomainModel modelRoot = null; // reset post process info VSPluginDSLSerializationPostProcessor.Instance.Reset(); DslModeling::Transaction transaction = this.ModelData.Store.TransactionManager.BeginTransaction("Load model", true); try { modelRoot = global::Tum.PDE.VSPluginDSL.VSPluginDSLSerializationHelper.Instance.LoadModelDomainModel(result, this.ModelData.GetModelPartition(), fileName, null, null, null); // post process if (modelRoot != null && !serializationResult.Failed) { VSPluginDSLSerializationPostProcessor.Instance.DoPostProcess(new System.Collections.Generic.List <string>(), result, modelRoot.Store); } if (!serializationResult.Failed) { // start validation because UseLoad=true ValidateAll(); } // load diagramsModel string diagramsFileName = GetDiagramsFileName(fileName); if (System.IO.File.Exists(diagramsFileName)) { diagramsModel = VSPluginDSLDiagramsDSLSerializationHelper.Instance.LoadModel(result, this.ModelData.GetModelPartition(), GetDiagramsFileName(fileName), null, null, null); } if (diagramsModel == null) { diagramsModel = new DslEditorDiagrams::DiagramsModel(this.ModelData.Store); } if (!diagramsModel.ContainsDiagram("DesignerDiagram")) { DesignerDiagram diagramDesignerDiagram = new DesignerDiagram(this.ModelData.Store); diagramDesignerDiagram.Name = "DesignerDiagram"; diagramsModel.Diagrams.Add(diagramDesignerDiagram); } diagramsModel.GetDiagram("DesignerDiagram").Initialize(); OnPropertyChanged("DesignerDiagram"); if (!diagramsModel.ContainsDiagram("SpecificElementsDiagramTemplate")) { SpecificElementsDiagramTemplate diagramSpecificElementsDiagramTemplate = new SpecificElementsDiagramTemplate(this.ModelData.Store); diagramSpecificElementsDiagramTemplate.Name = "SpecificElementsDiagramTemplate"; diagramsModel.Diagrams.Add(diagramSpecificElementsDiagramTemplate); } diagramsModel.GetDiagram("SpecificElementsDiagramTemplate").Initialize(); OnPropertyChanged("SpecificElementsDiagramTemplate"); if (result.Failed) { transaction.Rollback(); } else { transaction.Commit(); } } catch (System.Exception ex) { serializationResult.AddMessage(new DslEditorModeling::SerializationMessage( VSPluginDSLValidationMessageIds.SerializationLoadErrorId, DslEditorModeling::ModelValidationViolationType.Error, ex.Message, fileName, 0, 0)); transaction.Rollback(); } // copy messages bool bHasMessages = false; foreach (DslModeling::SerializationMessage m in result) { bHasMessages = true; DslEditorModeling.ModelValidationViolationType kind = DslEditorModeling.ModelValidationViolationType.Error; if (m.Kind == DslModeling.SerializationMessageKind.Info) { kind = DslEditorModeling.ModelValidationViolationType.Message; } else if (m.Kind == DslModeling.SerializationMessageKind.Warning) { kind = DslEditorModeling.ModelValidationViolationType.Warning; } DslEditorModeling::SerializationMessage message = new DslEditorModeling.SerializationMessage( VSPluginDSLValidationMessageIds.SerializationMessageId, kind, m.Message, m.Location, m.Line, m.Column); serializationResult.AddMessage(message); } serializationResult.Failed = result.Failed; if (serializationResult.Failed) { // Load failed, can't open the file. serializationResult.AddMessage(new DslEditorModeling::SerializationMessage(VSPluginDSLValidationMessageIds.SerializationLoadErrorId, DslEditorModeling::ModelValidationViolationType.Error, VSPluginDSLDomainModel.SingletonResourceManager.GetString("CannotOpenDocument"), fileName, 0, 0)); } else { this.rootModelElement = modelRoot; } if (!serializationResult.Failed && !bHasMessages) { // start validation because UseOpen=true ValidateAll(); } }
// 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); }
/// <summary> /// Ensures that the user truly wants to remove a reference to a domain model. /// </summary> /// <returns>True to remove; False otherwise.</returns> protected override bool EnsureClosing() { if (!IsReferencedModelSet) { return(true); } global::Tum.VModellXT.Musterbibliothek refModel = this.Elements[0] as global::Tum.VModellXT.Musterbibliothek; // we need to gather references that will be deleted if the referenced model is removed // 1. gather excluded domain models System.Collections.Generic.List <DslModeling::ModelElement> excludedDomainModels = new System.Collections.Generic.List <DslModeling::ModelElement>(); foreach (DslModeling::ModelElement domainModel in this.Store.ElementDirectory.FindElements(global::Tum.VModellXT.Musterbibliothek.DomainClassId)) { if (domainModel == refModel) { continue; } DslModeling::ModelElement parent = domainModel; while (parent != null) { parent = VModellXTElementParentProvider.Instance.GetParentModelElement(parent) as DslModeling::ModelElement; if (parent == refModel) { excludedDomainModels.Add(parent); break; } } } // 2. add elements of those excluded domain models to get existing dependencies on them to // the actual domain models System.Collections.Generic.List <DslModeling::ModelElement> elements = VModellXTElementChildrenProvider.Instance.GetChildren(refModel.VModell, false); // 3. ensure user wants to continue using (DslEditorViewModelDeletion::DeletionViewModel vm = new DslEditorViewModelDeletion::DeletionViewModel(this.ViewModelStore)) { vm.Set(elements, new RetrivalOptions(excludedDomainModels)); vm.Description = "Attention: This deletion can not be undone! \r\n \r\n" + vm.Description; bool?result = this.GlobalServiceProvider.Resolve <DslEditorViewModelServices::IUIVisualizerService>().ShowDialog("DeleteElementsPopup", vm); if (!result == true) { return(false); } } System.GC.Collect(); // 4. delete referenced model and flush undo/redo stacks using (new Tum.PDE.ToolFramework.Modeling.Visualization.ViewModel.UI.WaitCursor()) { using (DslModeling::Transaction transaction = this.Store.TransactionManager.BeginTransaction("Delete referenced model")) { refModel.VModell.Delete(); transaction.Commit(); } } this.ModelData.FlushUndoRedoStacks(); return(true); }
/// <summary> /// Loads the diagram. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TDiagram">The type of the diagram.</typeparam> /// <param name="serializationResult">The serialization result.</param> /// <param name="modelRoot">The model root.</param> /// <param name="diagramFileName">Name of the diagram file.</param> /// <param name="schemaResolver">The schema resolver.</param> /// <param name="diagramDomainId">The diagram domain id.</param> /// <param name="callback">The callback.</param> public void LoadDiagram <TModel, TDiagram>(DslModeling::SerializationResult serializationResult, TModel modelRoot, string diagramFileName, DslModeling::ISchemaResolver schemaResolver, System.Guid diagramDomainId, CreateDiagramHandler callback) where TModel : ModelElement where TDiagram : ComponentModelDiagram { Partition diagramPartition = modelRoot.Store.DefaultPartition; // 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(global::DSLFactory.Candle.SystemModel.CandleDomainModel.SingletonResourceManager.GetString("MissingTransaction")); } ComponentModelDiagram diagram = null; DslModeling::DomainClassXmlSerializer diagramSerializer = this.Directory.GetSerializer(diagramDomainId); global::System.Diagnostics.Debug.Assert(diagramSerializer != null, "Cannot find serializer for SystemModelDiagram"); if (diagramSerializer != null) { if (!global::System.IO.File.Exists(diagramFileName)) { // missing diagram file indicates we should create a new diagram. diagram = callback(diagramPartition); } else { using (global::System.IO.FileStream fileStream = global::System.IO.File.OpenRead(diagramFileName)) { DslModeling::SerializationContext serializationContext = new DslModeling::SerializationContext(this.Directory, fileStream.Name, serializationResult); using (DslModeling::Transaction t = diagramPartition.Store.TransactionManager.BeginTransaction("LoadDiagram", true)) { // 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 (fileStream.Length > 5) { global::System.Xml.XmlReaderSettings settings = new global::System.Xml.XmlReaderSettings(); try { using (global::System.Xml.XmlReader reader = global::System.Xml.XmlReader.Create(fileStream, settings)) { reader.MoveToContent(); diagram = diagramSerializer.TryCreateInstance(serializationContext, reader, diagramPartition) as ComponentModelDiagram; if (diagram != null) { // Note: the actual instance we get back from TryCreateInstance() can be of a derived type of SystemModelDiagram, // so we need to find the correct serializer instance to deserialize the element properly. DslModeling::DomainClassXmlSerializer instanceSerializer = this.Directory.GetSerializer(diagram.GetDomainClass().Id); global::System.Diagnostics.Debug.Assert(instanceSerializer != null, "Cannot find serializer for " + diagram.GetDomainClass().Name + "!"); instanceSerializer.ReadRootElement(serializationContext, 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 = CreateDiagramHelper(diagramPartition, modelRoot); } if (t.IsActive) { t.Commit(); } } // End inner Tx } } if (diagram != null) { diagram.ModelElement = modelRoot; } } }
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; }