public ValueFlowTestFixture() { String connectionString; GME.MGA.MgaUtils.ImportXMEForTest(path_XME, out connectionString); Boolean ro_mode; Project = new MgaProject(); Project.Open(connectionString, out ro_mode); Project.EnableAutoAddOns(true); MgaFilter filter = Project.CreateFilter(); filter.Kind = "Component"; filter.Name = "ValueFlow"; var mgaGateway = new MgaGateway(Project); mgaGateway.PerformInTransaction(delegate { ValueFlow = Project.AllFCOs(filter) .Cast <MgaFCO>() .Select(x => CyPhyC.Component.Cast(x)) .First(); RunFormulaEvaluator(ValueFlow.Impl as MgaFCO); }, transactiontype_enum.TRANSACTION_GENERAL, abort: false); }
public static IEnumerable <CyPhy.DesignContainer> GetDesignContainersByName(this MgaProject project, String name) { MgaFilter filter = project.CreateFilter(); filter.Kind = "DesignContainer"; filter.Name = name; return(project.AllFCOs(filter) .Cast <MgaFCO>() .Select(x => CyPhyClasses.DesignContainer.Cast(x))); }
public static IEnumerable <CyPhy.ComponentAssembly> GetComponentAssembliesByName(this MgaProject project, String name) { MgaFilter filter = project.CreateFilter(); filter.Kind = "ComponentAssembly"; filter.Name = name; return(project.AllFCOs(filter) .Cast <MgaFCO>() .Select(x => CyPhyClasses.ComponentAssembly.Cast(x))); }
public static IEnumerable <CyPhy.Component> GetComponentsByName(this MgaProject project, String name) { MgaFilter filter = project.CreateFilter(); filter.Kind = "Component"; filter.Name = name; return(project.AllFCOs(filter) .Cast <MgaFCO>() .Select(x => CyPhyClasses.Component.Cast(x)) .Where(c => c.ParentContainer.Kind == "Components")); }
private CyPhy.Component getComponentByPath(String path) { MgaFilter filter = fixture.proj.CreateFilter(); filter.Kind = "Component"; // Only find Components whose parent folders are "Components" folders var match = fixture.proj.AllFCOs(filter) .Cast <MgaFCO>() .FirstOrDefault(c => CyPhyClasses.Component.Cast(c).Path == path); return(CyPhyClasses.Component.Cast(match)); }
private CyPhy.TestBench GetTestBenchByName(String name) { MgaFilter filter = proj.CreateFilter(); filter.Kind = "TestBench"; filter.Name = name; return(proj.AllFCOs(filter) .Cast <MgaFCO>() .Select(x => CyPhyClasses.TestBench.Cast(x)) .Cast <CyPhy.TestBench>() .FirstOrDefault()); }
private CyPhy.Component GetComponentByName(String name) { MgaFilter filter = fixture.project.CreateFilter(); filter.Kind = "Component"; filter.Name = name; return(fixture.project.AllFCOs(filter) .Cast <MgaFCO>() .Select(x => CyPhyClasses.Component.Cast(x)) .Cast <CyPhy.Component>() .Where(c => c.ParentContainer.Kind == "Components") .First()); }
private static Dictionary <string, CyPhy.Component> getCyPhyMLComponentDictionary_ByName(CyPhy.RootFolder cyPhyMLRootFolder) { var rtn = new Dictionary <string, CyPhy.Component>(); var project = cyPhyMLRootFolder.Impl.Project; MgaFilter filter = project.CreateFilter(); filter.Kind = "Component"; foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>().Where(x => x.ParentFolder != null)) { var comp = CyPhyClasses.Component.Cast(item); rtn[comp.Name] = comp; } return(rtn); }
/// <summary> /// Given a component, ensures that is has an AVMID unique to its project. /// If it has an AVMID, and it is unique, it will not be changed. /// Otherwise, a new one will be assigned. /// </summary> /// <param name="component"></param> /// <returns>The resulting AVMID of the Component</returns> public static String EnsureAVMID(CyPhy.Component component) { var mp_GmeProject = component.Impl.Project; Boolean b_AssignNewAVMID = false; // If this component doesn't have an AVM ID already, we will assign one. if (String.IsNullOrWhiteSpace(component.Attributes.AVMID)) { b_AssignNewAVMID = true; } // If component is not an archetype (i.e.: not defined in a Components folder), don't mess with it. else if (component.ParentContainer.Kind != "Components") { b_AssignNewAVMID = false; } else { // Already has an AVMID -- Scan project for conflicts MgaFilter filter = mp_GmeProject.CreateFilter(); filter.Kind = "Component"; // Only find Components whose parent folders are "Components" folders foreach (var item in mp_GmeProject.AllFCOs(filter) .Cast <MgaFCO>() .Where(i => i.ParentFolder != null && i.ParentFolder.MetaBase.Name == "Components")) { var c_item = CyPhyClasses.Component.Cast(item); if (c_item.ID != component.ID && c_item.Attributes.AVMID == component.Attributes.AVMID) { b_AssignNewAVMID = true; } } } if (b_AssignNewAVMID) { component.Attributes.AVMID = Guid.NewGuid().ToString("D"); } return(component.Attributes.AVMID); }
private JObject RunComponent(string component_name) { if (File.Exists("output.py")) { File.Delete("output.py"); } // Ensure output.py is deleted Assert.False(File.Exists("output.py")); PerformInTransaction(delegate { MgaFilter filter = proj.CreateFilter(); filter.Kind = "Component"; filter.Name = component_name; var fco_component = proj.AllFCOs(filter) .Cast <MgaFCO>() .First(); Console.Out.Write(fco_component.ToString()); ValueFlowInterpreter.ValueFlowInterpreter vfint = new ValueFlowInterpreter.ValueFlowInterpreter(); vfint.Initialize(proj); vfint.Main(proj, fco_component, null, ValueFlowInterpreter.ValueFlowInterpreter.ComponentStartMode.GME_CONTEXT_START); }); // Ensure output.py was created Assert.True(File.Exists("output.py")); var str_result = RunPy(); Console.Out.Write(str_result); var result = JObject.Parse(str_result) as JObject; return(result); }
public static Dictionary <string, CyPhy.Component> getCyPhyMLComponentDictionary_ByAVMID(CyPhy.RootFolder cyPhyMLRootFolder) { var rtn = new Dictionary <string, CyPhy.Component>(); var project = cyPhyMLRootFolder.Impl.Project; MgaFilter filter = project.CreateFilter(); filter.Kind = "Component"; // The only folder that can contain components is "Components" foreach (var componentsFolder in cyPhyMLRootFolder.Children.ComponentsCollection) { IMgaFolder mgaComponentsFolder = (IMgaFolder)componentsFolder.Impl; foreach (var item in mgaComponentsFolder.GetDescendantFCOs(filter).Cast <MgaFCO>().Where(x => x.ParentFolder != null)) { var comp = CyPhyClasses.Component.Cast(item); rtn[comp.Attributes.AVMID] = comp; } } return(rtn); }
public List <IMgaFCO> GetRelatedComponents() { string classification = Clm.GetComponentCategory(this.CyPhyComponent); List <IMgaFCO> result = new List <IMgaFCO>(); MgaFilter filter = this.CyPhyComponent.Project.CreateFilter(); filter.Kind = "Component"; var components = this.CyPhyComponent.Project.AllFCOs(filter); foreach (IMgaFCO componentItem in components) { if (Clm.CompareClassifications(componentItem.StrAttrByName["Classifications"], classification)) { result.Add(componentItem); } } // TODO: filter the 'result' based on any parameters from the DesignContainer return(result); }
/// <summary> /// Utility function to switch a reference to a model copy or instance. Reference should be deleted after this call. /// </summary> /// <remarks>In case copy is requested and the target element is a derived type (i.e. subtype or instance) inheritance chain will be cut. To make further elaboration possible.</remarks> /// <param name="parentModel">Parent model of the reference</param> /// <param name="reference">Reference to switch to a model</param> /// <param name="createInstance">If true creates an instance otherwise makes a copy of the target object. See remarks.</param> /// <returns>Model which was created instead of the reference.</returns> protected MgaModel SwitchReferenceToModel(MgaModel parentModel, MgaReference reference, bool createInstance) { this.LogDebug("Switching reference to model", reference); if (reference.Referred == null) { // failed to elaborate this.Logger.WriteFailed("Reference is null. {0} {1} [{2}]", reference.ID, reference.Name, reference.MetaBase.Name); return(null); } var referred = reference.Referred; // FIXME: this could fail, e.g. if componentref refers to a test component and we are in a CA GME.MGA.Meta.MgaMetaRole role = null; foreach (GME.MGA.Meta.MgaMetaRole roleItem in (parentModel.Meta as GME.MGA.Meta.MgaMetaModel) .Roles) { if (roleItem.Kind.MetaRef == referred.MetaBase.MetaRef) { role = roleItem; break; } } if (role == null) { throw new ElaboratorException(string.Format("Role was not found for {0} [{1}] in {2} [{3}]", referred.Name, referred.MetaBase.Name, parentModel.Name, parentModel.MetaBase.Name)); } MgaFCO copiedObj = null; Func <MgaFCO, MgaFCO, MgaFCO> getOriginalChildObject = null; if (createInstance) { this.LogDebug("Creating instance from", referred); MgaFCO originalReferred = null; if (UnrollConnectors) { originalReferred = referred; MgaFCO referredCopy; if (ComponentCopyMap.TryGetValue(referred, out referredCopy)) { } else { // FIXME update traceability referredCopy = referred.ParentFolder.CopyFCODisp(referred); ComponentCopyMap[referred] = referredCopy; } referred = referredCopy; } copiedObj = parentModel.DeriveChildObject(referred, role, true); Func <IMgaFCO, int> getRelID = (fco) => { if (fco.DerivedFrom != null && fco.IsPrimaryDerived == false) { // workaround GME bug fixed 2/27/2017 const int RELID_BASE_MAX = 0x07FFFFFF; // Mga.idl return((~RELID_BASE_MAX & fco.RelID) | (RELID_BASE_MAX & fco.DerivedFrom.RelID)); } return(fco.RelID); }; Func <MgaFCO, string> getFCORelIds = fco => { string ret = "/#" + getRelID(fco); MgaModel parent = fco.ParentModel; while (parent != null) { ret = "/#" + getRelID(parent) + ret; parent = parent.ParentModel; } return(ret); }; getOriginalChildObject = new Func <MgaFCO, MgaFCO, MgaFCO>((parent, copied) => { if (UnrollConnectors == false) { return(copied.DerivedFrom); } string relPath = getFCORelIds(copied.DerivedFrom).Substring(getFCORelIds(referred).Length); var ret = (MgaFCO)originalReferred.GetObjectByPathDisp(relPath); if (ret == null) { ret = originalReferred; // GME bug workaround continued foreach (var relID in relPath.Substring(2).Split(new[] { "/#" }, StringSplitOptions.None)) { ret = ret.ChildObjects.Cast <MgaFCO>().Where(f => getRelID(f).ToString() == relID).First(); } if (ret == null) { throw new ArgumentNullException(); } } return(ret); }); var guid = reference.StrAttrByName[AttributeNameInstanceGuid]; if (string.IsNullOrWhiteSpace(guid)) { reference.set_StrAttrByName(AttributeNameInstanceGuid, reference.GetGuidDisp()); guid = reference.StrAttrByName[AttributeNameInstanceGuid]; this.LogDebug("InstanceGUID was empty for reference, assigned new : " + guid, reference); } // parent model should contain the concatenated InstanceGUID string guidConcat = parentModel.RegistryValue[RegistryNameInstanceGuidChain] + guid; copiedObj.RegistryValue[RegistryNameInstanceGuidChain] = guidConcat; copiedObj.RegistryValue[RegistryNameOriginalReferredID] = reference.Referred.ID; this.LogDebug(string.Format("Overwriting InstanceGUID to {0}", guidConcat), referred); copiedObj.StrAttrByName[AttributeNameInstanceGuid] = guidConcat; copiedObj.RegistryValue[RegistryNameGmeIDChain] = parentModel.RegistryValue[RegistryNameGmeIDChain] + "," + reference.ID + "," + referred.ID; } else { this.LogDebug("Creating copy from", referred); copiedObj = parentModel.CopyFCODisp(referred, role); if (copiedObj.ArcheType != null) { // instance or subtype this.LogDebug("Cutting inheritance for copied object", copiedObj); copiedObj.DetachFromArcheType(); } getOriginalChildObject = new Func <MgaFCO, MgaFCO, MgaFCO>((parent, copied) => { // only chance to find objects are based on relids, which might not be unique return(parent.ChildObjectByRelID[copied.RelID] as MgaFCO); }); copiedObj.RegistryValue[RegistryNameGmeIDChain] = parentModel.RegistryValue[RegistryNameGmeIDChain] + "," + reference.ID + "," + referred.ID; if (reference.MetaBase.MetaRef == this.Factory.ComponentRefMeta) { var guid = reference.StrAttrByName[AttributeNameInstanceGuid]; copiedObj.RegistryValue[RegistryNameInstanceGuidChain] = parentModel.RegistryValue[RegistryNameInstanceGuidChain] + guid; copiedObj.RegistryValue[RegistryNameOriginalReferredID] = reference.Referred.ID; // push current instance GUID down to all component assembly elements MgaFilter filter = copiedObj.Project.CreateFilter(); filter.ObjType = GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL.ToString(); // filter.Kind = "ComponentAssembly"; foreach (MgaFCO obj in (copiedObj as MgaModel).GetDescendantFCOs(filter)) { if (obj.MetaBase.MetaRef == this.Factory.ComponentAssemblyMeta) { obj.RegistryValue[RegistryNameInstanceGuidChain] = copiedObj.RegistryValue[RegistryNameInstanceGuidChain]; obj.RegistryValue[RegistryNameGmeIDChain] = copiedObj.RegistryValue[RegistryNameGmeIDChain]; } } } } copiedObj.Name = reference.Name; if (reference.Meta.MetaRef == this.Factory.ComponentRefMeta && copiedObj.Meta.MetaRef == this.Factory.ComponentAssemblyMeta) { // TODO what should happen here // var managedGuid = reference.StrAttrByName["ManagedGUID"]; ComponentRef does not have ManagedGUID var managedGuid = reference.StrAttrByName["InstanceGUID"]; if (string.IsNullOrEmpty(managedGuid) == false) { // copiedObj.StrAttrByName["ManagedGUID"] = managedGuid; } } foreach (MgaPart part in reference.Parts) { int x; int y; string icon; part.GetGmeAttrs(out icon, out x, out y); try { copiedObj.Part[part.MetaAspect].SetGmeAttrs(icon, x, y); } catch (System.Runtime.InteropServices.COMException) { // It's okay. This means that Reference is visible in this aspect, but copiedObj isn't } } // add / update to traceability string baseId = null; if (this.Traceability.TryGetValue(reference.ID, out baseId)) { //// if it is already in the traceability it is a temporary object. //// we need our final object in the mapping this.Traceability.Remove(reference.ID); this.Traceability.Add(copiedObj.ID, baseId); } else { this.Traceability.Add(copiedObj.ID, referred.ID); } // safe connection information for switching connections later. Dictionary <MgaFCO, MgaFCO> original2Copied = new Dictionary <MgaFCO, MgaFCO>(); original2Copied.Add(referred, copiedObj); MgaFCOs objects = null; if (createInstance) { objects = (copiedObj as MgaModel).GetDescendantFCOs(copiedObj.Project.CreateFilter()); } else { objects = (copiedObj as MgaModel).ChildFCOs; } foreach (MgaFCO copied in objects) { if (copied == copiedObj) { continue; } var original = getOriginalChildObject(referred, copied); original2Copied.Add(original, copied); if (this.Traceability.TryGetValue(original.ID, out baseId)) { // if it is already in the traceability it is a temporary object. // we need our final object in the mapping this.Traceability.Remove(original.ID); this.Traceability.Add(copied.ID, baseId); } else { this.Traceability.Add(copied.ID, original.ID); } if (!createInstance && copied.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL) { this.AddRecursivelyTraceability(copied, original); } } // switch connections to refport children foreach (MgaConnPoint connPoint in reference.UsedByConns) { var connection = connPoint.Owner as IMgaSimpleConnection; if (connPoint.ConnRole == "src" && connection.SrcReferences.Count > 0 && connection.SrcReferences[1] == reference) { // what if this is instance var newEndPoint = original2Copied[connection.Src]; if (newEndPoint == null) { throw new Exception("null connection endpoint"); } // create an empty array for the connection references MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType); connection.SetSrc(emptyArray, newEndPoint); } if (connPoint.ConnRole == "dst" && connection.DstReferences.Count > 0 && connection.DstReferences[1] == reference) { // what if this is instance var newEndPoint = original2Copied[connection.Dst]; if (newEndPoint == null) { throw new Exception("null connection endpoint"); } // create an empty array for the connection references MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType); connection.SetDst(emptyArray, newEndPoint); } } // switch connections to original reference object itself foreach (MgaConnPoint connPoint in reference.PartOfConns) { var connection = connPoint.Owner as IMgaSimpleConnection; if (connPoint.ConnRole == "src") { // create an empty array for the connection references MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType); try { connection.SetSrc(emptyArray, copiedObj); } catch (COMException ex) { if (ex.Message.Contains("Illegal connection") && ex.Message.Contains("meta violation")) { var refID = reference.ID; while (Traceability.ContainsKey(refID)) { refID = Traceability[refID]; } Logger.WriteWarning("<a href=\"mga:{0}\">{1}</a>'s referred type ({2}) isn't a legal SRC target for {3} connections. Skipping re-creation of this connection.", refID, reference.Name, reference.Referred.MetaBase.Name, connection.MetaBase.Name); } else { throw ex; } } } else if (connPoint.ConnRole == "dst") { // create an empty array for the connection references MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType); try { connection.SetDst(emptyArray, copiedObj); } catch (COMException ex) { if (ex.Message.Contains("Illegal connection") && ex.Message.Contains("meta violation")) { var refID = reference.ID; while (Traceability.ContainsKey(refID)) { refID = Traceability[refID]; } Logger.WriteWarning("<a href=\"mga:{0}\">{1}</a>'s referred type ({2}) isn't a legal DST target for {3} connections. Skipping re-creation of this connection.", refID, reference.Name, reference.Referred.MetaBase.Name, connection.MetaBase.Name); } else { throw ex; } } } } return(copiedObj as MgaModel); }
public static int Main(string[] args) { var options = new Options(); if (!Parser.Default.ParseArguments(args, options)) { return(-1); } var project = GetProject(options.MgaFile); if (project == null) { return(1); } try { var mgaGateway = new MgaGateway(project); var designList = new List <CyPhy.DesignEntity>(); var designName = Safeify(options.DesignName); bool bExceptionOccurred = false; mgaGateway.PerformInTransaction(delegate { try { #region Collect DesignEntities MgaFilter filter = project.CreateFilter(); filter.Kind = "ComponentAssembly"; foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>().Where(x => x.ParentFolder != null)) { designList.Add(CyPhyClasses.ComponentAssembly.Cast(item)); } filter = project.CreateFilter(); filter.Kind = "DesignContainer"; foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>().Where(x => x.ParentFolder != null)) { designList.Add(CyPhyClasses.DesignContainer.Cast(item)); } #endregion #region Process DesignEntities foreach (CyPhy.DesignEntity de in designList) { var currentDesignName = Safeify(de.Name); if (!string.IsNullOrEmpty(options.DesignName) && currentDesignName != designName) { continue; } var dm = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(de); var outFilePath = String.Format("{0}\\{1}.adm", new FileInfo(options.MgaFile).DirectoryName, currentDesignName); OpenMETA.Interchange.AvmXmlSerializer.SaveToFile(outFilePath, dm); } #endregion } catch (Exception ex) { Console.Error.WriteLine("Exception: {0}", ex.Message.ToString()); Console.Error.WriteLine("Stack: {0}", ex.StackTrace.ToString()); bExceptionOccurred = true; } }, abort: false); if (bExceptionOccurred) { return(-1); } return(0); } finally { project.Close(true); } }
/// <summary> /// Determines what action to take if a Component has been created under a Components folder. /// The actions are dispatched to other functions. /// </summary> /// <param name="componentFco"></param> private void Process(CyPhy.Component component) { var componentFco = component.Impl; if (Logger == null) { Logger = new CyPhyGUIs.GMELogger(componentFco.Project, this.ComponentName); } bool HasAVMID = !String.IsNullOrWhiteSpace(component.Attributes.AVMID); bool HasPath = !String.IsNullOrWhiteSpace(component.Attributes.Path); META.ComponentLibraryManager.EnsureComponentFolder(component); // Get all other components that have a "Components" folder as parent. // For the next logic tests, we'll need this list. var project = component.Impl.Project; MgaFilter filter = project.CreateFilter(); filter.Kind = "Component"; var otherComponents = project.AllFCOs(filter) .Cast <MgaFCO>() .Where(x => x.ParentFolder != null && x.ParentFolder.MetaBase.Name == "Components" && x.ID != componentFco.ID) .Select(x => CyPhyClasses.Component.Cast(x)); //bool AVMIDCollision = HasAVMID && otherComponents.Where(c => c.Attributes.AVMID == component.Attributes.AVMID).Any(); bool PathCollision = HasPath; if (HasPath) { PathCollision = false; string myFullPath = Path.GetFullPath(component.Attributes.Path); foreach (var cFullPath in otherComponents.Where(c => !String.IsNullOrWhiteSpace(c.Attributes.Path)) .Select(c => Path.GetFullPath(c.Attributes.Path))) { if (myFullPath == cFullPath) { PathCollision = true; } } } //bool PathCollision = HasPath && otherComponents.Where(c => Path.GetFullPath(c.Attributes.Path) == Path.GetFullPath(component.Attributes.Path)).Any(); var projectPath_Absolute = component.Impl.Project.GetRootDirectoryPath(); var lastChar = projectPath_Absolute.Last(); if (lastChar != '\\' && lastChar != '/') { projectPath_Absolute += '\\'; } if (HasAVMID && HasPath) { var oldCompPath_Absolute = Path.Combine(projectPath_Absolute, component.Attributes.Path); var folderExists = Directory.Exists(oldCompPath_Absolute); if (PathCollision || !folderExists) { var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project); var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute); newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/'; var firstChars = newCompPath_Relative.Substring(0, 2); if (firstChars != ".\\" && firstChars != "./") { newCompPath_Relative = newCompPath_Relative.Insert(0, "./"); } component.Attributes.Path = newCompPath_Relative; if (folderExists) { CopyComponentFiles(oldCompPath_Absolute, newCompPath_Absolute); } else if (component.Children.ResourceCollection.Any()) { WarnUserAboutMissingFiles(component); } } } else if (HasAVMID) { var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project); var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute); newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/'; component.Attributes.Path = newCompPath_Relative; if (component.Children.ResourceCollection.Any()) { WarnUserAboutMissingFiles(component); } } else if (HasPath) { var oldCompPath_Absolute = Path.Combine(projectPath_Absolute, component.Attributes.Path); var folderExists = Directory.Exists(oldCompPath_Absolute); if (PathCollision || !folderExists) { var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project); var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute); newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/'; var firstChars = newCompPath_Relative.Substring(0, 2); if (firstChars != ".\\" && firstChars != "./") { newCompPath_Relative = newCompPath_Relative.Insert(0, "./"); } component.Attributes.Path = newCompPath_Relative; if (folderExists) { CopyComponentFiles(oldCompPath_Absolute, newCompPath_Absolute); } else if (component.Children.ResourceCollection.Any()) { WarnUserAboutMissingFiles(component); } } } else { if (component.Children.ResourceCollection.Any()) { WarnUserAboutMissingFiles(component); } } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { Boolean disposeLogger = false; if (Logger == null) { Logger = new CyPhyGUIs.GMELogger(project, "CyPhyDesignExporter"); disposeLogger = true; } // TODO: Add your interpreter code Logger.WriteInfo("Running Design Exporter..."); #region Prompt for Output Path // Get an output path from the user. if (this.OutputDir == null) { using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog() { Description = "Choose a path for the generated files.", //ShowNewFolderButton = true, SelectedPath = Environment.CurrentDirectory, }) { DialogResult dr = fbd.ShowDialog(); if (dr == DialogResult.OK) { OutputDir = fbd.SelectedPath; } else { Logger.WriteWarning("Design Exporter cancelled"); return; } } } #endregion Logger.WriteInfo("Beginning Export..."); List <CyPhy.DesignEntity> lde_allCAandDC = new List <CyPhy.DesignEntity>(); List <CyPhy.TestBenchType> ltbt_allTB = new List <CyPhy.TestBenchType>(); if (currentobj != null && currentobj.Meta.Name == "ComponentAssembly") { lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(currentobj)); } else if (currentobj != null && currentobj.Meta.Name == "DesignContainer") { lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(currentobj)); } else if (currentobj != null && IsTestBenchType(currentobj.MetaBase.Name)) { ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(currentobj)); } else if (selectedobjs != null && selectedobjs.Count > 0) { foreach (MgaFCO mf in selectedobjs) { if (mf.Meta.Name == "ComponentAssembly") { lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(mf)); } else if (mf.Meta.Name == "DesignContainer") { lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(mf)); } else if (IsTestBenchType(mf.MetaBase.Name)) { ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(mf)); } } } else { CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject); MgaFilter filter = project.CreateFilter(); filter.Kind = "ComponentAssembly"; foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>()) { if (item.ParentFolder != null) { lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(item)); } } filter = project.CreateFilter(); filter.Kind = "DesignContainer"; foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>()) { if (item.ParentFolder != null) { lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(item)); } } filter = project.CreateFilter(); filter.Kind = "TestBenchType"; foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>()) { if (item.ParentFolder != null) { ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(item)); } } } foreach (CyPhy.DesignEntity de in lde_allCAandDC) { System.Windows.Forms.Application.DoEvents(); try { if (de is CyPhy.ComponentAssembly) { ExportToPackage(de as CyPhy.ComponentAssembly, OutputDir); } else { ExportToFile(de, OutputDir); } } catch (Exception ex) { Logger.WriteError("{0}: Exception encountered ({1})", de.Name, ex.Message); } Logger.WriteInfo("{0}: {1}", de.Name, OutputDir); } foreach (CyPhy.TestBenchType tbt in ltbt_allTB) { System.Windows.Forms.Application.DoEvents(); try { ExportToFile(tbt, OutputDir); } catch (Exception ex) { Logger.WriteError("{0}: Exception encountered ({1})", tbt.Name, ex.Message); } Logger.WriteInfo("{0}: {1}", tbt.Name, OutputDir); } Logger.WriteInfo(String.Format("{0} model(s) exported", lde_allCAandDC.Count + ltbt_allTB.Count)); Logger.WriteInfo("Design Exporter finished"); if (disposeLogger) { DisposeLogger(); } }
/// <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 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 void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // Get RootFolder IMgaFolder rootFolder = project.RootFolder; #region Prompt for Output Path // Get an output path from the user. String s_outPath; using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog() { Description = "Choose a path for the generated files.", //ShowNewFolderButton = true, SelectedPath = Environment.CurrentDirectory, }) { DialogResult dr = fbd.ShowDialog(); if (dr == DialogResult.OK) { s_outPath = fbd.SelectedPath; } else { GMEConsole.Warning.WriteLine("Design Exporter cancelled"); return; } } #endregion GMEConsole.Info.WriteLine("Beginning Export..."); var testBanches = new List <CyPhy.TestBench>(); if (currentobj != null && currentobj.Meta.Name == "TestBench") { testBanches.Add(CyPhyClasses.TestBench.Cast(currentobj)); } else if (selectedobjs.Count > 0) { foreach (MgaFCO mf in selectedobjs) { if (mf.Meta.Name == "TestBench") { testBanches.Add(CyPhyClasses.TestBench.Cast(mf)); } } } else { CyPhy.RootFolder root = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject); MgaFilter filter = project.CreateFilter(); filter.Kind = "TestBench"; foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>()) { if (item.ParentFolder != null) { testBanches.Add(CyPhyClasses.TestBench.Cast(item)); } } } foreach (var tb in testBanches) { System.Windows.Forms.Application.DoEvents(); try { ExportToFile(tb, s_outPath); } catch (Exception ex) { GMEConsole.Error.WriteLine("{0}: Exception encountered ({1})", tb.Name, ex.Message); } GMEConsole.Info.WriteLine("{0}: {1}", tb.Name, s_outPath); } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // TODO: show how to initialize DSML-generated classes myMig = new myMigrator(project); mig = new Migrator(project); if (currentobj != null) { if (currentobj is MgaModel) { GMEConsole.Info.WriteLine( "Migrating {0}... (To migrate the whole project, close all models and try again)", currentobj.Name); //myMig.migrateModel(currentobj as MgaModel); mig.findOldPortTypes(project, false); try { mig.migrateModel(currentobj as MgaModel); } catch (Exception ex) { GMEConsole.Error.WriteLine("{0}", ex.Message); GMEConsole.Info.WriteLine("{0}", ex.StackTrace); } } } else { //mig.convertFluidParameters(project); GMEConsole.Info.WriteLine("Migrating the entire project..."); myMig.migrateProject(); mig.findOldPortTypes(project, false); mig.migrateCyPhy2ModelicaWorkflow(project); List <string> kinds = new List <string>() { "TestBench", "ComponentAssembly", "DesignContainer", "TestComponent", "Component", "Environment" }; MgaFilter cyPhyModelFilter = project.CreateFilter(); cyPhyModelFilter.ObjType = objtype_enum.OBJTYPE_MODEL.ToString(); var objectsToMigrate = project .AllFCOs(cyPhyModelFilter) .OfType <MgaModel>() .Where(x => x.ParentModel == null && kinds.Contains(x.Meta.Name)); foreach (var objectToMigrate in objectsToMigrate) { //GMEConsole.Info.WriteLine( // "== Migrating <a href=\"mga:{0}\">{1}</a>", // objectToMigrate.ID, // objectToMigrate.Name); try { mig.migrateModel(objectToMigrate); } catch (Exception ex) { GMEConsole.Error.WriteLine("{0}", ex.Message); GMEConsole.Info.WriteLine("{0}", ex.StackTrace); } } } }
/// <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(); } } } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { if (currentobj == null) { GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName); return; } else if (currentobj.Meta.Name != "TestBench") { GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName); return; } GMEConsole.Info.WriteLine("Running {0} on TestBench '{1}'", ComponentName, currentobj.Name); // get root folder IMgaFolder rootFolder = project.RootFolder; // create a filter for components MgaFilter filter = project.CreateFilter(); filter.Kind = "Component"; // get all components var components = project.AllFCOs(filter).OfType <IMgaModel>().Cast <IMgaModel>().ToList(); // store components that may have an option (e.g. MM1, MM2) List <IMgaModel> componentsToShow = new List <IMgaModel>(); // iterate through all components // select only those which has more than one modelica model in it foreach (var component in components) { var modelicaModels = component.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "ModelicaModel"); if (modelicaModels.Count() > 1) { componentsToShow.Add(component); } } using (FidelitySelectorForm fsf = new FidelitySelectorForm()) { // show the form for the user foreach (var component in componentsToShow) { if (fsf.componentItems.FirstOrDefault( x => x.Classification == component.StrAttrByName["Classifications"]) == null) { fsf.componentItems.Add(new ComponentItem(component)); } } // get the current fidelity settings from the Testbench registry fsf.FidelitySettings = currentobj.RegistryValue["FidelitySettings"]; fsf.PopulateDgv(); fsf.ShowDialog(); foreach (string msg in fsf.consoleMessages) { GMEConsole.Info.WriteLine(msg); } // Check where the new fidelity settings should be applied: if (fsf.rbThisTestbench.Checked) { // Write the updated fidelity settings back to the Testbench registry currentobj.RegistryValue["FidelitySettings"] = fsf.FidelitySettings; } else if (fsf.rbThisFolder.Checked) { // Get all testbenches in the same folder as currentobj var thisTestingFolder = currentobj.ParentFolder; var siblingTBs = thisTestingFolder.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "TestBench").ToList(); GMEConsole.Info.WriteLine( "Applying these FidelitySettings to all TestBenches in folder '{0}':", thisTestingFolder.Name); // Go through each one and set the fidelity settings foreach (MgaFCO testbench in siblingTBs) { testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings; GMEConsole.Info.WriteLine("=> {0}", testbench.Name); } } else if (fsf.rbThisProject.Checked) { // Get all testbenches in the entire project MgaFilter testbenchFilter = project.CreateFilter(); testbenchFilter.Kind = "TestBench"; // get all testbenches var testbenches = project.AllFCOs(testbenchFilter).OfType <IMgaModel>().Cast <IMgaModel>().ToList(); GMEConsole.Info.WriteLine( "Applying these FidelitySettings to all TestBenches in project '{0}':", project.Name); // Go through each one and set the fidelity settings foreach (MgaFCO testbench in testbenches) { testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings; GMEConsole.Info.WriteLine("=> {0}", testbench.Name); } } } GMEConsole.Info.WriteLine("{0} finished.", ComponentName); }
/// <summary> /// Elaborates the give test bench. /// </summary> public override void Elaborate() { // gets all objects within the test bench in any depth. MgaFilter filter = this.Subject.Project.CreateFilter(); var allObjects = this.Subject.GetDescendantFCOs(filter); // list of test injection points in the test bench List <MgaReference> tips = new List <MgaReference>(); foreach (MgaFCO obj in allObjects) { // add object to traceability this.Traceability.Add(obj.ID, obj.ID); if (this.Factory.TestInjectionPointsMeta.Contains(obj.MetaBase.MetaRef)) { // if object is a kind of test injection point if (obj is MgaReference) { // if it is a reference if ((obj as MgaReference).Referred == null) { this.Logger.WriteWarning(string.Format("{0} [{1}] was ignored and skipped, because it points to a null reference.", obj.Name, obj.MetaBase.Name)); } else { // has a valid reference which is not null tips.Add(obj as MgaReference); } } else { this.Logger.WriteError(string.Format("{0} [{1}] is not a reference, therefore it was ignored and skipped.", obj.Name, obj.MetaBase.Name)); } } } // get the top level system under test object for this test bench var tlsut = allObjects.OfType <MgaReference>().FirstOrDefault(x => x.MetaBase.Name == "TopLevelSystemUnderTest"); // ASSUME we have exactly one // make sure it is not null if (tlsut == null) { this.Logger.WriteWarning(string.Format("No top level system under test object in {0} [{1}]", this.Subject.Name, this.Subject.MetaBase.Name)); this.Logger.WriteWarning("Assumes [{0}] has been elaborated...", this.Subject.MetaBase.Name); this.IsElaborated = true; return; } // it has a null reference if (tlsut.Referred == null) { throw new ElaboratorException(string.Format("Top level system under test object in {0} [{1}] is a null reference.", this.Subject.Name, this.Subject.MetaBase.Name)); } // switch the top level system under test to a Component Assembly // FIXME: what if it is not a component assembly ??? string tlsu_referred_id = tlsut.Referred.ID; var ca_tlsut = this.SwitchReferenceToModel(this.Subject, tlsut, false); // delete the reference object. tlsut.DestroyObject(); // component assembly elaborator used to elaborate the Top Level System Under Test object. ComponentAssemblyElaborator componentAssemblyElaborator = null; // get a Componenet assembly elaborator for the top level system under test object. componentAssemblyElaborator = Elaborator.GetElaborator <ComponentAssemblyElaborator>(ca_tlsut, this.Logger, UnrollConnectors); // pass our current traceability information componentAssemblyElaborator.Traceability = this.Traceability; componentAssemblyElaborator.ComponentGUIDs = this.ComponentGUIDs; // elaborate the top level system under test object componentAssemblyElaborator.Elaborate(); // TODO: Elaborate test components // get a look up map for all test injection point references var map = componentAssemblyElaborator.GetReverseLookupMap(tips.Select(x => x.Referred.ID)); map[tlsu_referred_id] = new MgaFCO[] { (MgaFCO)ca_tlsut }.ToList(); // gather all information about test injection points, pretend everything is ok. bool success = true; foreach (MgaReference tip in tips) { // get the new targets for this test injection point var tipTargets = map[tip.Referred.ID]; // looking for exactly one target if (tipTargets.Count == 0) { // no target mark it as failure success = false; this.Logger.WriteFailed("{0} [{1}] --> {2} [{3}] was not found in traceability.", tip.Name, tip.MetaBase.Name, tip.Referred.Name, tip.Referred.MetaBase.Name); } else if (tipTargets.Count == 1) { // exactly one target try { // redirect test injection point to the new target var switcher = new ReferenceSwitcher.ReferenceSwitcherInterpreter(); switcher.SwitchReference(tipTargets[0] as IMgaFCO, tip as IMgaReference); } catch (Exception ex) { success = false; // handle failures for this (use case we can lose ports/connections/ // what if something is an instance/subtype/readonly etc... this.Logger.WriteFailed("{0} [{1}] --> {2} [{3}] redirecting to --> {4} [{5}]", tip.Name, tip.MetaBase.Name, tip.Referred.Name, tip.Referred.MetaBase.Name, tipTargets[0].Name, tipTargets[0].MetaBase.Name); this.Logger.WriteDebug(ex.ToString()); } } else { // tipTarget.Count > 1 // more than one possible targets, this case is ambiguous, therefore mark it as failure. success = false; this.Logger.WriteFailed("{0} [{1}] --> {2} [{3}] was found more than once in the system - the choice is ambiguous.", tip.Name, tip.MetaBase.Name, tip.Referred.Name, tip.Referred.MetaBase.Name); } } if (tips.Any()) { if (success) { // check if no problems this.Logger.WriteInfo("All test injection points were redirected successfully."); } else { // some problems occured, must raise an exception throw new ElaboratorException("At least one test injection point was not redirected successfully. See log messages above."); } } // if this point is reached, mark it successful. this.IsElaborated = true; }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { if (currentobj == null) { GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName); return; } else if (currentobj.Meta.Name != "TestBench") { GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName); return; } GMEConsole.Info.WriteLine("Running {0} on TestBench '{1}'", ComponentName, currentobj.Name); // get root folder IMgaFolder rootFolder = project.RootFolder; this.currentobj = ISIS.GME.Dsml.CyPhyML.Classes.TestBench.Cast(currentobj); this.sut = this.currentobj.Children.TopLevelSystemUnderTestCollection.First(); MgaReference workflowRef = ((MgaModel)currentobj).ChildFCOs.Cast <MgaFCO>().Where(fco => fco.Meta.Name == "WorkflowRef").FirstOrDefault() as MgaReference; MgaFCO spiceTask = null; if (workflowRef != null && workflowRef.Referred != null) { foreach (var task in ((MgaModel)workflowRef.Referred).ChildFCOs.Cast <MgaFCO>().Where(fco => fco.Meta.Name == "Task")) { if (task.GetStrAttrByNameDisp("COMName").Equals("MGA.Interpreter.CyPhy2Schematic", StringComparison.InvariantCultureIgnoreCase)) { spiceTask = task; } } } if (spiceTask != null) { DoSpiceFidelitySelection(currentobj); return; } // create a filter for components MgaFilter filter = project.CreateFilter(); filter.Kind = "Component"; // get all components var components = project.AllFCOs(filter).OfType <IMgaModel>().Cast <IMgaModel>().ToList(); // store components that may have an option (e.g. MM1, MM2) List <IMgaModel> componentsToShow = new List <IMgaModel>(); // iterate through all components // select only those which has more than one modelica model in it foreach (var component in components) { var modelicaModels = component.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "ModelicaModel"); if (modelicaModels.Count() > 1) { componentsToShow.Add(component); } } using (FidelitySelectorForm fsf = new FidelitySelectorForm()) { // show the form for the user foreach (var component in componentsToShow) { if (fsf.componentItems.FirstOrDefault( x => x.Classification == component.StrAttrByName["Classifications"]) == null) { fsf.componentItems.Add(new ComponentItem(component)); } } // get the current fidelity settings from the Testbench registry fsf.FidelitySettings = currentobj.RegistryValue["FidelitySettings"]; fsf.PopulateDgv(); fsf.ShowDialog(); foreach (string msg in fsf.consoleMessages) { GMEConsole.Info.WriteLine(msg); } // Check where the new fidelity settings should be applied: if (fsf.rbThisTestbench.Checked) { // Write the updated fidelity settings back to the Testbench registry currentobj.RegistryValue["FidelitySettings"] = fsf.FidelitySettings; } else if (fsf.rbThisFolder.Checked) { // Get all testbenches in the same folder as currentobj var thisTestingFolder = currentobj.ParentFolder; var siblingTBs = thisTestingFolder.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "TestBench").ToList(); GMEConsole.Info.WriteLine( "Applying these FidelitySettings to all TestBenches in folder '{0}':", thisTestingFolder.Name); // Go through each one and set the fidelity settings foreach (MgaFCO testbench in siblingTBs) { testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings; GMEConsole.Info.WriteLine("=> {0}", testbench.Name); } } else if (fsf.rbThisProject.Checked) { // Get all testbenches in the entire project MgaFilter testbenchFilter = project.CreateFilter(); testbenchFilter.Kind = "TestBench"; // get all testbenches var testbenches = project.AllFCOs(testbenchFilter).OfType <IMgaModel>().Cast <IMgaModel>().ToList(); GMEConsole.Info.WriteLine( "Applying these FidelitySettings to all TestBenches in project '{0}':", project.Name); // Go through each one and set the fidelity settings foreach (MgaFCO testbench in testbenches) { testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings; GMEConsole.Info.WriteLine("=> {0}", testbench.Name); } } } GMEConsole.Info.WriteLine("{0} finished.", ComponentName); }