Exemplo n.º 1
0
        public MgaFCO Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            IMgaFolder rootFolder = project.RootFolder;

            acmFilename = project.ProjectConnStr.Substring("MGA=".Length, project.ProjectConnStr.Length - ".mga".Length - "MGA=".Length);
            var component = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter().CreateComponentForAcm(project, acmFilename);

            component.StrAttrByName["Path"] = "components/../";


            return((MgaFCO)component);
        }
Exemplo n.º 2
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj != null && currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);
        }
Exemplo n.º 3
0
        private string getPath(IMgaFCO fco)
        {
            string path = fco.Name;

            while (fco.ParentModel != null)
            {
                path = fco.ParentModel.Name + "/" + path;
                fco  = fco.ParentModel;
            }
            IMgaFolder folder = fco.ParentFolder;

            while (folder != null)
            {
                path   = folder.Name + "/" + path;
                folder = folder.ParentFolder;
            }
            return("/" + path);
        }
Exemplo n.º 4
0
        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);
        }
Exemplo n.º 5
0
        private void TriggerQudtRefreshIfNeeded()
        {
            if (!firstTime)
            {
                // put the arguments into private variables where they can be reached by the timer code
                if (GMEConsole == null)
                {
                    GMEConsole = GMEConsole.CreateFromProject(project);
                }
#if DEBUG
                GMEConsole.Info.WriteLine("CyPhySignalBlocksAddOn starting up...");
#endif
                GMEConsole.Info.WriteLine(String.Format("This is OpenMETA version {0}", META.VersionInfo.MetaVersion));

                //GMEConsole.Info.WriteLine(eventMask.ToString());
                if (!componentEnabled)
                {
                    GMEConsole.Info.WriteLine("CyPhySignalBlocksAddOn not enabled...");
                    return;
                }

                // First, check to see whether the libraries have already been loaded
                //CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.RootFolder>(rf as MgaObject);

                IMgaFolder  rootFolder = project.RootFolder;
                IMgaFolders subFolders = rootFolder.ChildFolders;

                // META-1320: refactored some
                // Run this on any event, but only once (if not already loaded)
                QudtLibraryInfo.Go();
                PortLibraryInfo.Go(); // portLibTimer.go();
                MaterialLibraryInfo.Go();
                CADResourceLibraryInfo.Go();
                TestbenchesInfo.Go();

                firstTime = true;
            }
        }
Exemplo n.º 6
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code

            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);

            if (currentobj.Meta.Name == "Component")
            {
                VF.Component dsCurrentObj = VFClasses.Component.Cast(currentobj);

                // List of components for which we need dictionaries
                var components = new List <string>();

                // constants and function references list
                var parameters = new List <Parameter>();

                // functions
                var functions = new List <Function>();

                // Build the list of all constants and functions
                BuildLists("", dsCurrentObj, components, parameters, functions);

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"output.py"))
                {
                    file.WriteLine("import json");
                    file.WriteLine("");
                    file.WriteLine("parameters = dict()");
                    file.WriteLine("");
                    file.WriteLine("def add(x, *args):");
                    file.WriteLine("  for arg in args:");
                    file.WriteLine("    x = x + arg");
                    file.WriteLine("  return x");
                    file.WriteLine("");
                    file.WriteLine("def mult(x, *args):");
                    file.WriteLine("  for arg in args:");
                    file.WriteLine("    x = x * arg");
                    file.WriteLine("  return x");
                    file.WriteLine("");
                    file.WriteLine("def max (x, *args):");
                    file.WriteLine("  for arg in args:");
                    file.WriteLine("    if arg > x:");
                    file.WriteLine("      x = arg");
                    file.WriteLine("  return x");
                    file.WriteLine("");

                    file.WriteLine("simpleResults = list()");
                    file.WriteLine("complexResults = list()");
                    file.WriteLine("pythonResults = list()");
                    file.WriteLine("");

                    foreach (var c in components)
                    {
                        file.WriteLine("parameters[\"" + c.Replace(".", "\"][\"") + "\"] = dict()");
                    }

                    var knownElements       = new List <System.Guid>();
                    var newKnownElements    = new List <System.Guid>();
                    var values              = new Dictionary <System.Guid, string>();
                    int simpleResultsCount  = 0;
                    int complexResultsCount = 0;
                    int pythonResultsCount  = 0;
                    int passIndex           = 0;

                    int lastCount = -1;
                    int count     = 0;
                    while (count > lastCount)
                    {
                        file.WriteLine("\n#----------------- Pass " + passIndex++ + " ------------------");
                        lastCount = count;
                        foreach (var p in parameters.Where(p => !knownElements.Contains(p.guid)))
                        {
                            if (p.constant)
                            {
                                newKnownElements.Add(p.guid);
                                values.Add(p.guid, "parameters[\"" + p.name.Replace(".", "\"][\"") + "\"]");
                                file.WriteLine("parameters[\"" + p.name.Replace(".", "\"][\"") + "\"] = " + p.value);
                                count++;
                            }
                            else if (knownElements.Contains(p.dependencies.First()))
                            {
                                newKnownElements.Add(p.guid);
                                values.Add(p.guid, values[p.dependencies.First()]);
                                file.WriteLine("parameters[\"" + p.name.Replace(".", "\"][\"") + "\"] = " + values[p.dependencies.First()]);
                                count++;
                            }
                        }
                        file.WriteLine("");

                        foreach (var f in functions.Where(f => !knownElements.Contains(f.guid)))
                        {
                            var unsatisfiedDeps = f.dependencies.Where(d => !knownElements.Contains(d));
                            if (!unsatisfiedDeps.Any())
                            {
                                if (f.type == Function.FunctionType.SIMPLE)
                                {
                                    var expressionString = Function.simpleFunctionTransform[f.simpleType] + "(" + String.Join(",", f.dependencies.Select(x => values[x]).ToList()) + ")";
                                    file.WriteLine("simpleResults.append(" + expressionString + ")");

                                    var valueString = "simpleResults[" + simpleResultsCount++ + "]";
                                    newKnownElements.Add(f.guid);
                                    values.Add(f.guid, valueString);
                                    count++;
                                }
                                else if (f.type == Function.FunctionType.COMPLEX)
                                {
                                    // Replace the META variables with their respective Python variables
                                    var templateStringIndex = 0;
                                    var output = new StringBuilder(f.expression);
                                    foreach (var d in f.dependencies)
                                    {
                                        output.Replace("$" + templateStringIndex++, values[d]);
                                    }
                                    var expressionString = "(" + output.ToString() + ")";
                                    file.WriteLine("complexResults.append(" + expressionString + ")");

                                    var valueString = "complexResults[" + complexResultsCount++ + "]";
                                    newKnownElements.Add(f.guid);
                                    values.Add(f.guid, valueString);
                                    count++;
                                }
                                else if (f.type == Function.FunctionType.PYTHON)
                                {
                                    var functionName = Path.GetFileNameWithoutExtension(f.python_filename);
                                    file.WriteLine("\nimport " + functionName);
                                    file.WriteLine("pythonResults.append(" + functionName + "." + functionName + "(");
                                    file.Write("    " + String.Join(",\n    ", f.dependencies.Select(x => values[x]).ToList()));
                                    file.WriteLine("))\n");
                                    int outputIndex = 0;
                                    foreach (var output in f.outputs)
                                    {
                                        var valueString = "pythonResults[" + pythonResultsCount + "][" + outputIndex++ + "]";
                                        newKnownElements.Add(output);
                                        values.Add(output, valueString);
                                        count++;
                                    }
                                    newKnownElements.Add(f.guid);
                                    pythonResultsCount++;
                                }
                            }
                        }
                        knownElements.AddRange(newKnownElements);
                        newKnownElements = new List <Guid>();
                    }
                    file.WriteLine("#------ Done! (No new values found.) -------");
                    file.WriteLine("");
                    file.WriteLine("print json.dumps(parameters, indent=2, sort_keys=True)");
                    file.WriteLine("");
                    file.WriteLine("with open('output.json', 'w') as f_out:");
                    file.WriteLine("    json.dump(parameters, f_out, indent=2, sort_keys=True)");
                }
            }
        }
Exemplo n.º 7
0
        public static int Main(String[] args)
        {
            if (args.Length < 2 || args.Length > 4)
            {
                usage();
                return(1);
            }
            MgaProject    mgaProject;
            List <String> lp_FilesToImport         = new List <string>();
            string        avmFilePath              = "";
            string        mgaProjectPath           = "";
            string        componentReplacementPath = "";

            bool rOptionUsed = false;
            bool pOptionUsed = false;

            for (int ix = 0; ix < args.Length; ++ix)
            {
                if (args[ix].ToLower() == "-r")
                {
                    if (pOptionUsed)
                    {
                        usage();
                        return(1);
                    }
                    rOptionUsed = true;

                    if (++ix >= args.Length)
                    {
                        usage();
                        return(1);
                    }

                    if (avmFilePath != null && avmFilePath != "")
                    {
                        if (mgaProjectPath != null && mgaProjectPath != "")
                        {
                            usage();
                            return(1);
                        }
                        mgaProjectPath = avmFilePath;
                        avmFilePath    = "";
                        lp_FilesToImport.Clear();
                    }

                    String sImportDirectory = args[ix];

                    String   startingDirectory = Path.GetFullPath(sImportDirectory);
                    string[] xmlFiles          = Directory.GetFiles(startingDirectory, "*.acm", SearchOption.AllDirectories);

                    foreach (String p_XMLFile in xmlFiles)
                    {
                        lp_FilesToImport.Add(Path.GetFullPath(p_XMLFile));
                    }
                }
                else if (args[ix].ToLower() == "-p")
                {
                    if (rOptionUsed)
                    {
                        usage();
                        return(1);
                    }
                    pOptionUsed = true;

                    if (++ix >= args.Length)
                    {
                        usage();
                        return(1);
                    }
                    componentReplacementPath = args[ix];
                }
                else if (lp_FilesToImport.Count == 0 && avmFilePath == "")
                {
                    avmFilePath = args[ix];
                    try
                    {
                        lp_FilesToImport.Add(Path.GetFullPath(avmFilePath));
                    }
                    catch (System.ArgumentException ex)
                    {
                        Console.Out.WriteLine(ex.Message);
                        Console.Out.WriteLine(avmFilePath);
                        throw ex;
                    }
                }
                else
                {
                    if (mgaProjectPath != null && mgaProjectPath != "")
                    {
                        usage();
                        return(1);
                    }
                    mgaProjectPath = args[ix];
                }
            }


            mgaProject = GetProject(mgaProjectPath);
            try
            {
                bool bExceptionOccurred = false;
                if (mgaProject != null)
                {
                    MgaGateway mgaGateway = new MgaGateway(mgaProject);

                    mgaGateway.PerformInTransaction(delegate
                    {
                        string libroot = Path.GetDirectoryName(Path.GetFullPath(mgaProjectPath));

                        CyPhyML.RootFolder cyPhyMLRootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyMLClasses.RootFolder>(mgaProject.RootFolder as MgaObject);

                        #region Attach QUDT library if needed
                        IMgaFolder oldQudt = mgaProject.RootFolder.ChildFolders.Cast <IMgaFolder>().Where(x => x.LibraryName != "" && (x.Name.ToLower().Contains("qudt"))).FirstOrDefault();
                        string mgaQudtPath = Meta_Path + "\\meta\\CyPhyMLQudt.mga";

                        bool needAttach = false;
                        if (oldQudt == null)
                        {
                            needAttach = true;
                        }
                        else
                        {
                            long loldModTime;
                            DateTime oldModTime = long.TryParse(oldQudt.RegistryValue["modtime"], out loldModTime) ? DateTime.FromFileTimeUtc(loldModTime) : DateTime.MinValue;
                            needAttach          = System.IO.File.GetLastWriteTimeUtc(mgaQudtPath).CompareTo(oldModTime) > 0;
                            if (!needAttach)
                            {
                                Console.Error.WriteLine("QUDT is up-to-date: embedded library modified " + oldModTime.ToString() + ", CyPhyMLQudt.mga modified " + System.IO.File.GetLastWriteTimeUtc(mgaQudtPath).ToString());
                            }
                        }

                        if (needAttach)
                        {
                            Console.Error.WriteLine("Attaching library " + mgaQudtPath);
                            ISIS.GME.Common.Interfaces.RootFolder newQudt = ISIS.GME.Common.Classes.RootFolder.GetRootFolder(mgaProject).AttachLibrary("MGA=" + mgaQudtPath);
                            DateTime modtime = System.IO.File.GetLastWriteTimeUtc(mgaQudtPath);
                            ((newQudt as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).RegistryValue["modtime"] =
                                modtime.ToFileTimeUtc().ToString();

                            if (oldQudt != null)
                            {
                                ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(oldQudt, newQudt.Impl, null);
                                sw.UpdateSublibrary();
                                oldQudt.DestroyObject();
                            }
                            ((newQudt as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).LibraryName = "UnitLibrary QUDT";
                            Console.Error.WriteLine((oldQudt == null ? "Attached " : "Refreshed") + " Qudt library.");
                        }
                        #endregion

                        var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                        importer.Initialize(cyPhyMLRootFolder.Impl.Project);
                        importer.ImportFiles(cyPhyMLRootFolder.Impl.Project, libroot, lp_FilesToImport.ToArray(), true);
                        importer.DisposeLogger();
                        bExceptionOccurred = importer.Errors.Count > 0;
                    }, abort: false);

                    mgaProject.Save();

                    if (bExceptionOccurred)
                    {
                        return(-1);
                    }
                }
            }
            finally
            {
                mgaProject.Close(true);
            }
            return(0);
        }
        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);
        }
Exemplo n.º 9
0
        private void AttachLibrary(LibraryInfo libraryInfo)
        {
            string mgaPath = metaPath + "\\" + libraryInfo.MgaName + ".mga";

            if ((project.ProjectStatus & PROJECT_STATUS_OPEN) == PROJECT_STATUS_OPEN)
            {
                if (!File.Exists(mgaPath))
                {
                    GMEConsole.Error.WriteLine("Path '" + mgaPath + "' does not exist. Cannot attach " + libraryInfo.MgaName);
                    return;
                }

                project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_BEGIN);
                try
                {
                    project.BeginTransaction(project.ActiveTerritory);

                    IMgaFolder oldLibFolder = project.RootFolder.ChildFolders.Cast <IMgaFolder>()
                                              .Where(x => string.IsNullOrWhiteSpace(x.LibraryName) == false && (x.Name.Contains(libraryInfo.DisplayName) || x.Name.Contains(libraryInfo.DisplayName))).FirstOrDefault();

                    bool needAttach;
                    if (oldLibFolder == null)
                    {
                        needAttach = true;

                        if (libraryPaths.Contains(Path.GetFullPath(project.ProjectConnStr.Substring("MGA=".Length))))
                        {
                            // Don't attach libraries to themselves
                            needAttach = false;
                        }
                    }
                    else
                    {
                        DateTime oldModTime;
                        long     loldModTime;
                        if (long.TryParse(oldLibFolder.RegistryValue["modtime"], out loldModTime))
                        {
                            oldModTime = DateTime.FromFileTimeUtc(loldModTime);
                        }
                        else
                        {
                            oldModTime = DateTime.MinValue;
                        }
                        needAttach = File.GetLastWriteTimeUtc(mgaPath).CompareTo(oldModTime) > 0;
                        if (!needAttach)
                        {
                            GMEConsole.Info.WriteLine("Library is up-to-date: embedded library modified " + oldModTime.ToString() +
                                                      ", " + libraryInfo.MgaName + " modified " + File.GetLastWriteTimeUtc(mgaPath).ToString());
                        }
                    }

                    if (needAttach)
                    {
                        MgaProject proj = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject"));
                        int        mgaVersion;
                        string     paradigmName;
                        string     paradigmVersion;
                        object     paradigmGuid;
                        bool       readOnly;
                        proj.QueryProjectInfo("MGA=" + mgaPath, out mgaVersion, out paradigmName, out paradigmVersion, out paradigmGuid, out readOnly);

                        Guid guidP1     = ConvertToGUID(paradigmGuid);
                        Guid guidP2     = ConvertToGUID(project.RootMeta.GUID);
                        bool guidsEqual = guidP1.Equals(guidP2);

                        if (paradigmName != project.MetaName || !guidsEqual)
                        {
                            GMEConsole.Info.WriteLine("Skipping refresh of " + libraryInfo.DisplayName + " because it uses a different metamodel version than the current project.");
                            project.AbortTransaction();
                            // not true, but don't try again
                            libraryInfo.attachedLibrary = true;
                            return;
                        }

                        // GMEConsole.Info.WriteLine("Attaching library " + mgaPath);
                        RootFolder newLibFolder = Common.Classes.RootFolder.GetRootFolder(project).AttachLibrary("MGA=" + mgaPath);
                        DateTime   modtime      = File.GetLastWriteTimeUtc(mgaPath);
                        ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).RegistryValue["modtime"] =
                            modtime.ToFileTimeUtc().ToString();

                        if (oldLibFolder != null)
                        {
                            ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(oldLibFolder, newLibFolder.Impl, null);
                            sw.UpdateSublibrary();
                            oldLibFolder.DestroyObject();
                        }
                        ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).LibraryName = libraryInfo.DisplayName;
                        GMEConsole.Info.WriteLine((oldLibFolder == null ? "Attached " : "Refreshed ") + libraryInfo.MgaName + ".mga library.");
                    }
                    project.CommitTransaction();
                }
                catch (Exception e)
                {
                    GMEConsole.Error.WriteLine("Error refreshing library: " + SecurityElement.Escape(e.Message));
                    project.AbortTransaction();
                }
                finally
                {
                    project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_END);
                }

                libraryInfo.attachedLibrary = true;
            }
        }
Exemplo n.º 10
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            GMEConsole.Clear();
            GMEConsole.Out.WriteLine("Running interpreter...");

            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "Json Files (*.json)|*.json";

            var userClickedOK = openFileDialog1.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK == System.Windows.Forms.DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;

                // parse Json
                if (File.Exists(fileName))
                {
                    List <string> materialKeys = new List <string>();
                    using (StreamReader reader = new StreamReader(fileName))
                    {
                        string  materialStr = reader.ReadToEnd();
                        JObject o           = JObject.Parse(materialStr);
                        JObject materialLib = o["Material library"].Value <JObject>();
                        if (materialLib != null)
                        {
                            materialKeys = materialLib.Properties().Select(p => p.Name).ToList();
                        }
                    }


                    // create material folders
                    if (materialKeys.Count() > 0)
                    {
                        int count = rootFolder.ChildFolders.OfType <GME.MGA.MgaFolder>().Where(f => f.MetaBase.Name == "MaterialsDefinition").Count();
                        if (count > 1)
                        {
                            GMEConsole.Error.WriteLine("There should only be 1 materials definition folder!");
                            return;
                        }
                        else if (count < 1)
                        {
                            var       role           = (rootFolder.MetaFolder as MgaMetaFolder).get_LegalChildFolderByName("MaterialsDefinition");
                            MgaFolder materialFolder = rootFolder.CreateFolder(role);
                            materialFolder.Name = "MaterialDefinitions";
                            CreateMaterialObjects(materialFolder,
                                                  materialKeys);
                        }
                        else
                        {
                            MgaFolder materialFolder = rootFolder.ChildFolders.OfType <GME.MGA.MgaFolder>().Where(f => f.MetaBase.Name == "MaterialsDefinition").First();
                            CreateMaterialObjects(materialFolder,
                                                  materialKeys);
                        }
                    }
                }
            }
            else
            {
                return;
            }

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);
        }
Exemplo n.º 11
0
        public void ImportCyberModel(string Cyberpath = null)
        {
            string CyberFilename = "";

            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);

            //  - Display a dialog box to let the user choose their Cyber model file
            bool Cyber_file_chosen = false;

            //bool test_copy_and_path_only = false;
            if (string.IsNullOrWhiteSpace(Cyberpath))
            {
                Cyber_file_chosen = get_Cyber_file(out CyberFilename);
            }
            else
            {
                //test_copy_and_path_only = true;
                CyberFilename = Cyberpath;
                if (File.Exists(CyberFilename))
                {
                    Cyber_file_chosen = true;
                }
                else
                {
                    this.Logger.WriteError("Invalid Cyber file path passed in: " + Cyberpath);
                }
            }

            //  - Run the extractor on the Creo model file
            #region Run the Extractor

            List <string> componentList = new List <string>();
            IMgaProject   project       = (IMgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject"));
            string        compName;
            project.OpenEx("MGA=" + CyberFilename, "CyberComposition", null);
            try
            {
                project.BeginTransactionInNewTerr();
                IMgaFCO currentObj;
                try
                {
                    IMgaFolder  currentFolder = (IMgaFolder)project.RootFolder;
                    IMgaFolders cFolders      = currentFolder.ChildFolders;
                    foreach (IMgaFolder f in cFolders)
                    {
                        if (f.MetaFolder.Name == "Components")
                        {
                            IMgaFCOs objects = f.ChildFCOs;
                            foreach (IMgaFCO o in objects)
                            {
                                componentList.Add("/" + f.Name + "/" + o.Name);
                            }
                        }
                    }
                }
                finally
                {
                    project.CommitTransaction();
                }


                // Adapted from ModelicaImporter.cs
                string result = "";
                using (CyberComponentPicker cyberpicker = new CyberComponentPicker(componentList))
                {
                    var dialogResult = cyberpicker.ShowDialog();
                    if (dialogResult != System.Windows.Forms.DialogResult.OK)
                    {
                        this.Logger.WriteInfo("Modelica import was cancelled by the user.");
                        return;
                    }

                    result = cyberpicker.compResult;
                }

                var halves = result.Split('/');
                compName = halves[1];

                project.BeginTransactionInNewTerr();
                try
                {
                    currentObj = (IMgaFCO)project.RootFolder.ObjectByPath[result];
                }
                finally
                {
                    project.CommitTransaction();
                }

                IMgaComponentEx comp = (IMgaComponentEx)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Interpreter.CyberComponentExporter"));
                comp.Initialize((MgaProject)project);
                comp.InvokeEx((MgaProject)project, (MgaFCO)currentObj, null, 128);

                project.Save();
            }
            finally
            {
                project.Close(true);
            }

            #endregion

            //  - Use a function from CyPhy2ComponentModel to convert the extractor's XML format into a CyPhy model fragment
            #region Convert_to_XML
            // used in creating the resource object below
            CyPhy.CyberModel ProcessedCyberModel = null;

            if (true)
            {
                this.Logger.WriteDebug("About to call DeserializeAvmComponentXml...");
                StreamReader  streamReader = new StreamReader(compName + ".component.acm");
                avm.Component ac_import    = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(streamReader);
                streamReader.Close();
                this.Logger.WriteDebug("... finished DeserializeAvmComponentXml call.");

                foreach (avm.cyber.CyberModel Cybermodel in ac_import.DomainModel.Where(dm => dm is avm.cyber.CyberModel)
                         .Cast <avm.cyber.CyberModel>())
                {
                    var rf = CyPhyClasses.RootFolder.GetRootFolder(CurrentProj);

                    Dictionary <string, CyPhy.Component> avmidComponentMap = new Dictionary <string, CyPhy.Component>();
                    AVM2CyPhyML.CyPhyMLComponentBuilder  newComponent      = new AVM2CyPhyML.CyPhyMLComponentBuilder(rf);
                    ProcessedCyberModel      = newComponent.process(Cybermodel, GetCurrentComp());
                    ProcessedCyberModel.Name = Path.GetFileNameWithoutExtension(CyberFilename);
                }

                // find the largest current Y value so our new elements are added below the existing design elements
                foreach (var child in GetCurrentComp().AllChildren)
                {
                    foreach (MgaPart item in (child.Impl as MgaFCO).Parts)
                    {
                        int    read_x, read_y;
                        string read_str;
                        item.GetGmeAttrs(out read_str, out read_x, out read_y);
                        greatest_current_y = (read_y > greatest_current_y) ? read_y : greatest_current_y;
                    }
                }

                // layout Cyber model to the "south" of existing elements
                foreach (MgaPart item in (ProcessedCyberModel.Impl as MgaFCO).Parts)
                {
                    item.SetGmeAttrs(null, Cyber_MODEL_START_X, greatest_current_y + Cyber_MODEL_START_Y);
                }

                // Extend it's properties out to the component level.
                this.CyberModuleImportExtension(ProcessedCyberModel);
            }

            #endregion

            //  - Copy the Cyber Model files into the component's backend folder
            //      - Note: The solution includes a function that can find this folder using the project.manifest.json file.
            //      - For nice organization, create them in a subfolder called "Cyber"
            // create avmproj
            #region Copy files to backend folder

            // used in creating the resource object below
            string PathforComp = null;

            var importedCyberFiles = new List <String>();
            if (true)
            {
                try
                {
                    // create the destination path
                    PathforComp = GetCurrentComp().GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

                    string finalPathName = Path.Combine(PathforComp, "Cyber");

                    Directory.CreateDirectory(finalPathName);

                    // determine if one part file or all part and assembly files need to be copied
                    string cpsrcfile = System.IO.Path.GetFileName(CyberFilename);

                    // copy the selected file
                    string CyberFileCopyPath = System.IO.Path.Combine(finalPathName, cpsrcfile);
                    System.IO.File.Copy(CyberFilename, CyberFileCopyPath, true);

                    // Set "primary" file as the first in the list.
                    importedCyberFiles.Add(Path.Combine("Cyber", Path.GetFileName(CyberFileCopyPath)));

                    if (true)
                    {
                        // get a string of the XML contents
                        this.Logger.WriteDebug("About to read contents of XML file using class XmlDocument: " + compName + ".component.acm");

                        XmlDocument doc = new XmlDocument();
                        doc.Load(compName + ".component.acm");
                        string xmlcontents = doc.InnerXml;

                        // mine down to the Resource dependencies
                        using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents)))
                        {
                            // iterate through each file listed in the resourcedependency section
                            while (reader.ReadToFollowing("ResourceDependency") == true)
                            {
                                string res_name = reader.GetAttribute("Name");
                                string res_path = reader.GetAttribute("Path");
                                this.Logger.WriteDebug("Copying this file: " + res_path + "\\" + res_name);

                                // Cyber files end in .1 .2 etc. Pick the latest ones
                                var allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*mga." /*n.b. literal dot*/ + "*")
                                               .Select(Path.GetFileName)
                                               .Select(filename => new { basename = filename.Substring(0, filename.LastIndexOf('.')), version = filename.Substring(filename.LastIndexOf('.') + 1) })
                                               .Where(p => { int val; return(Int32.TryParse(p.version, out val)); })
                                               .OrderByDescending(p => Int32.Parse(p.version))
                                               .ToArray();
                                foreach (var basename in allFiles.Select(p => p.basename).Distinct())
                                {
                                    var latest = allFiles.Where(p => p.basename == basename).FirstOrDefault();
                                    if (latest != null)
                                    {
                                        string latestFilename = latest.basename + "." + latest.version;
                                        // Need to limit this down to just the filename in question
                                        // The XML file changes the name to all caps, so compare apples to apples
                                        if (latestFilename.ToUpper().StartsWith(res_name.ToUpper()))
                                        {
                                            string destpathandname = Path.Combine(finalPathName, latestFilename);
                                            if (!importedCyberFiles.Contains(Path.Combine("Cyber", Path.GetFileName(destpathandname))))
                                            {
                                                importedCyberFiles.Add(Path.Combine("Cyber", Path.GetFileName(destpathandname)));
                                            }
                                            File.Copy(Path.Combine(Path.GetDirectoryName(res_path), latestFilename), destpathandname, true);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception err_create_proj)
                {
                    this.Logger.WriteError("Error creating AVM project: " + err_create_proj.Message, " - Extraction Failed. Possible ComponentManagement issue.");
                    //cleanup(tempXMLfile, true);
                    return;
                }
            }
            #endregion

            //  - Create Resource objects in the CyPhy Component model that point to these Cyber Model files
            //      - Note: The "paths" of these should be the relative path from that component's root folder
            if (true)
            {
                foreach (var CyberFile in importedCyberFiles)
                {
                    CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create(GetCurrentComp());
                    ResourceObj.Attributes.ID    = Guid.NewGuid().ToString("B");
                    ResourceObj.Attributes.Path  = CyberFile;
                    ResourceObj.Attributes.Notes = "Cyber Model Import tool added this resource object for the imported Cyber file";
                    ResourceObj.Name             = Path.GetFileName(CyberFile);

                    // layout Resource just to the side of the Cyber model
                    foreach (MgaPart item in (ResourceObj.Impl as MgaFCO).Parts)
                    {
                        item.SetGmeAttrs(null, RESOURCE_START_X, greatest_current_y + RESOURCE_START_Y);
                    }

                    // The "primary" Cyber model is the first one -- associate it with the CyPhy CyberModel object
                    if (importedCyberFiles.IndexOf(CyberFile) == 0)
                    {
                        //  - Create a UsesResource association between the CyPhy CyberModel object and the Resource object that represents the top-level Creo Model file.
                        CyPhyClasses.UsesResource.Connect(ResourceObj, ProcessedCyberModel, null, null, GetCurrentComp());
                    }
                }
            }

            // throw in an ACM file for the current state of the component.
            if (true)
            {
                var    exporter = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter();
                String acmPath  = Path.Combine(PathforComp, GetCurrentComp().Name + ".component.acm");
                CyPhyComponentExporterInterpreter.ExportToFile(GetCurrentComp(), Path.GetDirectoryName(acmPath));
            }

            // Clean up
            //cleanup(tempXMLfile, true);
        }
Exemplo n.º 12
0
        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);
            }
        }
Exemplo n.º 13
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // This is the main ShowNet interpreter code
            Boolean ownLogger = false;

            if (Logger == null)
            {
                ownLogger = true;
                Logger    = new CyPhyGUIs.GMELogger(project, "ShowNet");
            }
            GMEConsole.Out.WriteLine("\n======================================================================================================================================\n");
            Logger.WriteInfo("Starting ShowNet.");

            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;
            //GMEConsole.Out.WriteLine(rootFolder.Name);

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            bool done = false;

            if ((!done) && (null == currentobj))
            {
                done = true;
                Logger.WriteError("The current object is null.  Please select a ComponentAssembly or DesignContainer object.");
            }

            if ((!done) && (currentobj.Meta.Name != "ComponentAssembly" &&
                            currentobj.Meta.Name != "DesignContainer"))
            {
                done = true;
                Logger.WriteError("ShowNet only works on ComponentAssembly and DesignContainer objects.");
                Logger.WriteError("But, {1} is neither; it is a {0}.", currentobj.Meta.Name, currentobj.Name);
            }

            if (!done)
            {
                IEnumerable <CyPhy.PortComposition>      portCompositionChildren      = null;
                IEnumerable <CyPhy.ConnectorComposition> connectorCompositionChildren = null;

                if (currentobj.Meta.Name == "ComponentAssembly")
                {
                    var componentAssembly = ISIS.GME.Dsml.CyPhyML.Classes.ComponentAssembly.Cast(currentobj);
                    portCompositionChildren      = componentAssembly.Children.PortCompositionCollection;
                    connectorCompositionChildren = componentAssembly.Children.ConnectorCompositionCollection;
                }
                else if (currentobj.Meta.Name == "DesignContainer")
                {
                    var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(currentobj);
                    portCompositionChildren      = designContainer.Children.PortCompositionCollection;
                    connectorCompositionChildren = designContainer.Children.ConnectorCompositionCollection;
                }

                //=================================================================
                // Process the port connections
                //=================================================================

                NetworkManager portNetworkManager = new NetworkManager();

                foreach (CyPhy.PortComposition port in portCompositionChildren)
                {
                    Endpoint dstEndPoint = new Endpoint(port.DstEnd, port.GenericDstEndRef);
                    Endpoint srcEndPoint = new Endpoint(port.SrcEnd, port.GenericSrcEndRef);

                    //GMEConsole.Out.WriteLine("Found port: dst = '{0}' in the '{1}' {2}.",
                    //    dstEndPoint.Name,
                    //    dstEndPoint.ParentName,
                    //    dstEndPoint.ParentKind);

                    //GMEConsole.Out.WriteLine("            src = '{0}' in the '{1}' {2}.",
                    //    srcEndPoint.Name,
                    //    srcEndPoint.ParentName,
                    //    srcEndPoint.ParentKind);

                    // Create a network from the endpoints
                    List <Endpoint> nodes = new List <Endpoint>()
                    {
                        srcEndPoint, dstEndPoint
                    };
                    Network newNetwork = new Network(nodes);
                    portNetworkManager.Add(newNetwork);
                }

                //=================================================================
                // Process the connector connections
                //=================================================================

                NetworkManager connectorNetworkManager = new NetworkManager();

                foreach (CyPhy.ConnectorComposition connector in connectorCompositionChildren)
                {
                    Endpoint dstEndPoint = new Endpoint(connector.DstEnd, connector.GenericDstEndRef);
                    Endpoint srcEndPoint = new Endpoint(connector.SrcEnd, connector.GenericSrcEndRef);

                    // Create a network from the endpoints
                    List <Endpoint> nodes = new List <Endpoint>()
                    {
                        srcEndPoint, dstEndPoint
                    };
                    Network newNetwork = new Network(nodes);
                    connectorNetworkManager.Add(newNetwork);
                }

                // Make sure the network names are unique.
                NetworkNameChecker.Init();
                NetworkNameChecker.Update(ref portNetworkManager.NetworkList);
                NetworkNameChecker.Update(ref connectorNetworkManager.NetworkList);

                // Display all the networks.

                Logger.WriteInfo(string.Format("===== Found {0} port networks on {1}: =====\n",
                                               portNetworkManager.NetworkList.Count,
                                               currentobj.Name));

                foreach (Network mergedNet in portNetworkManager.NetworkList)
                {
                    using (StringReader sr = new StringReader(mergedNet.ToString()))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            GMEConsole.Out.WriteLine(line);
                        }
                    }
                }

                Logger.WriteInfo(string.Format("===== Found {0} connector networks on {1}: =====\n",
                                               connectorNetworkManager.NetworkList.Count,
                                               currentobj.Name));

                foreach (Network mergedNet in connectorNetworkManager.NetworkList)
                {
                    using (StringReader sr = new StringReader(mergedNet.ToString()))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            GMEConsole.Out.WriteLine(line);
                        }
                    }
                }
            }

            Logger.WriteInfo("The ShowNet interpreter has finished.");

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
Exemplo n.º 14
0
        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);
        }