public static void CreateNewProcessOverview(string ProcessName, ProjectItem processFile, ProjectItem diagramFile) { var store = new Store(typeof(CloudCoreArchitectProcessOverviewDomainModel)); var partition = new Partition(store); var result = new SerializationResult(); using (Transaction t = store.TransactionManager.BeginTransaction("create new process overview model")) { try { var processOverviewSerializationHelper = CloudCoreArchitectProcessOverviewSerializationHelper.Instance; Architect.ProcessOverview.Process process = processOverviewSerializationHelper.CreateModelHelper(partition); SetProcessOverviewProperties(ProcessName, process); var diagram = processOverviewSerializationHelper.CreateDiagramHelper(partition, process); processOverviewSerializationHelper.SaveModelAndDiagram(result, process, processFile.FileNames[0], diagram, diagramFile.FileNames[0]); AddAssemblyReference(ProcessName, process); t.Commit(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public override void OnPostSerialization(SerializationResult result) { var localPlayer = VRC.SDKBase.Networking.LocalPlayer; if (!(localPlayer.IsOwner(gameObject) && Utilities.IsValid(targetBehaviour) && Utilities.IsValid(localPlayer))) { Debug.LogWarning($"SyncedInteger.OnPostSerialization: aborting", this); return; } if (!result.success) { Debug.LogWarning($"SyncedInteger.OnPostSerialization: Serialization failed, trying again", this); RequestSerialization(); return; } Debug.Log($"SyncedInteger.OnPostSerialization: Serialized {result.byteCount} bytes"); if (!string.IsNullOrEmpty(targetSerializedEvent)) { targetBehaviour.SendCustomEvent(targetSerializedEvent); } }
protected override void OnUnresolvedMoniker(SerializationResult serializationResult, Moniker moniker) { /* * if (moniker.Link is SerializationClassReferencesChildren || * moniker.Link is SerializationClassReferencesAttributes || * moniker.Link is DomainClassReferencesBaseClass || * moniker.Link is DomainRelationshipReferencesBaseRelationship || * moniker.Link is TreeNodeReferencesInheritanceNodes || * moniker.Link is TreeNodeReferencesEmbeddingRSNodes || * moniker.Link is TreeNodeReferencesReferenceRSNodes || * moniker.Link is TreeNodeReferencesShapeClassNodes) * {*/ if (moniker.Link != null) { // TODO string name = moniker.Link.ToString() + " - " + moniker.MonikerName; moniker.DeleteLink(); SerializationUtilities.AddMessage(serializationResult, moniker.Location, SerializationMessageKind.Warning, "Moniker could not be resolved; The link was deleted from the model. " + name, moniker.Line, moniker.Column); } else { base.OnUnresolvedMoniker(serializationResult, moniker); } }
public SerializationResult <ObjectType> Read(string filePath) { if (filePath == null) { throw new ArgumentNullException("filePath"); } SerializationResult <ObjectType> serializationResult; _ClearResults(); try { ObjectType value = _Read(filePath); if (value != default(ObjectType)) { serializationResult = new SerializationResult <ObjectType>(true, "File read successful.", value, _results); } else { serializationResult = new SerializationResult <ObjectType>(false, "File does not exist.", null, _results); } } catch (Exception ex) { VixenSystem.Logging.Debug(ex); serializationResult = new SerializationResult <ObjectType>(false, ex.Message, null, _results); } return(serializationResult); }
internal override void SaveDiagram( SerializationResult serializationResult, EntityDesignerDiagram diagram, string diagramFileName, Encoding encoding, bool writeOptionalPropertiesWithDefaultValue) { // don't save the .diagram file return; }
public SerializationResult <ObjectType> Write(ObjectType value, string filePath) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (value == null) { throw new ArgumentNullException("value"); } SerializationResult <ObjectType> serializationResult; _ClearResults(); try { _Write(value, filePath); serializationResult = new SerializationResult <ObjectType>(true, "File write successful.", value, _results); } catch (Exception ex) { VixenSystem.Logging.Debug(ex); serializationResult = new SerializationResult <ObjectType>(false, ex.Message, null, _results); } return(serializationResult); }
public override void OnPostSerialization(SerializationResult result) { if (!result.success) { pen.DestroyJustBeforeInk(); } }
protected override void OnUnresolvedMoniker(SerializationResult serializationResult, Moniker moniker) { /* if (moniker.Link is SerializationClassReferencesChildren || moniker.Link is SerializationClassReferencesAttributes || moniker.Link is DomainClassReferencesBaseClass || moniker.Link is DomainRelationshipReferencesBaseRelationship || moniker.Link is TreeNodeReferencesInheritanceNodes || moniker.Link is TreeNodeReferencesEmbeddingRSNodes || moniker.Link is TreeNodeReferencesReferenceRSNodes || moniker.Link is TreeNodeReferencesShapeClassNodes) {*/ if( moniker.Link != null ) { // TODO string name = moniker.Link.ToString() + " - " + moniker.MonikerName; moniker.DeleteLink(); SerializationUtilities.AddMessage(serializationResult, moniker.Location, SerializationMessageKind.Warning, "Moniker could not be resolved; The link was deleted from the model. " + name, moniker.Line, moniker.Column); } else base.OnUnresolvedMoniker(serializationResult, moniker); }
public override void OnPostSerialization(SerializationResult result) { //requires "using VRC.Udon.Common;" to use //From what i understand this //runs after all other Serialization event and allows you top check if it was sent successfully. }
public override void OnPostSerialization(SerializationResult result) { if (!result.success) { DebugLog("Failed to sync"); return; } }
private SerializationStatus(SerializationResult result, object obj = null, Type alt = null, SerializationFixup fix = null, ulong[] missing_ids = null) { AltType = alt; Fix = fix; Object = obj; RequiredIDs = missing_ids; Result = result; }
// sending to server private void SendSerializationResultData(string errorMessage) { SerializationResult result = CreateResult(errorMessage); string objectJson = JsonConvert.SerializeObject(result); producer.Send(objectJson); }
private void OnPostLoadModelAndDiagram(SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition, string diagramFileName, ModelRoot modelRoot, EFModelDiagram diagram) { Debug.Assert(modelPartition != null); Debug.Assert(modelPartition.Store != null); // Tracking properties need to be set up according to whether the serialization matches the calculated values. ResetTrackingProperties(modelPartition.Store); }
/// <summary> /// Chargement d'un modèle à partir du repository local (Il doit être présent) /// </summary> /// <param name="fileName">Fichier du modèle</param> /// <param name="enableCache">Indique si on doit utiliser le cache</param> /// <returns></returns> public static ModelLoader GetLoader(string fileName, bool enableCache) { _serializationResult = null; if (String.IsNullOrEmpty(fileName)) { return(null); } if (!File.Exists(fileName)) { //ILogger logger = ServiceLocator.Instance.GetService<ILogger>(); //if( logger != null ) // logger.Write("Model Loader", String.Format("The model {0} doesn't exist", fileName), LogType.Error); return(null); } try { if (!enableCache) { return(new ModelLoader(fileName)); } CacheItem ci; // On cherche dans le cache s_modelsCache.TryGetValue(fileName, out ci); // Le cache n'est plus valide si le modèle a été modifié entre temps DateTime lastUpdateDateTime = File.GetLastWriteTimeUtc(fileName); if (ci == null || ci.lastUpdate < lastUpdateDateTime) { // Rien dans le cache, on crée une nouvelle entrée if (ci == null) { ci = new CacheItem(); } ci.loader = new ModelLoader(fileName); ci.lastUpdate = lastUpdateDateTime; s_modelsCache[fileName] = ci; } return(ci.loader); } catch (Exception ex) { ILogger logger = ServiceLocator.Instance.GetService <ILogger>(); if (logger != null) { logger.WriteError("Load model", String.Format("Error when loading external system {0}", Path.GetFileNameWithoutExtension(fileName)), ex); } return(null); } }
public void Serialization_Result_Test_Test_Failure_Initialization() { var originalObject = "Test"; var SUT = SerializationResult.InitFailedSerialization(originalObject, new Exception(), typeof(string)); Assert.IsTrue(SUT.FailureException != null); Assert.IsTrue(SUT.SerializedValue.Value == string.Empty); Assert.IsTrue(SUT.SerializedValue.Type.Equals(originalObject.GetType())); Assert.IsTrue(SUT.Success == false); }
public static void ShouldBeValid(this SerializationResult result, string message = null) { if (result.Success) { return; } throw new Exception($@"Expected serialization to succeed but failed. {(message ?? string.Empty) + result} "); }
/// <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> protected void OnPostLoadModelAndDiagram(SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition, string diagramFileName, TModel modelRoot, TDiagram diagram) { foreach (SerializationMessage message in serializationResult) { if (message.Kind == SerializationMessageKind.Warning && message.Message.StartsWith(Properties.Resources.MissingIdKey, StringComparison.OrdinalIgnoreCase)) { SerializationUtilities.AddMessage(serializationResult, modelFileName, SerializationMessageKind.Info, Properties.Resources.MissingIdWarnings, 0, 0); return; } } }
public void Serialization_Result_Test_Test_Successful_Initialization() { var originalObject = "Test"; var serializedObject = "Serialized Object"; var SUT = SerializationResult.InitSuccessfulSerialization(originalObject, serializedObject, typeof(string)); Assert.IsTrue(SUT.FailureException == null); Assert.IsTrue(SUT.SerializedValue.Value == serializedObject); Assert.IsTrue(SUT.SerializedValue.Type.Equals(originalObject.GetType())); Assert.IsTrue(SUT.Success == true); }
private ModelElement LoadPartition(Partition partition, string modelFile) { if (string.IsNullOrEmpty(modelFile) || !File.Exists(modelFile)) { base.ModelBus.LogError(ErrorCategory.Error, Microsoft.VisualStudio.TextTemplating.Modeling.ModelBusExceptionMessages.GetInvalidModelFilePath(modelFile)); return(null); } ISerializerLocator serializerLocator = this.CreateSerializerLocator(); if (serializerLocator == null) { base.ModelBus.LogError(ErrorCategory.Error, Microsoft.VisualStudio.TextTemplating.Modeling.ModelBusExceptionMessages.GetErrorLocateSerializer(modelFile)); return(null); } IDomainModelSerializer serializerFromFileName = serializerLocator.GetSerializerFromFileName(modelFile); if (serializerFromFileName == null) { base.ModelBus.LogError(ErrorCategory.Error, Microsoft.VisualStudio.TextTemplating.Modeling.ModelBusExceptionMessages.GetErrorLocateSerializer(modelFile)); return(null); } Type domainModelType = serializerFromFileName.DomainModelType; if (!(from i in partition.DomainDataDirectory.DomainModels select i.ImplementationType).Any <Type>(t => object.Equals(t, domainModelType))) { partition.Store.LoadDomainModels(new Type[] { domainModelType }); } SerializationResult serializationResult = new SerializationResult(); ModelElement element = null; using (Transaction transaction = partition.Store.TransactionManager.BeginTransaction("Load model", true)) { element = serializerFromFileName.LoadModel(serializationResult, partition, modelFile, serializerLocator); if (!serializationResult.Failed) { transaction.Commit(); } } if (!serializationResult.Failed && (element != null)) { return(element); } base.ModelBus.LogError(ErrorCategory.Error, Microsoft.VisualStudio.TextTemplating.Modeling.ModelBusExceptionMessages.GetErrorLoadFailed(modelFile)); if (serializationResult.Failed) { foreach (SerializationMessage message in serializationResult) { base.ModelBus.LogError(FromKind(message.Kind), message.Message); } } return(null); }
internal override EntityDesignerViewModel LoadModelAndDiagram( SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition, string diagramFileName, ISchemaResolver schemaResolver, ValidationController validationController, ISerializerLocator serializerLocator) { EntityDesignerViewModel evm = null; using (new VsUtils.HourglassHelper()) { evm = LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator); var diagram = CreateDiagramHelper(diagramPartition, evm); } return evm; }
public void Setup() { _successUnserializableTypehelper = new Mock <IUnserializableTypeHelper>(); _successUnserializableTypehelper.Setup(x => x.IsUnserializable(It.IsAny <Type>())).Returns(false); _failUnserializableTypehelper = new Mock <IUnserializableTypeHelper>(); _failUnserializableTypehelper.Setup(x => x.IsUnserializable(It.IsAny <Type>())).Returns(true); _successSerHelper = new Mock <ISerializationHelper>(); _successSerHelper.Setup(x => x.Serialize(It.IsAny <object>())).Returns(SerializationResult.InitSuccessfulSerialization(new object(), String.Empty, typeof(object))); _failSerHelper = new Mock <ISerializationHelper>(); _failSerHelper.Setup(x => x.Serialize(It.IsAny <object>())).Returns(SerializationResult.InitFailedSerialization(new object(), new StackOverflowException(), typeof(object))); }
internal override EntityDesignerViewModel LoadModelAndDiagram( SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition, string diagramFileName, ISchemaResolver schemaResolver, ValidationController validationController, ISerializerLocator serializerLocator) { EntityDesignerViewModel evm = null; using (new VsUtils.HourglassHelper()) { evm = LoadModel(serializationResult, modelPartition, modelFileName, schemaResolver, validationController, serializerLocator); var diagram = CreateDiagramHelper(diagramPartition, evm); } return(evm); }
public MetaModel LoadLibrary() { MetaModel m = null; using (Transaction t = this.Store.TransactionManager.BeginTransaction("load library", true)) { SerializationResult serializationResult = new SerializationResult(); m = LoadLibrary(serializationResult); t.Commit(); } return(m); }
public MetaModel LoadLibrary() { MetaModel m = null; using (Transaction t = this.Store.TransactionManager.BeginTransaction("load library", true)) { SerializationResult serializationResult = new SerializationResult(); m = LoadLibrary(serializationResult); t.Commit(); } return m; }
internal long WriteXref(SerializationResult serializeResult) { var position = this.Position; var xrefTable = new XrefTable(); foreach (var offset in serializeResult.Offsets) { xrefTable.Add(offset, new IndirectReference(0, 0)); } this.iSer.SerializeXrefTable(this, xrefTable); return(position); }
/// <summary> /// Serialize a C# model instance to JSON /// </summary> /// <typeparam name="TModel">The model type should be serialized</typeparam> /// <param name="model">The instance of the model, should be serialized</param> /// <param name="indented">Should the content well formatted?</param> /// <param name="ignoreValidation">Ignore the validation after serialization. May be helpful if no JSON Schema license is available</param> /// <returns>Instance of <see cref="SerializationResult"/></returns> /// <example> /// Serialize a model instance to JSON. /// <code>var result = Converter.Serialize(m);</code> /// </example> public static SerializationResult Serialize <TModel>(TModel model, bool indented = false, bool ignoreValidation = false, bool writeMetadata = false) where TModel : EdiModel { var schemaAttribute = typeof(TModel).GetCustomAttribute <ConiziSchemaAttribute>(); if (schemaAttribute == null) { throw new InvalidOperationException("Class is no valid conizi model!"); } var settings = SerializerSettings; if (writeMetadata) { model.AddOrUpdateMetadata(new EdiMetadata { CreatedAt = DateTime.Now, CreatedBy = typeof(Converter).Namespace + " (" + typeof(Converter).Assembly.GetName().Version + ")", Environment = "dev" }); } if (!indented) { settings.Formatting = Formatting.None; } var jsonString = JsonConvert.SerializeObject(model, settings); var conversionResult = new SerializationResult { Content = jsonString }; if (ignoreValidation) { return(conversionResult); } if (!Validator.ValidateSchema <TModel>(jsonString, out var validationErrors).IsValid) { conversionResult.ValidationErrors = validationErrors; } conversionResult.IsValidated = true; return(conversionResult); }
/// <summary> /// Constructeur privé. On ne peut instancier un loader qu'avec GetLoader (qui gére le cache) /// </summary> /// <param name="fileName"></param> private ModelLoader(string fileName) { SetFileName(fileName); Store store = CreateStore(); // Ouverture d'une transaction avec l'attribut IsSerializing à True using (Transaction transaction = store.TransactionManager.BeginTransaction("Load model", true)) { DisableAllRules(store); transaction.Context.ContextInfo["InModelLoader"] = true; // Chargement du modèle (Peut générer des exceptions) _serializationResult = new SerializationResult(); _model = CandleSerializationHelper.Instance.LoadModel(_serializationResult, store, fileName, null, null); transaction.Commit(); } }
// 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(SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition, string diagramFileName, LALDominio modelRoot, VisualLALDiagram diagram) { //Debug.WriteLine("OnPostLoadModelAndDiagram"); if (!serializationResult.Failed) { VisualLALMapeamento.Instance.SetStore(modelRoot.Store); var entries = VisualLALMapeamento.Instance.MapaEntradas; var links = VisualLALMapeamento.Instance.MapaReferencias; var simbolos = modelRoot.Simbolos; var sinonimos = modelRoot.Simbolos.SelectMany(s => s.Sinonimos); var nocoes = modelRoot.Simbolos.SelectMany(s => s.Nocoes); var impactos = modelRoot.Simbolos.SelectMany(s => s.Impactos); links.ApagarTudo(); entries.ApagarTudo(); foreach (var s in simbolos) { //Debug.WriteLine(s.Nome); entries.Adicionar(s); } foreach (var s in sinonimos) { //Debug.WriteLine(s.Nome); entries.Adicionar(s); } foreach (var n in nocoes) { //Debug.WriteLine(n.Texto); links.AnalisaEAdicionaMapaDeReferenciaParaNovaSubEntrada(n); } foreach (var b in impactos) { //Debug.WriteLine(b.Texto); links.AnalisaEAdicionaMapaDeReferenciaParaNovaSubEntrada(b); } return; } Debug.WriteLine("OnPostLoadModelAndDiagram Failed"); }
/// <summary> /// Save the given document that is subordinate to this document. /// </summary> /// <param name="subordinateDocument">The subordinate document.</param> /// <param name="fileName">The fileName to save.</param> protected override void SaveSubordinateFile(DocData subordinateDocument, string fileName) { Guard.NotNull(() => subordinateDocument, subordinateDocument); SerializationResult serializationResult = new SerializationResult(); var diagrams = this.GetDiagrams(fileName); foreach (var diagram in diagrams) { try { this.SuspendFileChangeNotification(diagram.Key); PatternModelSerializationHelper.Instance.SaveDiagram(serializationResult, diagram.Value, diagram.Key, this.Encoding, false); } finally { this.ResumeFileChangeNotification(fileName); } } this.SuspendErrorListRefresh(); try { foreach (var serializationMessage in serializationResult) { this.AddErrorListItem(new SerializationErrorListItem(this.ServiceProvider, serializationMessage)); } } finally { this.ResumeErrorListRefresh(); } if (!serializationResult.Failed) { this.NotifySubordinateDocumentSaved(subordinateDocument.FileName, fileName); } else { throw new InvalidOperationException(PatternModelDomainModel.SingletonResourceManager.GetString("CannotSaveDocument")); } }
public void Clone() { tracer.Info(string.Format(CultureInfo.InvariantCulture, Properties.Resources.PatternModelCloner_PatternModelCloning, this.SourcePatternModel.Id)); tracer.Info(Properties.Resources.PatternModelCloner_EstablishingPatternModelInheritance); this.TargetPatternModel.Store.TransactionManager.DoWithinTransaction( () => this.TargetPatternModel.BaseVersion = this.SourceVersion.ToString()); if (this.SourcePatternModel.Pattern != null) { var serializationResult = new SerializationResult(); this.TargetPatternModel.Store.TransactionManager.DoWithinTransaction(() => { tracer.Info(Properties.Resources.PatternModelCloner_CloningViews); foreach (var view in this.SourcePatternModel.Pattern.Views) { tracer.Info(string.Format(CultureInfo.InvariantCulture, Properties.Resources.PatternModelCloner_CloningView, view.Name)); PatternModelSerializationHelper.CreatePatternModelSchemaDiagram( serializationResult, this.TargetPatternModel.Store.GetDefaultDiagramPartition(), this.TargetPatternModel, view.DiagramId); } }); if (this.SourcePatternModel.Pattern != null) { tracer.Info(Properties.Resources.PatternModelCloner_CloningProduct); CopyElementGraph(this.TargetPatternModel.Store, this.TargetPatternModel, this.SourcePatternModel.Pattern); } tracer.Info(Properties.Resources.PatternModelCloner_EstablishingElementInheritance); this.SetNamedElementBaseIdentifiers(); } else { tracer.Warn(Properties.Resources.PatternModelCloner_PatternSchemaNotFound); } }
private static ConfigurationSectionModel PrepareModel(string inputFilePath, Store store) { ConfigurationSectionModel model; using (Transaction transaction = store.TransactionManager.BeginTransaction("Load", true)) { SerializationResult serializationResult = new SerializationResult(); model = ConfigurationSectionDesignerSerializationHelper.Instance.LoadModel(serializationResult, store, inputFilePath, null, null); if (serializationResult.Failed) { throw new SerializationException(serializationResult); } transaction.Commit(); } return(model); }
/// <summary> /// Loads the domain model serialized in the specified path. /// </summary> /// <param name="modelPath">The model path.</param> /// <param name="loader">The model loader.</param> /// <returns></returns> public static TModel LoadModel <TDomainModel, TModel>(string modelPath, ModelLoader <TModel> loader) where TDomainModel : DomainModel where TModel : ModelElement { Store store = new Store(typeof(CoreDesignSurfaceDomainModel), typeof(TDomainModel)); SerializationResult result = new SerializationResult(); using (Transaction transaction = store.TransactionManager.BeginTransaction("Load", true)) { TModel model = loader(modelPath, store, result); if (result.Failed) { throw new SerializationException(result); } transaction.Commit(); return(model); } }
public static SubProcess CreateNewSubProcess(string subProcessName, ProjectItem subProcessItem, ModelBusReference processReference) { var store = new Store(typeof(CloudCoreArchitectSubProcessDomainModel)); var partition = new Partition(store); var result = new SerializationResult(); using (Transaction t = store.TransactionManager.BeginTransaction("create new model")) { try { var subProcessDSLSerializationHelper = CloudCoreArchitectSubProcessSerializationHelper.Instance; SubProcess subProcess = subProcessDSLSerializationHelper.CreateModelHelper(partition); SetSubProcessSettings(subProcessName, subProcess, processReference); CreateAndSaveSubProcessFile(partition, result, subProcessItem.FileNames[0], subProcessDSLSerializationHelper, subProcess); ModelBusReference subProcessReference = GetSubProcessOverviewFileModelBusReference(subProcessItem.FileNames[0]); ProcessOverview.ProcessOverviewDiagram diagram = ProcessOverview.CustomCode.Helpers.ProcessFileHelper.GetProcessOverviewDiagram(processReference); ProcessOverview.Process process = diagram.ModelElement as ProcessOverview.Process; Architect.ProcessOverview.SubProcessElement subProcessElement = null; using (Transaction tB = diagram.Store.TransactionManager.BeginTransaction("create subprocess element")) { subProcessElement = ProcessOverview.CustomCode.Helpers.ProcessFileHelper.CreateSubProcessElement(subProcessName, process.Partition, process, subProcess, subProcessReference); tB.Commit(); } t.Commit(); ProcessOverview.CustomCode.Helpers.ProcessFileHelper.SetAddedSubProcessReference(subProcessReference, subProcessItem.Name, processReference, subProcessElement); return subProcess; } catch (Exception ex) { MessageBox.Show(ex.Message); } return null; } }
internal override EntityDesignerViewModel LoadModel( SerializationResult serializationResult, Partition partition, string fileName, ISchemaResolver schemaResolver, ValidationController validationController, ISerializerLocator serializerLocator) { var docData = VSHelpers.GetDocData(PackageManager.Package, fileName) as IEntityDesignDocData; docData.CreateAndLoadBuffer(); EntityDesignerViewModel evm = null; var serializationContext = new SerializationContext(GetDirectory(partition.Store), fileName, serializationResult); var transactionContext = new TransactionContext(); transactionContext.Add(SerializationContext.TransactionContextKey, serializationContext); using (var t = partition.Store.TransactionManager.BeginTransaction("Load Model from " + fileName, true, transactionContext)) { var uri = Tools.XmlDesignerBase.Base.Util.Utils.FileName2Uri(fileName); var context = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(uri); evm = ModelTranslatorContextItem.GetEntityModelTranslator(context).TranslateModelToDslModel(null, partition) as EntityDesignerViewModel; if (evm == null) { serializationResult.Failed = true; } else { if (t.IsActive) { t.Commit(); } } } // Validate imported model if (!serializationResult.Failed && (validationController != null)) { validationController.Validate(partition, ValidationCategories.Load); } return(evm); }
/// <summary> /// Loads the given file. /// </summary> protected void LoadVModell(string fileName, bool isReload) { SerializationResult serializationResult = new SerializationResult(); global::Tum.PDE.LanguageDSL.MetaModel modelRoot = null; ISchemaResolver schemaResolver = new ModelingSchemaResolver(this.ServiceProvider); //clear the current root element this.SetRootElement(null); modelRoot = global::Tum.PDE.LanguageDSL.LanguageDSLSerializationHelper.Instance.LoadModel(serializationResult, this.GetModelPartition(), fileName, schemaResolver, null /* no load-time validation */, this.SerializerLocator, true, true); // Report serialization messages. this.SuspendErrorListRefresh(); try { foreach (SerializationMessage serializationMessage in serializationResult) { this.AddErrorListItem(new SerializationErrorListItem(this.ServiceProvider, serializationMessage)); } } finally { this.ResumeErrorListRefresh(); } if (serializationResult.Failed) { // Load failed, can't open the file. throw new global::System.InvalidOperationException(global::Tum.PDE.LanguageDSL.LanguageDSLDomainModel.SingletonResourceManager.GetString("CannotOpenDocument")); } else { this.SetRootElement(modelRoot); // Attempt to set the encoding if (serializationResult.Encoding != null) { this.ModelingDocStore.SetEncoding(serializationResult.Encoding); global::Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(this.SetDocDataDirty(0)); // Setting the encoding will mark the document as dirty, so clear the dirty flag. } } }
internal override EntityDesignerViewModel LoadModel( SerializationResult serializationResult, Partition partition, string fileName, ISchemaResolver schemaResolver, ValidationController validationController, ISerializerLocator serializerLocator) { var docData = VSHelpers.GetDocData(PackageManager.Package, fileName) as IEntityDesignDocData; docData.CreateAndLoadBuffer(); EntityDesignerViewModel evm = null; var serializationContext = new SerializationContext(GetDirectory(partition.Store), fileName, serializationResult); var transactionContext = new TransactionContext(); transactionContext.Add(SerializationContext.TransactionContextKey, serializationContext); using (var t = partition.Store.TransactionManager.BeginTransaction("Load Model from " + fileName, true, transactionContext)) { var uri = Tools.XmlDesignerBase.Base.Util.Utils.FileName2Uri(fileName); var context = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(uri); evm = ModelTranslatorContextItem.GetEntityModelTranslator(context).TranslateModelToDslModel(null, partition) as EntityDesignerViewModel; if (evm == null) { serializationResult.Failed = true; } else { if (t.IsActive) { t.Commit(); } } } // Validate imported model if (!serializationResult.Failed && (validationController != null)) { validationController.Validate(partition, ValidationCategories.Load); } return evm; }
public override HostDesignerModel LoadModelAndDiagram( SerializationResult serializationResult, Partition modelPartition, string modelFileName, Partition diagramPartition, string diagramFileName, ISchemaResolver schemaResolver, ValidationController validationController, ISerializerLocator serializerLocator) { ISchemaResolver resolver = new CustomModelingSchemaResolver(schemaResolver, "GeneratedCode\\HostDesignerSchema.xsd"); return base.LoadModelAndDiagram( serializationResult, modelPartition, modelFileName, diagramPartition, diagramFileName, resolver, validationController, serializerLocator); }
private static void CreateAndSaveSubProcessFile(Partition partition, SerializationResult result, string subProcessFile, CloudCoreArchitectSubProcessSerializationHelper subProcessDSLSerializationHelper, SubProcess subProcess) { var bDiagram = subProcessDSLSerializationHelper.CreateDiagramHelper(partition, subProcess); subProcessDSLSerializationHelper.SaveModelAndDiagram(result, subProcess, subProcessFile, bDiagram, subProcessFile + ".diagram", Encoding.UTF8, false); }
protected override void Load(string fileName, bool reload) { Guard.NotNullOrEmpty(() => fileName, fileName); var serializationResult = new SerializationResult(); PatternModelSchema modelRoot = null; var schemaResolver = new ModelingSchemaResolver(this.ServiceProvider); PatternModelDomainModel.EnableDiagramRules(this.Store); this.Store.RuleManager.DisableRule(typeof(FixUpDiagram)); this.Store.RuleManager.EnableRule(typeof(FixUpMultipleDiagram)); var diagramFileNames = Directory.GetFiles( Path.GetDirectoryName(fileName), string.Concat("*", DesignerConstants.ModelExtension, DesignerConstants.DiagramFileExtension)); // Run migration rules this.ExecuteUpgradeRules(fileName, diagramFileNames); // Load models modelRoot = PatternModelSerializationHelper.Instance.LoadModelAndDiagrams( serializationResult, this.GetModelPartition(), fileName, this.GetDiagramPartition(), diagramFileNames, schemaResolver, null /* no load-time validation */, this.SerializerLocator); this.SuspendErrorListRefresh(); try { foreach (SerializationMessage serializationMessage in serializationResult) { this.AddErrorListItem(new SerializationErrorListItem(this.ServiceProvider, serializationMessage)); } } finally { this.ResumeErrorListRefresh(); } if (serializationResult.Failed) { throw new InvalidOperationException(PatternModelDomainModel.SingletonResourceManager.GetString("CannotOpenDocument")); } else { this.SetRootElement(modelRoot); // Attempt to set the encoding if (serializationResult.Encoding != null) { this.ModelingDocStore.SetEncoding(serializationResult.Encoding); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(this.SetDocDataDirty(0)); // Setting the encoding will mark the document as dirty, so clear the dirty flag. } } this.RehydrateModel(); }
/// <summary> /// Saves the given file. /// </summary> /// <param name="fileName">The filename.</param> protected override void Save(string fileName) { Guard.NotNullOrEmpty(() => fileName, fileName); var serializationResult = new SerializationResult(); var modelRoot = (PatternModelSchema)this.RootElement; bool saveAs = StringComparer.OrdinalIgnoreCase.Compare(fileName, this.FileName) != 0; var diagrams = this.GetDiagrams(fileName); if (diagrams.Count > 0 && !saveAs) { try { foreach (var diagramFile in diagrams) { this.SuspendFileChangeNotification(diagramFile.Key); } PatternModelSerializationHelper.Instance.SaveModelAndDiagrams(serializationResult, modelRoot, fileName, diagrams, this.Encoding, false); var solution = this.ServiceProvider.GetService<ISolution>(); if (solution == null) { throw new InvalidOperationException("Can not locate solution service."); } AddDependentFiles(this.ServiceProvider.GetService<ISolution>(), fileName, diagrams.Select(dg => dg.Key)); } finally { foreach (var diagramFile in diagrams) { this.ResumeFileChangeNotification(diagramFile.Key); } } } else { PatternModelSerializationHelper.Instance.SaveModel(serializationResult, modelRoot, fileName, this.Encoding, false); } this.SuspendErrorListRefresh(); try { foreach (SerializationMessage serializationMessage in serializationResult) { this.AddErrorListItem(new SerializationErrorListItem(this.ServiceProvider, serializationMessage)); } } finally { this.ResumeErrorListRefresh(); } if (serializationResult.Failed) { throw new InvalidOperationException(PatternModelDomainModel.SingletonResourceManager.GetString("CannotSaveDocument")); } }
/// <summary> /// This method loads the DSL view model with the items in the artifact's C-Model. /// </summary> internal void ReloadModel(EntityDesignerViewModel viewModel) { var diagram = viewModel.GetDiagram(); if (diagram == null) { // empty DSL diagram return; } // get our artifact var artifact = EditingContextManager.GetArtifact(viewModel.EditingContext) as EntityDesignArtifact; Debug.Assert(artifact != null); var serializationResult = new SerializationResult(); var serializationContext = new SerializationContext(GetDirectory(viewModel.Store), artifact.Uri.LocalPath, serializationResult); var transactionContext = new TransactionContext(); transactionContext.Add(SerializationContext.TransactionContextKey, serializationContext); var workaroundFixSerializationTransactionValue = false; if (viewModel.Store.PropertyBag.ContainsKey("WorkaroundFixSerializationTransaction")) { workaroundFixSerializationTransactionValue = (bool)viewModel.Store.PropertyBag["WorkaroundFixSerializationTransaction"]; } try { // To fix performance issue during reload, we turn-off layout during "serialization". viewModel.Store.PropertyBag["WorkaroundFixSerializationTransaction"] = true; using (var t = viewModel.Store.TransactionManager.BeginTransaction("ReloadModel", true, transactionContext)) { if (artifact.ConceptualModel() == null) { return; } DesignerModel.Diagram diagramModel = null; // If DiagramId is not string empty, try to get the diagram from the artifact. // There is a situation where we could not find the diagram given an ID (for example: EDMX Model's Diagram that is created by VS before SQL 11; // In that case, we assign temporary ID to the diagram and a new ID will be generated every time the model is reloaded.) // We could safely choose the first diagram since multiple diagrams feature didn't exist in VS prior to SQL11 release. if (!string.IsNullOrEmpty(diagram.DiagramId)) { diagramModel = artifact.DesignerInfo.Diagrams.GetDiagram(diagram.DiagramId); } if (diagramModel == null) { diagramModel = artifact.DesignerInfo.Diagrams.FirstDiagram; } if (diagramModel != null) { // Re-establish the xref between Escher conceptual model and DSL root model. // and between Escher Diagram model and DSL diagram model. Debug.Assert(viewModel.ModelXRef != null, "Why ModelXRef is null?"); if (viewModel.ModelXRef != null) { viewModel.ModelXRef.Add(artifact.ConceptualModel(), viewModel, viewModel.EditingContext); viewModel.ModelXRef.Add(diagramModel, diagram, viewModel.EditingContext); ModelTranslatorContextItem.GetEntityModelTranslator(viewModel.EditingContext) .TranslateModelToDslModel(diagramModel, viewModel.Partition); } } if (t.IsActive) { t.Commit(); } } } finally { viewModel.Store.PropertyBag["WorkaroundFixSerializationTransaction"] = workaroundFixSerializationTransactionValue; } }
/// <summary> /// Reads the model into the given store and returns it. /// </summary> public static IPatternModelSchema Read(SerializationResult result, Store store, string modelFile) { return PatternModelSerializationHelper.Instance.LoadModel(result, store, modelFile, null, null, null); }
internal override MemoryStream InternalSaveModel( SerializationResult serializationResult, EntityDesignerViewModel modelRoot, string fileName, Encoding encoding, bool writeOptionalPropertiesWithDefaultValue) { IEntityDesignDocData docData = null; MemoryStream stream = null; Debug.Assert(modelRoot.EditingContext != null, "Designer model root has a null EditingContext"); if (modelRoot.EditingContext != null) { // find our doc data; don't use the passed in fileName as this will be the new name // during a SaveAs operation var artifact = EditingContextManager.GetArtifact(modelRoot.EditingContext); if (artifact != null) { docData = VSHelpers.GetDocData(PackageManager.Package, artifact.Uri.LocalPath) as IEntityDesignDocData; } Debug.Assert(docData != null, "Couldn't locate our DocData"); if (docData != null) { var text = docData.GetBufferTextForSaving(); if (!string.IsNullOrEmpty(text)) { stream = FileUtils.StringToStream(text, encoding) as MemoryStream; } } } // if we don't have a stream, then we couldn't serialize for some reason if (stream == null) { serializationResult.Failed = true; } return stream; }
public override MetaModel LoadModel(SerializationResult serializationResult, Store store, string fileName, ISchemaResolver schemaResolver, DslValidation.ValidationController validationController, ISerializerLocator serializerLocator) { return LoadModel(serializationResult, store.DefaultPartition, fileName, schemaResolver, validationController, serializerLocator, true, true); }
//private dynamic GetFlowDetermined(Activity source, Activity target) //{ // //if (source is Rule) // // return Flow.GetLink(source, target); // //return FlowMinimal.GetLink(source, target); //} private void UpdateExistingProcessFile() { var store = new Store(typeof(CloudCoreArchitectSubProcessDomainModel)); var result = new SerializationResult(); _backupFolderPath = txtBackupLocation.Text + ((txtBackupLocation.Text.Last().ToString() != @"\") ? @"\" : string.Empty); btnImport.Enabled = false; btnCancel.Enabled = false; foreach (SubProcess btProcess in _btProcessList) { #region Delete Existing start page elements from assemblyinfo var assemblyPath = string.Format(@"{0}\Properties\AssemblyInfo.cs", _projectFolderPath); ProjectItem assemblyProjectItem = _dte.Solution.FindProjectItem(assemblyPath); var elements = assemblyProjectItem.FileCodeModel.CodeElements; var processIdStr = string.Format(", \"{0}\"", btProcess.VisioId); for (var index = 1; index <= elements.Count; index++) { var elemnt = elements.Item(index); if (elemnt.Kind != vsCMElement.vsCMElementAttribute) continue; if (elemnt.Name != "BTEmbeddedProcessUrl") continue; var u = (CodeAttribute)elemnt; if (u.Value.IndexOf(processIdStr) != -1) { u.Delete(); } } #endregion #region Add start page elements to assembly info //ImportHelper.AddAssembly(_dte, assemblyProjectItem.ContainingProject, btProcess, startPagesList); #endregion #region Delete and move code items marked for deletion if (deletedCode.Count > 0) { foreach (var f in deletedCode) { if (f.Path != null) if (f.Path.IndexOf("aspx") != -1) { ImportHelper.MovePageCodeToBackup(f.Id, f.Path, f.Name, _backupFolderPath, _dte); } else { ImportHelper.MoveCodeToBackup(f.Id, f.Path, f.Name, _backupFolderPath, _dte); } } } #endregion #region Save Diagram using (Transaction trans = store.TransactionManager.BeginTransaction("save")) { CloudCoreArchitectSubProcessSerializationHelper.Instance.SaveModelAndDiagram(result, btProcess, _filePath, _bDiagram, _filePath + ".diagram", Encoding.UTF8, false); ProjectItem file = _dte.Solution.FindProjectItem(_filePath); file.Open().Activate(); file.Save(); trans.Commit(); } #endregion CreateCodeFiles(btProcess); } Close(); }
internal override void SaveModelAndDiagram( SerializationResult serializationResult, EntityDesignerViewModel modelRoot, string modelFileName, EntityDesignerDiagram diagram, string diagramFileName, Encoding encoding, bool writeOptionalPropertiesWithDefaultValue) { // only save the model base.SaveModel(serializationResult, modelRoot, modelFileName, encoding, writeOptionalPropertiesWithDefaultValue); if (!serializationResult.Failed) { // flip our dirty bit (as long as we aren't trying to save the auto-recovery backup file) var artifact = EditingContextManager.GetArtifact(modelRoot.EditingContext); Debug.Assert(artifact != null, "Failed to get a valid EFArtifact from the context"); IEntityDesignDocData docData = null; var fileName = String.Empty; if (artifact != null) { fileName = artifact.Uri.LocalPath; } docData = VSHelpers.GetDocData(PackageManager.Package, fileName) as IEntityDesignDocData; Debug.Assert(docData != null, "Couldn't locate our DocData"); if (artifact != null && docData != null && !string.Equals(docData.BackupFileName, modelFileName, StringComparison.OrdinalIgnoreCase)) { artifact.IsDirty = false; } // SaveDiagram file if the file exists // TODO: What happened if saving diagram file failed? Should we rollback the model file? var diagramDocData = VSHelpers.GetDocData(PackageManager.Package, fileName + EntityDesignArtifact.ExtensionDiagram) as XmlModelDocData; if (diagramDocData != null) { int saveIsCancelled; diagramDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out diagramFileName, out saveIsCancelled); } } }
private void CreateNewProcessFile(SubProcess btProcess) { var store = new Store(typeof(CloudCoreArchitectSubProcessDomainModel)); var result = new SerializationResult(); #region Delete Existing start page elements from assemblyinfo var assemblyPath = string.Format(@"{0}\Properties\AssemblyInfo.cs", _projectFolderPath); ProjectItem assemblyProjectItem = _dte.Solution.FindProjectItem(assemblyPath); var elements = assemblyProjectItem.FileCodeModel.CodeElements; var processIdStr = string.Format(", \"{0}\"", btProcess.VisioId); for (var index = 1; index <= elements.Count; index++) { var elemnt = elements.Item(index); if (elemnt.Kind != vsCMElement.vsCMElementAttribute) continue; if (elemnt.Name != "BTEmbeddedProcessUrl") continue; var u = (CodeAttribute)elemnt; if (u.Value.IndexOf(processIdStr) != -1) { u.Delete(); } } #endregion #region Add start page elements to assembly info //ImportHelper.AddAssembly(_dte, assemblyProjectItem.ContainingProject, btProcess, startPagesList); #endregion using (Transaction trans = store.TransactionManager.BeginTransaction("save")) { CloudCoreArchitectSubProcessSerializationHelper.Instance.SaveModelAndDiagram(result, btProcess, _filePath, _bDiagram, _filePath + ".diagram", Encoding.UTF8, false); ProjectItem file = _l.FirstOrDefault(p => p.ProjectPath == lstProjects.SelectedValue.ToString()).ProjectObject.ProjectItems.AddFromFile(_filePath); file.Open().Activate(); file.Save(); //file.Properties.Item("CustomTool").Value = "SubProcessFileCodeGenerator"; trans.Commit(); } CreateCodeFiles(btProcess); }