public FCO( MgaObject subject, CodeTypeReferenceCollection baseTypes, CodeTypeReferenceCollection attributes) : base(subject, baseTypes, attributes) { }
public void Export() { avm.Design design = null; proj.PerformInTransaction(delegate { // Retrieve design contain as MgaObject MgaObject objDesignContainer = null; objDesignContainer = proj.get_ObjectByPath(@"DesignSpaces/DesignContainer"); Assert.NotNull(objDesignContainer); // Cast as DesignContainer and run converter var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(objDesignContainer); design = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(designContainer); }); Assert.NotNull(design); String pathXmlOut = Path.Combine(fixture.PathTest, "DesignContainer.adm"); using (StreamWriter sw = new StreamWriter(pathXmlOut, false)) { sw.Write(design.Serialize()); } var checker = new LayoutDataChecker(); var result = checker.Check(design.RootContainer); if (result.Any()) { String msg = Environment.NewLine + String.Join(Environment.NewLine, result); Assert.True(false, msg); } }
private static string GetNamespaceName(MgaObject obj) { Contract.Requires(obj != null); string ns = ""; MgaModel paradigmSheet = null; MgaFolder rootFolder = null; if (obj.MetaBase.Name == "RootFolder") { rootFolder = obj as MgaFolder; } else { paradigmSheet = (obj as MgaFCO).ParentModel; rootFolder = GetLibraryRoot(paradigmSheet.ParentFolder); } try { ns = rootFolder.RegistryValue["Namespace"]; } catch { // com exception... } return(ns); }
public avm.Design Convert(String pathDE) { MgaObject objDE = null; proj.PerformInTransaction(delegate { objDE = proj.get_ObjectByPath(pathDE); }); Assert.NotNull(objDE); var interp = new CyPhyDesignExporter.CyPhyDesignExporterInterpreter(); interp.Initialize(proj); InterpreterMainParameters param = new InterpreterMainParameters() { OutputDirectory = PathTest, CurrentFCO = objDE as MgaFCO, Project = proj }; var result = interp.Main(param); Assert.True(result.Success); // Load the new .adm file var pathAdm = Path.Combine(PathTest, pathDE.Split('/').Last() + ".adm"); var xml = File.ReadAllText(pathAdm); var design = OpenMETA.Interchange.AvmXmlSerializer.Deserialize <avm.Design>(xml); Assert.NotNull(design); return(design); }
// Not used by GME public void ObjectsInvokeEx( MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); }
/// <summary> /// Returns true if parent is either a Configurations or CWC /// </summary> /// <param name="parent"></param> /// <returns></returns> protected bool IsConfigurationType(MgaObject parent) { if (parent.MetaBase.MetaRef == this.Factory.ConfigurationsMeta || parent.MetaBase.MetaRef == this.Factory.CWCMeta) { return(true); } return(false); }
/// <summary> /// Returns true if parent is either a Configurations or CWC /// </summary> /// <param name="parent"></param> /// <returns></returns> protected bool IsConfigurationType(MgaObject parent) { if (parent.MetaBase.MetaRef == this.Factory.ConfigurationsMeta || parent.MetaBase.MetaRef == this.Factory.CWCMeta) { return true; } return false; }
/// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject">the object the event(s) happened to</param> /// <param name="eventMask">objectevent_enum values ORed together</param> /// <param name="param">extra information provided for cetertain event types</param> public void ObjectEvent(MgaObject subject, uint eventMask, object param) { // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(project); } TriggerQudtRefreshIfNeeded(); }
internal static string GetNamespacePrefixedName(MgaObject obj) { string ns = GetNamespaceName(obj); if (string.IsNullOrEmpty(ns) == false) { return(ns + "_" + obj.Name); } return(obj.Name); }
/// <summary> /// format NSName:: /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetGmeNamespaceName(MgaObject obj) { string ns = GetNamespaceName(obj); if (string.IsNullOrEmpty(ns) == false) { ns = ns + GmeNamespaceDelimiter; } return(ns); }
private void DisplayPCCIterations(MgaObject subject, bool attributeChanged) { List <string> kinds = new List <string>() { "PCCDriver", "PCCParameterBeta", "PCCParameterUniform", "PCCParameterLNormal", "PCCParameterNormal" }; if (kinds.Contains(subject.MetaBase.Name) == false) { return; } MgaModel PCCDriver = null; if (attributeChanged && subject.MetaBase.Name == "PCCDriver") { // TODO: Compute and PCCDriver = subject as MgaModel; } else if (attributeChanged == false && subject.MetaBase.Name == "PCCDriver") { // Compute and prin //GME.MGA.Meta.objtype_enum type; //MgaObject parent; //(subject as MgaFCO).GetParent(out parent, out type); PCCDriver = subject as MgaModel; } else { return; } //Compute and print PCCDriver var nbrOfParameters = PCCDriver.ChildFCOs.Cast <MgaFCO>().Where(x => kinds.Contains(x.Meta.Name)).Count(); var saMethod = PCCDriver.StrAttrByName["PCC_SA_Methods"]; var upMethod = PCCDriver.StrAttrByName["PCC_UP_Methods"]; GMEConsole.Out.WriteLine("{2}Iterations : UP : {0}, SA : {1}", this.GetNumberOfIterations(upMethod, nbrOfParameters), this.GetNumberOfIterations(saMethod, nbrOfParameters), INFO_BADGE); }
private static String GetSimplePath(MgaObject obj) { var hierarchy = new List <MgaObject>(); var iter = obj; while (iter != null) { hierarchy.Add(iter); GME.MGA.Meta.objtype_enum ot; iter.GetParent(out iter, out ot); } hierarchy.Reverse(); return(String.Join("/", hierarchy.Select(o => o.Name))); }
internal static string GetKindName(MgaObject obj) { string ns = GetNamespaceName(obj); if (string.IsNullOrEmpty(ns) == false) { ns = ns + GmeNamespaceDelimiter; } if (obj is MgaReference) { return(ns + (obj as MgaReference).Referred.Name); } else { return(ns + obj.Name); } }
public Base( MgaObject subject, CodeTypeReferenceCollection baseTypes, CodeTypeReferenceCollection attributes) { Subject = subject; BaseTypes = baseTypes; Attributes = attributes; if (Subject.MetaBase.Name == "RootFolder") { ClassName = "RootFolder"; } else { ClassName = subject.Name; } if (Subject.MetaBase.Name != "RootFolder") { baseClasses.Add(Subject as MgaFCO); baseClasses.AddRange(FCO.GetBaseClasses(Subject as MgaFCO)); } if (Subject is MgaFCO) { baseClassesWoObject.AddRange(FCO.GetBaseClasses(Subject as MgaFCO)); } //GeneratedClass = new CodeNamespace(Configuration.ProjectClassNamespace); //GeneratedInterface = new CodeNamespace(Configuration.ProjectIntefaceNamespace); GeneratedClass = new CodeNamespace(Configuration.GetClassNamespace(Subject)); GeneratedInterface = new CodeNamespace(Configuration.GetInterfaceNamespace(Subject)); GeneratedClass.Imports.Add(new CodeNamespaceImport("global::System.Linq")); //GeneratedClass.Imports.Add(new CodeNamespaceImport("global::GME.MGA")); //GeneratedInterface.Imports.Add(new CodeNamespaceImport("global::GME.MGA")); GenerateClassCode(); GenerateInterfaceCode(); }
internal static string GetInterfaceNamespace(MgaObject obj) { Contract.Requires(obj != null); string ns = GetNamespaceName(obj); if (string.IsNullOrEmpty(ns) == false) { ns = "." + ns; } if (obj is MgaReference) { return(Configuration.ProjectNamespace + ns + "." + Interfaces); } else { return(Configuration.ProjectNamespace + ns + "." + Interfaces); } }
internal static string GetClassName(MgaObject obj) { Contract.Requires(obj != null); Contract.Requires(obj is MgaFCO); string ns = GetNamespaceName(obj); if (string.IsNullOrEmpty(ns) == false) { ns = "." + ns; } if (obj is MgaReference) { return(Configuration.ProjectNamespace + ns + "." + Classes + "." + (obj as MgaReference).Referred.Name); } else { return(Configuration.ProjectNamespace + ns + "." + Classes + "." + obj.Name); } }
public void NullObjectAndInteractiveMode() { MgaProject project = null; MgaFCO currentObj = null; MgaFCOs fcos = null; MgaObject obj = null; MgaObjects objs = null; IMgaComponentEx interpreter = GetInterpreterByProgID(ProgID); Assert.Throws <ArgumentNullException>(() => { interpreter.Initialize(project); }); Assert.Throws <NotImplementedException>(() => { interpreter.ObjectsInvokeEx(project, obj, objs, 128); }); Assert.Throws <ArgumentNullException>(() => { interpreter.InvokeEx(project, currentObj, fcos, 128); }); Assert.True(File.Exists(this.mgaFile), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(this.mgaFile); project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { // project is set, but fcos are not Assert.DoesNotThrow(() => { interpreter.Initialize(project); }); Assert.Throws <ArgumentNullException>(() => { interpreter.InvokeEx(project, currentObj, fcos, 128); }); // fcos are set fcos = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); Assert.DoesNotThrow(() => { interpreter.InvokeEx(project, currentObj, fcos, 128); }); Assert.True(interpreter.InteractiveMode == false, "Interactive is not set correctly. (128) silent mode"); Assert.DoesNotThrow(() => { interpreter.InvokeEx(project, currentObj, fcos, 16); }); Assert.True(interpreter.InteractiveMode == true, "Interactive is not set correctly. (16)"); } finally { project.Close(true); } }
/// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject">the object the event(s) happened to</param> /// <param name="eventMask">objectevent_enum values ORed together</param> /// <param name="param">extra information provided for cetertain event types</param> public void ObjectEvent(MgaObject subject, uint eventMask, object param) { if (!componentEnabled || !handleEvents) { return; } if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(subject.Project); } if ((eventMask & (uint)objectevent_enum.OBJEVENT_OPENMODEL) != 0) { openModels.Add(subject.AbsPath); #if (DEBUG) GMEConsole.Info.Write(String.Format("Opened Model: {0}", subject.AbsPath)); #endif } if ((eventMask & (uint)objectevent_enum.OBJEVENT_CLOSEMODEL) != 0) { openModels.Remove(subject.AbsPath); #if (DEBUG) GMEConsole.Info.Write(String.Format("Closed Model: {0}", subject.AbsPath)); #endif } // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask // If the event is OBJEVENT_DESTROYED, most operations on subject will fail // Safe operations: getting Project, ObjType, ID, MetaRole, Meta, MetaBase, Name, AbsPath // Operations that will fail: all others, including attribute access and graph navigation // Try handling OBJEVENT_PRE_DESTROYED if these operations are necessary // Be careful not to modify Library objects (check subject.IsLibObject) // MessageBox.Show(eventMask.ToString()); // GMEConsole.Out.WriteLine(subject.Name); }
public static bool IsValidComponentRef(MgaObject obj) { return(obj.MetaBase.Name == "ComponentRef" && ((MgaReference)obj).Referred != null && ((MgaReference)obj).Referred.Status == (int)objectstatus_enum.OBJECT_EXISTS && ((MgaReference)obj).Referred.Meta.Name == "Component"); }
public static bool IsComponentRef(MgaObject obj) { return(obj.MetaBase.Name == "ComponentRef"); }
private void AddConnection(MgaObject subject) { // [1] Traverse a ConnectorComposition connection // [2] if (2 ends of a ConnectorComposition ends inside a Component) // Find matching datums // Create a constraint message // Send message // [3] Create Protobuf message // [4] Send message CyPhyML.ConnectorComposition connection = CyPhyMLClasses.ConnectorComposition.Cast(subject); if (connection != null) { // Is this an event from a Meta-Linked assembly? if (!syncedComponents.ContainsKey(connection.ParentContainer.Guid.ToString())) return; // snyako: removing and adding that connection back doesn't always work as connection doesn't always map the same way in Creo. Need to investigate this // Currently just re-sync the whole assembly CyPhyML.ComponentAssembly assembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, AssemblyID); RestartAssemblySyncAtEndOfTransaction(assembly); /* // [1] //CyPhyML.Connector startconnector = connection.SrcEnds.Connector; //CyPhy2CAD_CSharp.CommonTraversal traverser = new CyPhy2CAD_CSharp.CommonTraversal(startconnector); CyPhy2CAD_CSharp.CommonTraversal traverser = new CyPhy2CAD_CSharp.CommonTraversal(connection, CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, AssemblyID)); if (traverser.FoundConnectedNodes.Count != 2) { #if DEBUG GMEConsole.Warning.WriteLine("Unable to create constraint because >2 or <2 Connectors are connected together [" + connection.Path + "]"); #endif return; } // [2] if (traverser.FoundConnectedNodes.Count == 2) { if (traverser.FoundConnectedNodes[0].ParentContainer.Kind == "Component" && traverser.FoundConnectedNodes[1].ParentContainer.Kind == "Component") { MgaFCOs dstRefs = ((IMgaSimpleConnection)connection.Impl).DstReferences; MgaReference dstRef = null; if (dstRefs != null) { dstRef = dstRefs.Cast<MgaReference>().FirstOrDefault(); } MgaFCOs srcRefs = ((IMgaSimpleConnection)connection.Impl).SrcReferences; MgaReference srcRef = null; if (srcRefs != null) { srcRef = srcRefs.Cast<MgaReference>().FirstOrDefault(); } if (srcRef == null || dstRef == null) { return; } string aInstanceID; string bInstanceID; if (traverser.FoundConnectedNodes[0].ParentContainer.ID == dstRef.Referred.ID) { aInstanceID = CyPhyMLClasses.ComponentRef.Cast(dstRef).Attributes.InstanceGUID; bInstanceID = CyPhyMLClasses.ComponentRef.Cast(srcRef).Attributes.InstanceGUID; } else { aInstanceID = CyPhyMLClasses.ComponentRef.Cast(srcRef).Attributes.InstanceGUID; bInstanceID = CyPhyMLClasses.ComponentRef.Cast(dstRef).Attributes.InstanceGUID; } //= (traverser.FoundConnectedNodes[0].ParentContainer as CyPhyML.Component).Attributes.InstanceGUID; //= (traverser.FoundConnectedNodes[1].ParentContainer as CyPhyML.Component).Attributes.InstanceGUID; CyPhyML.CADModel acadmodel = CyphyMetaLinkUtils.FindCADModelObject(traverser.FoundConnectedNodes[0].ParentContainer as CyPhyML.Component); CyPhyML.CADModel bcadmodel = CyphyMetaLinkUtils.FindCADModelObject(traverser.FoundConnectedNodes[1].ParentContainer as CyPhyML.Component); if (acadmodel != null && bcadmodel != null) { CyPhy2CAD_CSharp.DataRep.StructuralInterfaceConstraint asirep = new CyPhy2CAD_CSharp.DataRep.StructuralInterfaceConstraint(traverser.FoundConnectedNodes[0] as CyPhyML.Connector, traverser.FoundConnectedNodes[0].ParentContainer.ID, aInstanceID); asirep.PopulateStructuralInterface(traverser.FoundConnectedNodes[0] as CyPhyML.Connector, acadmodel); CyPhy2CAD_CSharp.DataRep.StructuralInterfaceConstraint bsirep = new CyPhy2CAD_CSharp.DataRep.StructuralInterfaceConstraint(traverser.FoundConnectedNodes[1] as CyPhyML.Connector, traverser.FoundConnectedNodes[1].ParentContainer.ID, bInstanceID); bsirep.PopulateStructuralInterface(traverser.FoundConnectedNodes[1] as CyPhyML.Connector, bcadmodel); List<string> Errors_L = new List<string>(); List<Tuple<CyPhy2CAD_CSharp.DataRep.Datum, CyPhy2CAD_CSharp.DataRep.Datum>> constraintPairs = new List<Tuple<CyPhy2CAD_CSharp.DataRep.Datum, CyPhy2CAD_CSharp.DataRep.Datum>>(); CyPhy2CAD_CSharp.DataRep.StructuralInterfaceConstraint.MatchStructuralInterfaceDatums(asirep, bsirep, constraintPairs, Errors_L); // [] Figure out which component to add the constraint to int aConstraints = 0; int bConstraints = 0; if (!InstanceIDToConstraint_Table.TryGetValue(aInstanceID, out aConstraints)) { // root component InstanceIDToConstraint_Table.Add(aInstanceID, 1); aConstraints = 1; } if (!InstanceIDToConstraint_Table.TryGetValue(bInstanceID, out bConstraints)) { // root component InstanceIDToConstraint_Table.Add(bInstanceID, 1); bConstraints = 1; } string constraintComponentID; if (aConstraints > bConstraints) { constraintComponentID = bInstanceID; InstanceIDToConstraint_Table[bInstanceID] = InstanceIDToConstraint_Table[bInstanceID] + 1; } else { constraintComponentID = aInstanceID; InstanceIDToConstraint_Table[aInstanceID] = InstanceIDToConstraint_Table[aInstanceID] + 1; } // [3] Create Protobuf Message MetaLinkProtobuf.Edit message = CreateAddConstraintProtoBufMsg(constraintComponentID, constraintPairs); // [4] Send message bridgeClient.SendToMetaLinkBridge(message); } } */ } }
private void RemoveConstraint(MgaObject subject) { }
private void AddComponent(MgaObject mgaComponentRef) { // [1] Find ModelName // [2] Find ModelType // [3] Find URL - search path // [4] Find Instance GUID // [5] CADParameters // [6] Create Protobuf Message // [7] Send message CyPhyML.ComponentRef componentRef = CyPhyMLClasses.ComponentRef.Cast(mgaComponentRef); // Does this component belong to the Meta-Linked assembly? if (!syncedComponents.ContainsKey(componentRef.ParentContainer.Guid.ToString()) && !syncedComponents.ContainsKey(componentRef.Guid.ToString())) return; CyPhyML.Component component = componentRef.Referred.Component; if (component != null) { // [6] Create Protobuf message MetaLinkProtobuf.Edit message = AddComponentProtoBufMsg(componentRef); if (message != null) { // [6.5] Add SearchPath to message try { var env = new MetaLinkProtobuf.Environment { name = SearchPathStr, }; AddSearchPathToEnvironment(component, env); if (env.value.Count > 0) { message.actions[0].environment.Add(env); } } catch (IOException) { // XXX } // [7] Send message bridgeClient.SendToMetaLinkBridge(message); } } }
private void RemoveComponent(MgaObject mgaComponentRef) { }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List <IMgaFCO> objectsToCheck = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast <MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck = allObjects.Where(x => x.AbsPath.Contains("ProcessorTypesForContexts")).ToList(); objectsToCheck.Sort((x, y) => { return(x.Meta.Name.CompareTo(y.Meta.Name) != 0 ? x.Meta.Name.CompareTo(y.Meta.Name) : x.AbsPath.CompareTo(y.AbsPath)); }); } finally { project.AbortTransaction(); } Assert.True(objectsToCheck != null, "There are no object in the project that has to be checked."); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToCheck) { // single test CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; project.BeginTransactionInNewTerr(); try { Assert.ThrowsDelegate d = () => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel); }; MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var contextSupportExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; if (contextSupportExpected) { Assert.DoesNotThrow(d); Assert.True(analysisModelProcessor != null, string.Format("Analysis model processor was not able to create the model processor for {0} {1}.", subject.Name, subject.Meta.Name)); if (subject.Name.Contains(analysisModelProcessor.GetType().Name)) { numSuccess++; Console.Out.WriteLine("[Passed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name); } else { success = false; numFailures++; Console.Out.WriteLine("[Failed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name); } } else { Assert.Throws <CyPhyMasterInterpreter.AnalysisModelContextNotSupportedException>(d); numSuccess++; Console.Out.WriteLine("[Passed] Context not supported {0} [{1}]", subject.Name, subject.Meta.Name); } } finally { project.AbortTransaction(); } } if (success) { Console.Out.WriteLine("[OK] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one analysis model processor was not instantiated as expected."); } finally { project.Close(true); } }
/// <summary> /// Elaborates the given context recursively. /// </summary> public override void Elaborate() { SortedDictionary <string, MgaModel> parentsWithDupComponentGuids = new SortedDictionary <string, MgaModel>(); MgaFilter filter = this.Subject.Project.CreateFilter(); var allObjects = this.Subject.GetDescendantFCOs(filter); foreach (MgaFCO obj in allObjects) { if (obj.IsPrimaryDerived) { obj.DetachFromArcheType(); } } foreach (MgaFCO obj in allObjects) { if (this.Traceability.ContainsKey(obj.ID) == false) { // add to traceability this.Traceability.Add(obj.ID, obj.ID); } if (obj is MgaModel) { var model = obj as MgaModel; if (model.MetaBase.MetaRef == this.Factory.ComponentAssemblyMeta) { var managedGuid = model.StrAttrByName["ManagedGUID"]; if (string.IsNullOrEmpty(managedGuid) == false) { // copiedObj.StrAttrByName["ManagedGUID"] = managedGuid; // model.RegistryValue[RegistryNameInstanceGuidChain] = model.RegistryValue[RegistryNameInstanceGuidChain] + managedGuid; } } } else if (obj is MgaReference) { var reference = obj as MgaReference; if (reference.Referred == null) { if (reference.MetaBase.MetaRef == this.Factory.ComponentRefMeta) { this.Logger.WriteWarning(string.Format("Null {0} [{1}] was ignored and skipped.", reference.Name, reference.MetaBase.Name)); } continue; } var referred = reference.Referred; if (referred.MetaBase.MetaRef == this.Factory.ComponentMeta) { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; reference.GetParent(out parent, out type); var instanceGuid = reference.GetStrAttrByNameDisp("InstanceGUID"); if (string.IsNullOrWhiteSpace(instanceGuid)) { instanceGuid = new Guid(reference.GetGuidDisp()).ToString("D"); reference.SetStrAttrByNameDisp("InstanceGUID", instanceGuid); } if (parent is MgaModel) { instanceGuid = ((MgaModel)parent).RegistryValue[RegistryNameInstanceGuidChain] + instanceGuid; bool dupComponentGuid = !this.ComponentGUIDs.Add(instanceGuid); if (dupComponentGuid) { LogDebug("Duplicate ID " + instanceGuid, reference); parentsWithDupComponentGuids[parent.AbsPath] = parent as MgaModel; } } var copied = this.SwitchReferenceToModel(parent as MgaModel, reference, createInstance: true); // delete reference reference.DestroyObject(); } else if (referred.MetaBase.MetaRef == this.Factory.ComponentAssemblyMeta) { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; reference.GetParent(out parent, out type); MgaObject parent2 = parent; GME.MGA.Meta.objtype_enum type2; // worst case this will terminate at the root folder level while (parent2 != null && parent2 is MgaModel) { // FIXME: is this safe? should we compare IDs? if (parent2 == reference.Referred) { string message = string.Format("Circular dependency: {0} --> {1}", parent2.Name, reference.Referred.Name); throw new ElaboratorCircularReferenceException(message); } parent2.GetParent(out parent2, out type2); } if (this.ComponentAssemblyReferences.Any(x => x.ID == reference.Referred.ID)) { string message = string.Format("Circular dependency: {0} --> {1}", string.Join(" -> ", this.ComponentAssemblyReferences.Select(x => x.Name)), reference.Referred.Name); throw new ElaboratorCircularReferenceException(message); } var copied = this.SwitchReferenceToModel(parent as MgaModel, reference, false); // prevent circular dependency var innerElaborator = Elaborator.GetElaborator(copied, this.Logger, UnrollConnectors) as ComponentAssemblyElaborator; // use only one map innerElaborator.Traceability = this.Traceability; innerElaborator.ComponentGUIDs = this.ComponentGUIDs; innerElaborator.ComponentCopyMap = this.ComponentCopyMap; // hold only one queue foreach (var item in this.ComponentAssemblyReferences) { innerElaborator.ComponentAssemblyReferences.Enqueue(item); } innerElaborator.ComponentAssemblyReferences.Enqueue(reference.Referred); this.InnerElaborators.Add(innerElaborator); innerElaborator.Elaborate(); // delete reference reference.DestroyObject(); } } } // FIXME: it is possible for a parentWithDupComponentGuid to contain child CAs that need to be deduped also string lastPath = null; foreach (var ent in parentsWithDupComponentGuids) { if (lastPath != null) { if (ent.Key.StartsWith(lastPath)) { continue; } } lastPath = ent.Key; var model = ent.Value; allObjects = model.GetDescendantFCOs(filter); var parentGuid = model.ParentModel != null ? model.ParentModel.RegistryValue[RegistryNameInstanceGuidChain] : null; // parent model should contain the concatenated InstanceGUID string guidConcat = (parentGuid ?? "") + new Guid(model.GetGuidDisp()).ToString("D"); foreach (MgaFCO obj in allObjects) { if (obj.MetaBase.MetaRef == this.Factory.ComponentMeta) { obj.SetStrAttrByNameDisp("InstanceGUID", guidConcat + obj.GetStrAttrByNameDisp("InstanceGUID")); } if (obj.MetaBase.MetaRef == this.Factory.ComponentAssemblyMeta) { obj.RegistryValue[RegistryNameInstanceGuidChain] = guidConcat; } } } this.IsElaborated = true; }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE; //bool runNewImplementationOnly = true; //runNewImplementationOnly = false; //if (runNewImplementationOnly) //{ // this.NewMasterInterpreterImplementationFull(currentobj); // return; //} List <IMgaFCO> objectsToCheck = new List <IMgaFCO>(); List <IMgaFCO> objectsToGetConfigurations = new List <IMgaFCO>(); MgaGateway.PerformInTransaction(() => { if (currentobj == null) { var allObjects = project .RootFolder .ChildFolders .Cast <MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingContextChecker"))); objectsToGetConfigurations.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingGetConfigurations"))); } else { objectsToCheck.Add(currentobj); //objectsToGetConfigurations.Add(currentobj); } objectsToCheck.Sort((x, y) => { return(x.Meta.Name.CompareTo(y.Meta.Name) != 0 ? x.Meta.Name.CompareTo(y.Meta.Name) : x.AbsPath.CompareTo(y.AbsPath)); }); }); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; StringBuilder sbAssumptions = new StringBuilder(); sbAssumptions.Append("Implemented".PadToCenter(11)); sbAssumptions.Append("Valid".PadToCenter(11)); sbAssumptions.Append("Context".PadToCenter(30)); sbAssumptions.Append("Assumption"); sbAssumptions.AppendLine(); foreach (var subject in objectsToCheck) { var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); IEnumerable <CyPhyMasterInterpreter.Rules.ContextCheckerResult> contextCheckerResults = null; // check context var checkerSuccess = masterInterpreter.TryCheckContext(subject as MgaModel, out contextCheckerResults); List <CyPhyMasterInterpreter.Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList(); // sort results Passed, Failed, then alphabetically based on message. sortedResults.Sort((x, y) => { return(x.Success == y.Success ? x.Message.CompareTo(y.Message) : y.Success.CompareTo(x.Success)); }); // print out nicely in the GME console MgaGateway.PerformInTransaction(() => { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var successExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; sbAssumptions.AppendFormat("{0}{1}{2}{3}", (successExpected == checkerSuccess).ToString().PadToCenter(11), successExpected.ToString().PadToCenter(11), subject.Meta.Name.PadToCenter(30), subject.Name.ToSentenceCase()); sbAssumptions.AppendLine(); if (successExpected == checkerSuccess) { numSuccess++; //GMEConsole.Info.WriteLine("OK"); if (currentobj != null) { foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name); sb.Append(result.Message); tw.WriteLine(sb); } } } else { foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name); sb.Append(result.Message); tw.WriteLine(sb); } numFailures++; GMEConsole.Error.WriteLine("========= FAILED =========="); GMEConsole.Error.WriteLine("= {0}", subject.Name); GMEConsole.Error.WriteLine("= {0}", subject.AbsPath); GMEConsole.Error.WriteLine("==========================="); } }); if (currentobj != null) { CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; MgaGateway.PerformInTransaction(() => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel); }); GMEConsole.Info.WriteLine("AnalysisProcessor type: {0}", analysisModelProcessor.GetType().Name); GMEConsole.Info.WriteLine("Interpreters: {0}", string.Join(", ", analysisModelProcessor.Interpreters)); GMEConsole.Info.WriteLine("InterpretersToConfigure: {0}", string.Join(", ", analysisModelProcessor.InterpretersToConfiguration)); MgaFCO configuration = null; configuration = masterInterpreter.GetConfigurations(subject as MgaModel).Cast <MgaFCO>().FirstOrDefault(); var results = masterInterpreter.RunInTransaction(subject as MgaModel, configuration, keepTempModels: true); MgaGateway.PerformInTransaction(() => { foreach (var result in results) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i>{0}</i> {1} ", result.Context.Name, result.Configuration.Name); sb.Append(result.Message); tw.WriteLine(sb); } }); } } File.WriteAllText("master_interpreter_assumptions.txt", sbAssumptions.ToString()); foreach (var subject in objectsToGetConfigurations) { var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); // we are not checking the models again, these test models must be valid enough to get configurations from them var configurations = masterInterpreter.GetConfigurations(subject as MgaModel); // print out nicely in the GME console MgaGateway.PerformInTransaction(() => { GMEConsole.Info.WriteLine("{0} has {1} configurations.", subject.Name, configurations.Count); //GMEConsole.Info.WriteLine("- {0}", string.Join(", ", configurations.Cast<MgaFCO>().Select(x => x.Name))); }); //CyPhyMasterInterpreter.MasterInterpreterResult[] masterInterpreterResults = null; //using (var progressDialog = new CyPhyMasterInterpreter.ProgressDialog()) //{ // masterInterpreter.MultipleConfigurationProgress += progressDialog.MultipleConfigurationProgressHandler; // masterInterpreter.SingleConfigurationProgress += progressDialog.SingleConfigurationProgressHandler; // progressDialog.ShowWithDisabledMainWindow(); // masterInterpreterResults = masterInterpreter.RunInTransaction(subject as IMgaModel, configurations); //} } GMEConsole.Info.WriteLine("ContextChecks: {0}", numContexts); GMEConsole.Info.WriteLine("Successful : {0}", numSuccess); GMEConsole.Info.WriteLine("Failures : {0}", numFailures); if (numContexts == numSuccess) { GMEConsole.Info.WriteLine("ALL GREEN :-)"); } else { GMEConsole.Error.WriteLine("You need to work more on the code..."); } GMEConsole.Info.WriteLine( "Duration: {0}.", sw.Elapsed.ToString("c")); } finally { System.Windows.Forms.Application.DoEvents(); if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
private Type GetBaseType(MgaObject subject, bool iface = true) { Type result = null; // TODO: use appropriate base class ... switch (subject.MetaBase.Name) { case "RootFolder": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.RootFolder); } else { result = typeof(ISIS.GME.Common.Classes.RootFolder); } break; case "Folder": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.Folder); } else { result = typeof(ISIS.GME.Common.Classes.Folder); } break; case "Model": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.Model); } else { result = typeof(ISIS.GME.Common.Classes.Model); } break; case "Connection": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.Connection); } else { result = typeof(ISIS.GME.Common.Classes.Connection); } break; case "Atom": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.Atom); } else { result = typeof(ISIS.GME.Common.Classes.Atom); } break; case "FCO": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.FCO); } else { result = typeof(ISIS.GME.Common.Classes.FCO); } break; case "Reference": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.Reference); } else { result = typeof(ISIS.GME.Common.Classes.Reference); } break; case "Set": if (iface) { result = typeof(ISIS.GME.Common.Interfaces.Set); } else { result = typeof(ISIS.GME.Common.Classes.Set); } break; default: if (iface) { result = typeof(ISIS.GME.Common.Interfaces.Base); } else { result = typeof(ISIS.GME.Common.Classes.Base); } break; } return(result); }
public void ObjectEvent(MgaObject obj, uint EventMask, object v) { }
/// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject">the object the event(s) happened to</param> /// <param name="eventMask">objectevent_enum values ORed together</param> /// <param name="param">extra information provided for cetertain event types</param> public void ObjectEvent(MgaObject subject, uint eventMask, object param) { if (!componentEnabled) { return; } if (!handleEvents) { return; } uint uOBJEVENT_CREATED = 0; unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; } bool objectCreatedAndNotLibObject = (eventMask & uOBJEVENT_CREATED) != 0 && (eventMask & (uint)objectevent_enum.OBJEVENT_DESTROYED) == 0 && subject.IsLibObject == false; if (xmeImportInProgress) { if (objectCreatedAndNotLibObject && subject.MetaBase.MetaRef == componentAssemblyMetaRef && componentAssemblyPathMetaRef != 0) { string path = ((IMgaFCO)subject).StrAttrByName["Path"]; if (path == "") { ((IMgaFCO)subject).StrAttrByName["Path"] = GetRandomComponentAssemblyDir(); } } return; } // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask // If the event is OBJEVENT_DESTROYED, most operations on subject will fail // Safe operations: getting Project, ObjType, ID, MetaRole, Meta, MetaBase, Name, AbsPath // Operations that will fail: all others, including attribute access and graph navigation // Try handling OBJEVENT_PRE_DESTROYED if these operations are necessary // Be careful not to modify Library objects (check subject.IsLibObject) // MessageBox.Show(eventMask.ToString()); // GMEConsole.Out.WriteLine(subject.Name); // attribute was changed and object was neither created nor destroyed bool attributeChanged = (eventMask & (uint)objectevent_enum.OBJEVENT_ATTR) != 0 && (eventMask & uOBJEVENT_CREATED) == 0 && (eventMask & (uint)objectevent_enum.OBJEVENT_DESTROYED) == 0; if (objectCreatedAndNotLibObject) { MgaObject parent; GME.MGA.Meta.objtype_enum objType; subject.GetParent(out parent, out objType); // Object was created if (subject.MetaBase.Name == "Component") { // Check that parent is a Components folder if (objType == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER && parent.MetaBase.Name == "Components") { Process(CyPhyClasses.Component.Cast(subject)); } } else if (subject.MetaBase.Name == "ComponentAssembly") { Process(CyPhyClasses.ComponentAssembly.Cast(subject)); } } else if (attributeChanged && subject.IsLibObject == false) { MgaObject parent; GME.MGA.Meta.objtype_enum objType; subject.GetParent(out parent, out objType); if (subject.MetaBase.Name == "Component") { string oldPath = null; // Check that parent is a Components folder if (objType == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER && parent.MetaBase.Name == "Components") { if (param != null) { var parameters = ((object[])param).ToList(); int pathAttr = parameters.IndexOf("ATTR:Path"); if (pathAttr != -1) { oldPath = (string)parameters[pathAttr + 1]; RenameComponentDirectory(CyPhyClasses.Component.Cast(subject), oldPath); } } } } } }
public void PCBMfg_WorkflowTests() { var pathTestbench = "/@TestBenches|kind=Testing|relpos=0/PCB_Manufacturing|kind=TestBench|relpos=0"; String testName = System.Reflection.MethodBase.GetCurrentMethod().Name; String pathOutput = Path.Combine(project.GetRootDirectoryPath(), "output", testName); string configAbsPath = "/@ComponentAssemblies|kind=ComponentAssemblies|relpos=0/@AstableMultivibrator|kind=ComponentAssembly|relpos=0"; // CyPhy2PCBMfg.CyPhy2PCBMfgInterpreter interpreter = null; MgaObject objTestbench = null; MgaFCO configObj = null; project.PerformInTransaction(delegate { objTestbench = project.get_ObjectByPath(pathTestbench); Assert.NotNull(objTestbench); configObj = project.get_ObjectByPath(configAbsPath) as MgaFCO; Assert.NotNull(configObj); }); bool postToJobManager = false; bool keepTempModels = false; bool result = false; string outputDirectory = ""; // Use the master Interpreter to create a JSON file in the results folder based on the Testbench's Workflow using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { masterInterpreter.Logger.GMEConsoleLoggingLevel = CyPhyGUIs.SmartLogger.MessageType_enum.Debug; var miResults = masterInterpreter.RunInTransactionOnOneConfig(objTestbench as MgaModel, configObj, postToJobManager, keepTempModels); outputDirectory = miResults[0].OutputDirectory; result = miResults.Any(x => x.Success == false) ? false : true; } Assert.True(result); string manifestFileName = "testbench_manifest.json"; var pathToManifestFile = Path.Combine(outputDirectory, manifestFileName); Assert.True(File.Exists(pathToManifestFile)); var fileContents = File.ReadAllText(pathToManifestFile); Assert.False(String.IsNullOrWhiteSpace(fileContents)); // Use a process to start a Python script to execute the JSON file, similar to the Job Manager, but with synchronous execution. // See LocalPool.cs around lines 165-186, from the CyPhyMl solution, TestBenchExecutionFramework folder, JobManager project. using (var proc0 = new System.Diagnostics.Process()) { proc0.StartInfo.FileName = META.VersionInfo.PythonVEnvExe; proc0.StartInfo.Arguments = "-m testbenchexecutor testbench_manifest.json"; proc0.StartInfo.UseShellExecute = false; proc0.StartInfo.CreateNoWindow = true; proc0.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized; proc0.StartInfo.WorkingDirectory = Path.Combine(outputDirectory); proc0.StartInfo.RedirectStandardError = true; proc0.StartInfo.RedirectStandardOutput = true; proc0.Start(); StringBuilder output = new StringBuilder(); proc0.ErrorDataReceived += (o, dataArgs) => { if (dataArgs.Data != null) { try { output.Append(dataArgs.Data); } catch (ObjectDisposedException) { } } }; proc0.OutputDataReceived += (o, dataArgs) => { if (dataArgs.Data != null) { try { output.Append(dataArgs.Data); } catch (ObjectDisposedException) { } } }; proc0.BeginOutputReadLine(); proc0.BeginErrorReadLine(); bool isFinished = proc0.WaitForExit(60000); // Wait up to a minute for the workflow tests to finish. Assert.True(isFinished, String.Format("python {0} in {1} timed out", proc0.StartInfo.Arguments, outputDirectory)); proc0.Refresh(); if (0 != proc0.ExitCode) { Console.WriteLine("Process exit code: {0}", proc0.ExitCode); } Assert.True(0 == proc0.ExitCode, "Testbench run failed: " + output.ToString() + " " + outputDirectory + " " + File.ReadAllText(Path.Combine(outputDirectory, "testbench_manifest.json"))); // Check that the job finished OK. } // Check that files were created in the output path. string[] createdFileNames = { "schema.boardoutline.ger", "schema.boardoutline.gpi", "schema.bottomlayer.ger", "schema.bottomlayer.gpi", "schema.bottomsilkscreen.ger", "schema.bottomsilkscreen.gpi", "schema.bottomsoldermask.ger", "schema.bottomsoldermask.gpi", "schema.drills.dri", "schema.drills.xln", "schema.tcream.ger", "schema.tcream.gpi", "schema.toplayer.ger", "schema.toplayer.gpi", "schema.topsoldermask.ger", "schema.topsoldermask.gpi", "schema_centroids.csv", "schema.XYRS", // MOT-743 "assemblyBom.csv" }; foreach (string filename in createdFileNames) { var pathOutputFile = Path.Combine(outputDirectory, filename); Assert.True(File.Exists(pathOutputFile)); var fileText = File.ReadAllText(pathOutputFile); Assert.False(String.IsNullOrWhiteSpace(fileText)); } }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List <IMgaFCO> objectsToCheck = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast <MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck = allObjects.Where(x => x.AbsPath.Contains("TestingContextChecker") && x.Name.Contains("ReadOnly") == false).ToList(); objectsToCheck.Sort((x, y) => { return(x.Meta.Name.CompareTo(y.Meta.Name) != 0 ? x.Meta.Name.CompareTo(y.Meta.Name) : x.AbsPath.CompareTo(y.AbsPath)); }); } finally { project.AbortTransaction(); } Assert.True(objectsToCheck != null, "There are no object in the project that has to be checked."); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToCheck) { // single test using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { CyPhyMasterInterpreter.Rules.ContextCheckerResult[] contextCheckerResults = null; // check context var checkerSuccess = masterInterpreter.TryCheckContext(subject as MgaModel, out contextCheckerResults); List <CyPhyMasterInterpreter.Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList(); // sort results Passed, Failed, then alphabetically based on message. sortedResults.Sort((x, y) => { return(x.Success == y.Success ? x.Message.CompareTo(y.Message) : y.Success.CompareTo(x.Success)); }); project.BeginTransactionInNewTerr(); try { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var successExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; if (successExpected == checkerSuccess) { numSuccess++; //GMEConsole.Info.WriteLine("OK"); } else { success = false; foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[Passed]"); tw = Console.Out; } else { sb.Append("[Failed]"); tw = Console.Error; } sb.AppendFormat(" {0} - {1} ", result.Subject.Name, result.Subject.AbsPath); sb.Append(result.Message); tw.WriteLine(sb); } numFailures++; Console.Error.WriteLine("========= FAILED =========="); Console.Error.WriteLine("= {0}", subject.Name); Console.Error.WriteLine("= {0}", subject.AbsPath); Console.Error.WriteLine("==========================="); } } finally { project.AbortTransaction(); } } } if (success) { Console.Out.WriteLine("[OK] Checked contexts: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Checked contexts: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one context was failed to check against the expected results."); } finally { project.Close(true); } }
/// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject"> /// the object the event(s) happened to /// </param> /// <param name="eventMask"> /// objectevent_enum values ORed together /// </param> /// <param name="param"> /// extra information provided for cetertain event types /// </param> public void ObjectEvent( MgaObject subject, uint eventMask, object param) { if (!componentEnabled) { return; } else if (isXMLImportInProgress) { return; } //else if (isProjectInTransation) //{ // return; //} if (subject.HasReadOnlyAccess() || subject.IsLibObject) { return; } uint uOBJEVENT_CREATED = 0; uint uOBJEVENT_COPIED = 0; unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; } unchecked { uOBJEVENT_COPIED = (uint)objectevent_enum.OBJEVENT_COPIED; } if ((eventMask & uOBJEVENT_COPIED) != 0) { isCopied = true; } else if ((eventMask & uOBJEVENT_CREATED) != 0 && subject.Status == 0) // check Status, since object can be created and deleted in same tx { if (isCopied) { // handle copy event isCopied = false; } else { //subject.Project.RootMeta.RootFolder.DefinedFCOByName["Task", //MgaMetaBase task; //if (task.MetaRef == subject.MetaBase.MetaRef) { } // handle new object event if (subject.MetaBase.Name == "Task" || subject.MetaBase.Name == "WorkflowRef") { Type t = Type.GetTypeFromProgID(DecoratorName); if (t != null) { (subject as MgaFCO).RegistryValue["decorator"] = DecoratorName; } } bool isBasicTask = (subject.MetaBase.Name == "Task"); if (subject.MetaBase.Name == "Task" || subject.MetaBase.Name == "ExecutionTask") { using (InterpreterSelectionForm form = new InterpreterSelectionForm()) { form.addon = this; form.Init(); IEnumerable<MgaAtom> taskChildren = subject.ExGetParent(). ChildObjects. OfType<MgaAtom>(). Where(x => x.ExDstFcos().Count() == 0). Where(x => x.ID != subject.ID); form.lbTasks.Items.Clear(); foreach (var currTask in taskChildren) { var atomWrapper = new MgaAtomWrapper(currTask); form.lbTasks.Items.Add(new MgaAtomWrapper(currTask)); form.lbTasks.SelectedItem = atomWrapper; } if (form.lbTasks.Items.Count > 0) { form.lbTasks.SetSelected(0, true); } if (!isBasicTask) // remove interpreter selection and reset positions { form.lbInterpreters.Items.Clear(); form.lbInterpreters.Visible = false; form.lblSelectInterpreter.Visible = false; form.chbAutoConnect.Location = form.label1.Location; form.label1.Location = form.lblSelectInterpreter.Location; form.lbTasks.Location = form.lbInterpreters.Location; } DialogResult dgr = form.ShowDialog(); if (dgr == DialogResult.OK) { if (isBasicTask) { ComComponent c = form.lbInterpreters.SelectedItem as ComComponent; try { if (c != null && c.isValid) { (subject as MgaFCO).StrAttrByName["COMName"] = c.ProgId; } } catch { MessageBox.Show("Cannot save interpreter settings. 'COMName' is not a parameter of 'Task'."); } } //Flow if (form.chbAutoConnect.Checked && (form.lbTasks.SelectedItem != null)) { MgaAtomWrapper selectedTask = form.lbTasks.SelectedItem as MgaAtomWrapper; MgaAtom lastInWorkflow = null; if (selectedTask != null) { lastInWorkflow = selectedTask.Atom; } if (lastInWorkflow != null) { MgaMetaRole role = ((subject.ExGetParent() as MgaModel). Meta as MgaMetaModel).RoleByName["Flow"]; (subject.ExGetParent() as MgaModel).CreateSimplerConnDisp( role, lastInWorkflow as MgaFCO, subject as MgaFCO); } } } } } } } // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask // MessageBox.Show(eventMask.ToString()); }
public IEnumerable <MgaFCO> GetChildren(MgaObject subject) { Contract.Requires((subject is MgaReference) == false); List <MgaFCO> children = new List <MgaFCO>(); if (subject.MetaBase.Name == "RootFolder") { // get root folder objects MgaFilter f = subject.Project.CreateFilter(); foreach (MgaFCO fco in subject.Project.AllFCOs(f)) { foreach (MgaAttribute attr in fco.Attributes) { if (attr.Meta.Name == "InRootFolder") { if (fco.BoolAttrByName["InRootFolder"] == true) { children.Add(fco); } } } } } else { List <MgaFCO> baseClasses = GetBaseClasses(subject as MgaFCO).ToList(); baseClasses.Add(subject as MgaFCO); // folder or model foreach (MgaFCO baseFco in baseClasses) { foreach (MgaFCO fco in baseFco.ReferencedBy) { foreach (MgaConnPoint cp in fco.PartOfConns) { MgaSimpleConnection conn = cp.Owner as MgaSimpleConnection; // compare the dst with the proxy if (conn.Dst == fco) { if (conn.Meta.Name == "Containment" || conn.Meta.Name == "FolderContainment") { if (conn.Src is MgaReference) { children.Add((conn.Src as MgaReference).Referred); } else { children.Add(conn.Src); } } } } } foreach (MgaConnPoint cp in baseFco.PartOfConns) { MgaSimpleConnection conn = cp.Owner as MgaSimpleConnection; if (conn.Meta.Name == "Containment" || conn.Meta.Name == "FolderContainment") { if (conn.Dst == baseFco) { if (conn.Src is MgaReference) { children.Add((conn.Src as MgaReference).Referred); } else { children.Add(conn.Src); } } } } } } return(children.Distinct()); }
public static bool IsComponentRef(MgaObject obj) { return obj.MetaBase.Name == "ComponentRef"; }
/// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject">the object the event(s) happened to</param> /// <param name="eventMask">objectevent_enum values ORed together</param> /// <param name="param">extra information provided for cetertain event types</param> public void ObjectEvent(MgaObject subject, uint eventMask, object param) { if (!componentEnabled) { return; } if (subject.HasReadOnlyAccess()) { return; } if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(subject.Project); } // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask uint uOBJEVENT_ATTR = 0; uint uOBJEVENT_CREATED = 0; uint uOBJEVENT_NEWCHILD = 0; uint uOBJEVENT_LOSTCHILD = 0; uint uOBJEVENT_OPENMODEL = 0; unchecked { uOBJEVENT_ATTR = (uint)objectevent_enum.OBJEVENT_ATTR; } unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; } unchecked { uOBJEVENT_NEWCHILD = (uint)objectevent_enum.OBJEVENT_NEWCHILD; } unchecked { uOBJEVENT_LOSTCHILD = (uint)objectevent_enum.OBJEVENT_LOSTCHILD; } unchecked { uOBJEVENT_OPENMODEL = (uint)objectevent_enum.OBJEVENT_OPENMODEL; } if ((eventMask & uOBJEVENT_CREATED) != 0) { if (subject.IsLibObject || subject.IsWritable == false) return; if (subject.MetaBase.Name == "TestBenchRef") { // set the port label lenght 0 // FIXME: why not just change it in the meta? (subject as MgaFCO).RegistryValue["portLabelLength"] = "0"; if (subject as MgaReference != null) { UpdateColor((subject as MgaReference).Referred); } } else if (subject.MetaBase.Name == "Optimizer") { (subject as MgaFCO).RegistryValue["portLabelLength"] = "0"; UpdateColor(subject as MgaFCO); } else if (subject.MetaBase.Name == "VariableSweep") { (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow"; (subject as MgaFCO).RegistryValue["color"] = "0xff80c0"; } else if (subject.MetaBase.Name == "ObjectiveMapping") { (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow"; (subject as MgaFCO).RegistryValue["color"] = "0x7cadde"; } } else if ((eventMask & uOBJEVENT_ATTR) != 0) { this.DisplayPCCIterations(subject, true); if (subject.MetaBase.Name == "ValueFlow") { // set the src custom formula's name to the specified name // in the ValueFlow attribute field MgaConnection ValueFlow = subject as MgaConnection; foreach (MgaConnPoint cp in ValueFlow.ConnPoints) { if (cp.ConnRole == "src") { if (cp.Target.Meta.Name == "CustomFormula") { foreach (MgaAttribute attr in ValueFlow.Attributes) { if (attr.Meta.Name == "FormulaVariableName") { if (string.IsNullOrEmpty(attr.StringValue) == false) { cp.Target.Name = attr.StringValue; break; } } } } break; } } } else if (subject.MetaBase.Name == "TestBench") { // Excel import helper MgaModel testBench = subject as MgaModel; // call color helper UpdateColor(testBench as MgaFCO); } } else if ((eventMask & uOBJEVENT_NEWCHILD) != 0 || (eventMask & uOBJEVENT_LOSTCHILD) != 0) { this.DisplayPCCIterations(subject, false); } else if ((eventMask & uOBJEVENT_OPENMODEL) != 0) { if (subject.MetaBase.Name == "ParametricExploration") { var pet = subject as MgaModel; foreach (MgaModel PCCDriver in pet.GetChildrenOfKind("PCCDriver")) { var upMethod = PCCDriver.StrAttrByName["PCC_UP_Methods"]; if (upMethod == "UP_MPP" || upMethod == "UP_PCE") { GMEConsole.Out.WriteLine("{1}The output of the selected method ({0}) is not compatible with the project analyzer Dashboard.", upMethod, WARNING_BADGE); if (upMethod == "UP_PCE") { GMEConsole.Out.WriteLine("{0}Trying to display such data might require a refresh in order to view other data again.", WARNING_BADGE); } } } } } //MessageBox.Show(eventMask.ToString()); }
public static bool IsValidComponentRef(MgaObject obj) { return obj.MetaBase.Name == "ComponentRef" && ((MgaReference)obj).Referred != null && ((MgaReference)obj).Referred.Status == (int)objectstatus_enum.OBJECT_EXISTS && ((MgaReference)obj).Referred.Meta.Name == "Component"; }
/// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject">the object the event(s) happened to</param> /// <param name="eventMask">objectevent_enum values ORed together</param> /// <param name="param">extra information provided for cetertain event types</param> public void ObjectEvent(MgaObject subject, uint eventMask, object param) { if (!componentEnabled) { return; } if (subject.HasReadOnlyAccess()) { return; } if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(subject.Project); } // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask uint uOBJEVENT_ATTR = 0; uint uOBJEVENT_CREATED = 0; uint uOBJEVENT_NEWCHILD = 0; uint uOBJEVENT_LOSTCHILD = 0; uint uOBJEVENT_OPENMODEL = 0; unchecked { uOBJEVENT_ATTR = (uint)objectevent_enum.OBJEVENT_ATTR; } unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; } unchecked { uOBJEVENT_NEWCHILD = (uint)objectevent_enum.OBJEVENT_NEWCHILD; } unchecked { uOBJEVENT_LOSTCHILD = (uint)objectevent_enum.OBJEVENT_LOSTCHILD; } unchecked { uOBJEVENT_OPENMODEL = (uint)objectevent_enum.OBJEVENT_OPENMODEL; } if ((eventMask & uOBJEVENT_CREATED) != 0) { if (subject.IsLibObject || subject.IsWritable == false) { return; } if (subject.MetaBase.Name == "TestBenchRef") { if (subject as MgaReference != null) { UpdateColor((subject as MgaReference).Referred); } } else if (subject.MetaBase.Name == "Optimizer") { (subject as MgaFCO).RegistryValue["portLabelLength"] = "0"; } else if (subject.MetaBase.Name == "VariableSweep") { (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow"; (subject as MgaFCO).RegistryValue["color"] = "0xff80c0"; } else if (subject.MetaBase.Name == "ObjectiveMapping") { (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow"; (subject as MgaFCO).RegistryValue["color"] = "0x7cadde"; } } else if ((eventMask & uOBJEVENT_ATTR) != 0) { this.DisplayPCCIterations(subject, true); if (subject.MetaBase.Name == "ValueFlow") { // set the src custom formula's name to the specified name // in the ValueFlow attribute field MgaSimpleConnection ValueFlow = subject as MgaSimpleConnection; var src = ValueFlow.Src; if (src.Meta.Name == "CustomFormula") { foreach (MgaAttribute attr in ValueFlow.Attributes) { if (attr.Meta.Name == "FormulaVariableName") { if (string.IsNullOrEmpty(attr.StringValue) == false) { src.Name = attr.StringValue; break; } } } } } else if (subject.MetaBase.Name == "TestBench") { // Excel import helper MgaModel testBench = subject as MgaModel; // call color helper UpdateColor(testBench as MgaFCO); } } else if ((eventMask & uOBJEVENT_NEWCHILD) != 0 || (eventMask & uOBJEVENT_LOSTCHILD) != 0) { this.DisplayPCCIterations(subject, false); } else if ((eventMask & uOBJEVENT_OPENMODEL) != 0) { } //MessageBox.Show(eventMask.ToString()); }
private void DisplayPCCIterations(MgaObject subject, bool attributeChanged) { List<string> kinds = new List<string>() { "PCCDriver", "PCCParameterBeta", "PCCParameterUniform", "PCCParameterLNormal", "PCCParameterNormal" }; if (kinds.Contains(subject.MetaBase.Name) == false) { return; } MgaModel PCCDriver = null; if (attributeChanged && subject.MetaBase.Name == "PCCDriver") { // TODO: Compute and PCCDriver = subject as MgaModel; } else if (attributeChanged == false && subject.MetaBase.Name == "PCCDriver") { // Compute and prin //GME.MGA.Meta.objtype_enum type; //MgaObject parent; //(subject as MgaFCO).GetParent(out parent, out type); PCCDriver = subject as MgaModel; } else { return; } //Compute and print PCCDriver var nbrOfParameters = PCCDriver.ChildFCOs.Cast<MgaFCO>().Where(x => kinds.Contains(x.Meta.Name)).Count(); var saMethod = PCCDriver.StrAttrByName["PCC_SA_Methods"]; var upMethod = PCCDriver.StrAttrByName["PCC_UP_Methods"]; if (attributeChanged && (upMethod == "UP_MPP" || upMethod == "UP_PCE")) { GMEConsole.Out.WriteLine("{1}The output of the selected method ({0}) is not compatible with the project analyzer Dashboard.", upMethod, WARNING_BADGE); if (upMethod == "UP_PCE") { GMEConsole.Out.WriteLine("{0}Trying to display such data might require a refresh in order to view other data again.", WARNING_BADGE); } } GMEConsole.Out.WriteLine("{2}Iterations : UP : {0}, SA : {1}", this.GetNumberOfIterations(upMethod, nbrOfParameters), this.GetNumberOfIterations(saMethod, nbrOfParameters), INFO_BADGE); }
/// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject">the object the event(s) happened to</param> /// <param name="eventMask">objectevent_enum values ORed together</param> /// <param name="param">extra information provided for cetertain event types</param> public void ObjectEvent(MgaObject subject, uint eventMask, object param) { // 6-28-2013: Harmon added an enable property that gets set from CyPhyMLSync. That code is currently commented out in CyPhyMLSync. if (!enabled || !componentEnabled || !handleEvents) { return; } //if (!componentEnabled || !handleEvents) { // return; //} if (GMEConsole == null) { GMEConsole = GME.CSharp.GMEConsole.CreateFromProject(subject.Project); } uint uOBJEVENT_ATTR = 0; uint uOBJEVENT_CONNECTED = 0; uint uOBJEVENT_CREATED = 0; uint uOBJEVENT_PROPERTIES = 0; uint uOBJEVENT_OPENMODEL = 0; uint uOBJEVENT_CLOSEMODEL = 0; uint uOBJEVENT_NEWCHILD = 0; uint uOBJEVENT_PRE_STATUS = 0; uint uOBJEVENT_PRE_DESTROYED = 0; unchecked { uOBJEVENT_ATTR = (uint)objectevent_enum.OBJEVENT_ATTR; } unchecked { uOBJEVENT_CONNECTED = (uint)objectevent_enum.OBJEVENT_CONNECTED; } unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; } unchecked { uOBJEVENT_PROPERTIES = (uint)objectevent_enum.OBJEVENT_PROPERTIES; } unchecked { uOBJEVENT_OPENMODEL = (uint)objectevent_enum.OBJEVENT_OPENMODEL; } unchecked { uOBJEVENT_CLOSEMODEL = (uint)objectevent_enum.OBJEVENT_CLOSEMODEL; } unchecked { uOBJEVENT_NEWCHILD = (uint)objectevent_enum.OBJEVENT_NEWCHILD; } unchecked { uOBJEVENT_PRE_STATUS = (uint)objectevent_enum.OBJEVENT_PRE_STATUS; } unchecked { uOBJEVENT_PRE_DESTROYED = (uint)objectevent_enum.OBJEVENT_PRE_DESTROYED; } uint uOBJEVENT_REFERENCED = unchecked((uint)objectevent_enum.OBJEVENT_REFERENCED); uint uOBJEVENT_DESTROYED = unchecked((uint)objectevent_enum.OBJEVENT_DESTROYED); uint uOBJEVENT_RELATION = unchecked((uint)objectevent_enum.OBJEVENT_RELATION); // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask // If the event is OBJEVENT_DESTROYED, most operations on subject will fail // Safe operations: getting Project, ObjType, ID, MetaRole, Meta, MetaBase, Name, AbsPath // Operations that will fail: all others, including attribute access and graph navigation // Try handling OBJEVENT_PRE_DESTROYED if these operations are necessary // Be careful not to modify Library objects (check subject.IsLibObject) // MessageBox.Show(eventMask.ToString()); // GMEConsole.Out.WriteLine(subject.Name); #if DEBUG GMEConsole.Info.WriteLine("EventID: " + eventMask.ToString()); #endif if ((eventMask & uOBJEVENT_PRE_STATUS) != 0) { if (param != null) { string paramString = param as string; string[] paramData = paramString.Split(','); if (paramData[0] == "ATTR" && paramData[2] == "Cleared") { string attributeName = paramData[1]; MgaFCO mgaFCO = subject as MgaFCO; MgaMetaAttribute mgaMetaAttribute = mgaFCO.Meta.get_AttributeByName(attributeName); GMEConsole.Error.WriteLine("Attribute \"" + attributeName + "\" cleared, default value = \"" + mgaMetaAttribute.get_DefaultValue().ToString() + "\""); } } } if (AssemblyID != null && (((eventMask & uOBJEVENT_RELATION) != 0 && (eventMask & uOBJEVENT_DESTROYED) == 0 && (eventMask & uOBJEVENT_CREATED) == 0) || (eventMask & uOBJEVENT_PRE_DESTROYED) != 0 && (eventMask & uOBJEVENT_CREATED) == 0) && subject.Status == (int)objectstatus_enum.OBJECT_EXISTS) { if (CyphyMetaLinkUtils.IsValidComponentRef(subject)) { CyPhyML.ComponentRef componentRef = CyPhyMLClasses.ComponentRef.Cast(subject); var parent = componentRef.ParentContainer; if (parent.Kind == typeof(CyPhyML.ComponentAssembly).Name) { foreach (CyPhyML.ComponentAssembly assembly in CyphyMetaLinkUtils.GetContainingAssemblies(CyPhyMLClasses.ComponentAssembly.Cast(parent.Impl))) { if (assembly.Guid == Guid.Parse(AssemblyID)) { RestartAssemblySyncAtEndOfTransaction(assembly); } } } } else if (subject.MetaBase.Name == "ConnectorComposition") { CyPhyML.ConnectorComposition connector = CyPhyMLClasses.ConnectorComposition.Cast(subject); var parent = connector.ParentContainer; if (parent.Kind == typeof(CyPhyML.ComponentAssembly).Name) { foreach (CyPhyML.ComponentAssembly assembly in CyphyMetaLinkUtils.GetContainingAssemblies(CyPhyMLClasses.ComponentAssembly.Cast(parent.Impl))) { if (assembly.Guid == Guid.Parse(AssemblyID)) { RestartAssemblySyncAtEndOfTransaction(assembly); } } } } // If the user adds or deletes an FCO contained in a Component that is contained in the synced design, restart the sync (META-1811) if (subject is MgaFCO) { CyPhyML.Component component = null; MgaModel model = (subject as MgaFCO).ParentModel; while (model != null) { if (model.Meta.Name == "Component") { component = CyPhyMLClasses.Component.Cast(model); break; } model = model.ParentModel; } if (component != null) { foreach (CyPhyML.ComponentAssembly asm in CyphyMetaLinkUtils.GetContainingAssemblies(component)) { if (asm.Guid == Guid.Parse(AssemblyID)) { var syncedAssembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(subject.Project, AssemblyID); RestartAssemblySyncAtEndOfTransaction(syncedAssembly); } } } } } if ((eventMask & uOBJEVENT_PROPERTIES) != 0 && param != null && (eventMask & uOBJEVENT_DESTROYED) == 0) { // Change of a parameter on componentref if (CyphyMetaLinkUtils.IsComponentRef(subject)) { if (!syncedComponents.ContainsKey(CyPhyMLClasses.Property.Cast(subject).ParentContainer.Guid.ToString())) return; string paramName = null; object[] paramData = param as object[]; string p = paramData[0].ToString(); if (p.StartsWith("PROPERTIES:")) { try { paramName = p.Substring(p.IndexOf(':') + 1); } catch (Exception) { // Fail silently } if (paramName != null) { string paramValue = paramData[1].ToString(); if (paramName == "Name") { MetaLinkProtobuf.Edit editMsg = UpdateComponentNameProtoBufMsg(CyPhyMLClasses.ComponentRef.Cast(subject), paramValue); bridgeClient.SendToMetaLinkBridge(editMsg); } } } } } if ((eventMask & uOBJEVENT_ATTR) != 0 && param != null && (eventMask & uOBJEVENT_DESTROYED) == 0) { // GMEConsole.Info.WriteLine("CyPhyMLPropagate OBJEVENT_ATTR"); object[] paramData = param as object[]; string attributeName = ""; //((string)paramData[0]).Substring(((string)paramData[0]).IndexOf(':') + 1); foreach (var item in paramData) { string s = item.ToString(); if (!string.IsNullOrEmpty(s)) { if (s.Contains("ATTR:")) { string tmp = s.Substring(s.IndexOf(':') + 1); if (tmp == "Value" || tmp == "InstanceGUID") attributeName = tmp; } } } if (attributeName == "Value") { MgaFCO mgaFCO = subject as MgaFCO; MgaMetaAttribute mgaMetaAttribute = mgaFCO.Meta.get_AttributeByName(attributeName); #if DEBUG GMEConsole.Error.WriteLine("Attribute change detected, name = \"" + attributeName + "\", old value = \"" + paramData[1].ToString() + "\", new value = \"" + mgaFCO.get_Attribute(mgaMetaAttribute).Value.ToString() + "\""); #endif // A property has been modified string kind = subject.MetaBase.Name; if (kind == "Property" || kind == "Parameter" || kind == "Metric") { // Does this parameter belong to the Meta-Linked assembly? if (kind == "Property") { if (!syncedComponents.ContainsKey(CyPhyMLClasses.Property.Cast(subject).ParentContainer.Guid.ToString())) return; } else if (kind == "Parameter") { if (!syncedComponents.ContainsKey(CyPhyMLClasses.Parameter.Cast(subject).ParentContainer.Guid.ToString())) return; } else if (kind == "Metric") { if (!syncedComponents.ContainsKey(CyPhyMLClasses.Metric.Cast(subject).ParentContainer.Guid.ToString())) return; } // If any parameter changes, the whole assembly needs to be re-built // The elaborator can't trace back the original references // So it can't be used to change the Creo model partially // This can be changed when the elaborator is replaced by some more fine-tailored solution CyPhyML.ComponentAssembly assembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, AssemblyID); RestartAssemblySyncAtEndOfTransaction(assembly); /*CyPhyML.ValueFlowTarget vft = CyPhyMLClasses.ValueFlowTarget.Cast(subject); if (vft != null) { ValueFlowTraverse traverser = new ValueFlowTraverse(); traverser.TraverseValueFlow(vft); if (traverser.Found.Count > 0) { handleEvents = false; MgaModel model = (subject as MgaFCO).ParentModel; RunFormulaEvaluator(CyPhyMLClasses.ValueFlowTarget.Cast(subject), model as MgaFCO, subject.Project); handleEvents = true; foreach (var item in traverser.Found) { ModifyCADParameter(item); } } }*/ } } else if (attributeName == "InstanceGUID") { MgaFCO mgaFCO = subject as MgaFCO; if (CyphyMetaLinkUtils.IsValidComponentRef(subject)) { AddComponent(subject); } } } // end if (eventMask) if ((eventMask & uOBJEVENT_PROPERTIES) != 0) { if (CyphyMetaLinkUtils.IsComponent(subject)) { if (param != null) { object[] paramData = param as object[]; string parameterName = ((string)paramData[0]).Substring(((string)paramData[0]).IndexOf(':') + 1); if (parameterName != "Name") return; GMEConsole.Error.WriteLine("Name change detected, old name = \"" + ((string)paramData[1]) + "\", new name = \"" + subject.Name + "\""); CyPhyML.Component cyPhyMLComponent = CyPhyMLClasses.Component.Cast(subject); /* Message message = new Message(); message.cadComponent = new CADComponentType(); message.cadComponent.ComponentID = cyPhyMLComponent.Attributes.InstanceGUID; message.cadComponent.Name = cyPhyMLComponent.Name; message.type = Message.MessageType.UPDATE; _socketQueue.enQueue(message); */ } } } if ((eventMask & uOBJEVENT_OPENMODEL) != 0) { //GMEConsole.Info.WriteLine("OBJEVENT_OPENMODEL"); } // Component or Constraint has been created if ((eventMask & uOBJEVENT_CREATED) != 0 && (eventMask & uOBJEVENT_DESTROYED) == 0 && (subject is MgaFCO) && ((MgaFCO)subject).ParentModel != null) { #if DEBUG GMEConsole.Info.WriteLine("OBJEVENT_CREATED"); #endif /*if (CyphyMetaLinkUtils.IsComponentRef(subject)) { AddComponent(subject); }*/ if (subject.MetaBase.Name == "ConnectorComposition") { AddConnection(subject); } } }
/// <summary> /// Elaborates a DesignContainer object. /// </summary> public override void Elaborate() { MgaFilter filter = this.Subject.Project.CreateFilter(); var allObjects = this.Subject.GetDescendantFCOs(filter); foreach (MgaFCO obj in allObjects) { if (obj.IsPrimaryDerived) { obj.DetachFromArcheType(); } } foreach (MgaFCO obj in allObjects) { if (this.Traceability.ContainsKey(obj.ID) == false) { // add to traceability this.Traceability.Add(obj.ID, obj.ID); } if (obj is MgaReference) { var reference = obj as MgaReference; if (reference.Referred == null) { if (reference.MetaBase.MetaRef == this.Factory.ComponentRefMeta) { this.Logger.WriteWarning(string.Format("Null {0} [{1}] was ignored and skipped.", reference.Name, reference.MetaBase.Name)); } continue; } var referred = reference.Referred; MgaObject parent = null; GME.MGA.Meta.objtype_enum type; reference.GetParent(out parent, out type); if (IsConfigurationType(parent)) { continue; } if (parent.MetaBase.MetaRef == Factory.DecisionGroupMeta || parent.MetaBase.MetaRef == Factory.VisualConstraintMeta || parent.MetaBase.MetaRef == Factory.And_operatorMeta || parent.MetaBase.MetaRef == Factory.Or_operatorMeta || parent.MetaBase.MetaRef == Factory.Not_operatorMeta) { // DecisionGroup can hold only ComponentRefs, so we can't do anything with its children (META-3595) continue; } if (referred.MetaBase.MetaRef == this.Factory.ComponentMeta) { var copied = this.SwitchReferenceToModel(parent as MgaModel, reference, true); // delete reference reference.DestroyObject(); } else if (referred.MetaBase.MetaRef == this.Factory.ComponentAssemblyMeta) { MgaObject parent2 = parent; GME.MGA.Meta.objtype_enum type2; // worst case this will terminate at the root folder level while (parent2 != null && parent2 is MgaModel) { // FIXME: is this safe? should we compare IDs? if (parent2 == reference.Referred) { string message = string.Format("Circular dependency: {0} --> {1}", parent2.Name, reference.Referred.Name); throw new ElaboratorCircularReferenceException(message); } parent2.GetParent(out parent2, out type2); } if (this.ComponentAssemblyReferences.Any(x => x.ID == reference.Referred.ID)) { string message = string.Format("Circular dependency: {0} --> {1}", string.Join(" -> ", this.ComponentAssemblyReferences.Select(x => x.Name)), reference.Referred.Name); throw new ElaboratorCircularReferenceException(message); } var copied = this.SwitchReferenceToModel(parent as MgaModel, reference, false); // prevent circular dependency var innerElaborator = Elaborator.GetElaborator(copied, this.Logger, UnrollConnectors) as ComponentAssemblyElaborator; // use only one map innerElaborator.Traceability = this.Traceability; innerElaborator.ComponentGUIDs = this.ComponentGUIDs; innerElaborator.ComponentCopyMap = this.ComponentCopyMap; // hold only one queue foreach (var item in this.ComponentAssemblyReferences) { innerElaborator.ComponentAssemblyReferences.Enqueue(item); } innerElaborator.ComponentAssemblyReferences.Enqueue(reference.Referred); this.InnerElaborators.Add(innerElaborator); innerElaborator.Elaborate(); // delete reference reference.DestroyObject(); } else if (referred.MetaBase.MetaRef == this.Factory.DesignContainerMeta) { MgaObject parent2 = parent; GME.MGA.Meta.objtype_enum type2; // worst case this will terminate at the root folder level while (parent2 != null && parent2 is MgaModel) { // FIXME: is this safe? should we compare IDs? if (parent2 == reference.Referred) { string message = string.Format("Circular dependency: {0} --> {1}", parent2.Name, reference.Referred.Name); throw new ElaboratorCircularReferenceException(message); } parent2.GetParent(out parent2, out type2); } if (this.DesignSpaceReferences.Any(x => x.ID == reference.Referred.ID)) { string message = string.Format("Circular dependency: {0} --> {1}", string.Join(" -> ", this.DesignSpaceReferences.Select(x => x.Name)), reference.Referred.Name); throw new ElaboratorCircularReferenceException(message); } var copied = this.SwitchReferenceToModel(parent as MgaModel, reference, false); var innerElaborator = Elaborator.GetElaborator(copied, this.Logger, UnrollConnectors) as DesignContainerElaborator; // use only one map innerElaborator.Traceability = this.Traceability; innerElaborator.ComponentGUIDs = this.ComponentGUIDs; innerElaborator.ComponentCopyMap = this.ComponentCopyMap; // hold only one queue foreach (var item in this.DesignSpaceReferences) { innerElaborator.DesignSpaceReferences.Enqueue(item); } innerElaborator.DesignSpaceReferences.Enqueue(reference.Referred); this.InnerElaborators.Add(innerElaborator); innerElaborator.Elaborate(); // delete reference reference.DestroyObject(); } } } }