Beispiel #1
0
        public static bool GetConfigurations(string projectPath, string absPath)
        {
            bool result = false;

            Assert.True(File.Exists(projectPath), "Project file does not exist.");
            string ProjectConnStr = "MGA=" + Path.GetFullPath(projectPath);

            MgaProject project = new MgaProject();

            project.OpenEx(ProjectConnStr, "CyPhyML", null);
            try
            {
                var terr    = project.BeginTransactionInNewTerr();
                var testObj = project.ObjectByPath[absPath] as MgaFCO;
                project.AbortTransaction();

                using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project))
                {
                    IMgaFCOs configurations = null;

                    Assert.ThrowsDelegate d = () =>
                    {
                        configurations = masterInterpreter.GetConfigurations(testObj as MgaModel);
                    };

                    Assert.DoesNotThrow(d);
                }
            }
            finally
            {
                project.Close(true);
            }

            return(result);
        }
Beispiel #2
0
        private static IMgaFCOs GetRefChain(IMgaReference reference)
        {
            IMgaFCOs ret = (IMgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));

            ret.Append(reference as MgaFCO);
            while (true)
            {
                if (reference.Referred == null)
                {
                    break;
                }
                if (reference.Referred.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_REFERENCE)
                {
                    reference = reference.Referred as IMgaReference;
                    ret.Append(reference as MgaFCO);
                }
                else
                {
                    break;
                }
            }
            return(ret);
        }
Beispiel #3
0
        private static Dictionary <string, IMgaFCO> GetNameMap(IMgaFCOs fcos,
                                                               Action <string> warnFunc)
        {
            Dictionary <string, IMgaFCO> refeChildren;

            refeChildren = new Dictionary <string, IMgaFCO>();
            foreach (IMgaFCO refeChild in fcos.Cast <IMgaFCO>())
            {
                if (refeChild.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION)
                {
                    continue;
                }
                if (refeChildren.ContainsKey(refeChild.Name))
                {
                    warnFunc(refeChild.Name);
                    refeChildren[refeChild.Name] = null;
                }
                else
                {
                    refeChildren.Add(refeChild.Name, refeChild);
                }
            }
            return(refeChildren);
        }
        /// <summary>
        /// Resolves all possible variations of configuration specification.
        /// </summary>
        /// <param name="configurations">Contains a set of Component Assembly, CWC, Configurations.</param>
        /// <returns>List of CWC and Component Assembly</returns>
        private MgaFCOs ResolveConfigurations(IMgaFCOs configurations)
        {
            MgaFCOs results = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));

            foreach (MgaFCO configuration in configurations)
            {
                foreach (MgaFCO config in this.ResolveConfiguration(configuration))
                {
                    results.Append(config);
                }
            }

            return results;
        }
        /// <summary>
        /// All RunInTransaction public functions should end up calling this function.
        /// It checks all constraints and initializes the variables.
        /// <para><remarks>Execute outside of transactions.</remarks></para>
        /// </summary>
        /// <param name="context">Master interpreter runs on this model.</param>
        /// <param name="configurations">Configurations to run the context with.</param>
        /// <param name="postToJobManager">True posts all jobs to the job manager.</param>
        /// <param name="keepTempModels">The interpreter will keep all temporary models.</param>
        /// <returns>Results that represent, which configurations where successful and which ones failed.</returns>
        /// <exception cref="ArgumentNullException" />
        /// <exception cref="InvalidOperationException" />
        /// <exception cref="ExecutionCanceledByUserException" />
        public MasterInterpreterResult[] RunInTransactionOnMultipleConfigs(
            IMgaModel context,
            IMgaFCOs configurations,
            bool postToJobManager = false,
            bool keepTempModels = false)
        {
            if (context == null ||
                configurations == null)
            {
                throw new ArgumentNullException();
            }

            this.Logger.WriteDebug("Start main method for master interpreter.");

            this.Logger.WriteDebug("Start copying dashboard sync.");
            this.copyDashboard.Invoke();

            if (this.ProjectManifest == null)
            {
                this.ExecuteInTransaction(context, () =>
                {
                    this.ProjectManifest = this.CreateOrUpdateProjectManifest(context.Project);
                });
            }

            string projectPath = this.ProjectManifest.OutputDirectory;
            this.Logger.WriteDebug("Project directory: {0}", projectPath);

            // delete all previous interpreter configurations
            this.interpreterConfigurations.Clear();

            var results = new List<MasterInterpreterResult>();

            IMgaFCOs resolvedConfigurations = this.ResolveConfigurations(configurations);

            if (resolvedConfigurations.Count == 0)
            {
                this.Logger.WriteInfo("Configurations were not specified. Use all configurations for the given context.");
                resolvedConfigurations = this.GetConfigurations(context);
            }

            var count = 0;
            this.ExecuteInTransaction(context, () =>
            {
                count = resolvedConfigurations.Count;
            });

            var currentNumber = 0;

            this.Logger.WriteInfo("Number of configurations to execute: {0}", count);

            this.ExecuteInTransaction(context, () =>
            {
                this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs()
                {
                    Percent = 0,
                    Context = context.Name,
                    Title = "Starting"
                });
            });

            this.Logger.WriteDebug("Wait for dashboard copy to finish");
            this.Logger.WriteDebug("Dashboard copy finished");

            this.ExecuteInTransaction(context, () =>
            {
                this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs()
                {
                    Percent = 1,
                    Context = context.Name,
                    Title = "Updating local dashboard"
                });
            });

            int successes = 0;
            int failures = 0;

            foreach (MgaFCO configuration in resolvedConfigurations)
            {
                if (this.IsCancelled)
                {
                    this.Logger.WriteWarning("Execution was cancelled.");
                    break;
                }

                this.Logger.WriteDebug("Processing {0} out of {1} [{2} success(es) and {3} failure(s)]", currentNumber + 1, count, successes, failures);

                this.ExecuteInTransaction(context, () =>
                {
                    this.Logger.WriteDebug("Configuration {0}", configuration.AbsPath);

                    this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs()
                    {
                        Percent = currentNumber * 99 / count,
                        Context = context.Name,
                        Configuration = configuration.Name,
                        Title = string.Format("Processing {0} out of {1} [{2} success(es) and {3} failure(s)]", currentNumber + 1, count, successes, failures)
                    });
                });

                this.Logger.WriteDebug("Starting analysis model processor");
                var thisResult = this.RunAnalysisModelProcessors(context, configuration, postToJobManager, keepTempModels);

                this.Logger.WriteDebug("Analysis model processor is done");

                results.Add(thisResult);
                currentNumber++;

                if (thisResult.Success)
                {
                    successes++;
                }
                else
                {
                    failures++;
                }
            }

            this.Logger.WriteDebug("Generate dashboard script files");
            this.GenerateDashboardScriptFiles();
            this.Logger.WriteDebug("Dashboard script files generated");

            this.ExecuteInTransaction(context, () =>
            {
                this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs()
                {
                    Percent = 100,
                    Context = context.Name,
                    Title = "Finished"
                });
            });

            this.Results = results.ToArray();

            return this.Results;
        }
Beispiel #6
0
        public IMgaFCOs ImportFiles(MgaProject project, string projRootPath, string[] FileNames, bool alwaysReplace = false, bool doNotReplaceAll = false)
        {
            Boolean b_CLMAddOnStatus = META.ComponentLibraryManagerAddOn.GetEnabled(project);

            META.ComponentLibraryManagerAddOn.Enable(false, project);
            var addons = project.AddOnComponents.Cast <IMgaComponentEx>();

            foreach (var addon in addons)
            {
                if (addon.ComponentName.ToLowerInvariant() == "CyPhyAddOn".ToLowerInvariant())
                {
                    addon.ComponentParameter["DontAssignGuidsOnNextTransaction".ToLowerInvariant()] = true;
                }
            }

            IMgaFCOs importedComponents = (IMgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));

            try
            {
                bool             replaceAll = alwaysReplace;
                CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);
                Dictionary <string, CyPhy.Component> avmidComponentMap = getCyPhyMLComponentDictionary_ByAVMID(rootFolder);
                Dictionary <string, CyPhy.Component> nameComponentMap  = getCyPhyMLComponentDictionary_ByName(rootFolder);
                Boolean b_FirstComponent = true;

                foreach (String inputFile in FileNames)
                {
                    var inputFilePath = inputFile;

                    /* Disable validation for now
                     #region Check validation rules
                     *
                     * var errorMessages = new List<string>();
                     * ComponentImportRules.CheckUniqueNames(inputXMLFile, ref errorMessages);
                     * var isValid = ComponentImportRules.ValidateXsd(inputXMLFile, ref errorMessages);
                     *
                     * foreach (var errorMessage in errorMessages)
                     * {
                     *  GMEConsole.Error.WriteLine(errorMessage);
                     * }
                     *
                     * if (!isValid)
                     * {
                     *  GMEConsole.Info.WriteLine("XML is not valid. Skip file: {0}", inputXMLFile);
                     *  continue;
                     * }
                     #endregion
                     */

                    GMEConsole.Info.WriteLine("Importing {0}", inputFilePath);

                    // If ZIP file, unzip it to a temporary directory, then import as usual
                    UnzipToTemp unzip       = null;
                    bool        bZipArchive = (Path.GetExtension(inputFilePath) == ".zip");
                    if (bZipArchive)
                    {
                        unzip = new UnzipToTemp(GMEConsole);
                        List <string> entries = unzip.UnzipFile(inputFilePath);
                        inputFilePath = entries.Where(entry => Path.GetDirectoryName(entry) == "" && entry.EndsWith(".acm")).FirstOrDefault();
                        if (inputFilePath != null)
                        {
                            inputFilePath = Path.Combine(unzip.TempDirDestination, inputFilePath);
                        }
                    }

                    using (unzip)
                        try
                        {
                            if (inputFilePath == null) // may be null if .zip didn't contain .acm
                            {
                                throw new FileNotFoundException("No ACM file not found in root directory of ZIP file.");
                            }
                            avm.Component ac_import = null;

                            /* META-3003: Check for old-style ITAR statement */
                            bool isDistributionD = false;
                            bool isNotItar       = false;

                            #region Check for old-style ITAR statements

                            XmlDocument doc = new XmlDocument();
                            doc.Load(inputFilePath);
                            XmlNode root = doc.DocumentElement;

                            XmlNodeList nodeList = root.SelectNodes("//*[local-name()='DistributionRestriction' and @Level='ITARDistributionD']");
                            if (nodeList.Count > 0)
                            {
                                isDistributionD = true;
                            }
                            else
                            {
                                nodeList = root.SelectNodes("//*[local-name()='DistributionRestriction' and @Level='NotITAR']");
                                if (nodeList.Count > 0)
                                {
                                    isNotItar = true;
                                }
                            }

                            #endregion

                            using (StreamReader streamReader = new StreamReader(inputFilePath))
                            {
                                ac_import = DeserializeAvmComponentXml(streamReader);
                            }
                            if (ac_import == null)
                            {
                                throw new Exception("Could not load ACM file.");
                            }

                            /* Throw warning if from an unexpected schema version */
                            CheckAndWarnOnSchemaVersion(ac_import);

                            /* META-3003: Strip old-style ITAR statement */
                            #region Strip old-style ITAR statements

                            if (isDistributionD)
                            {
                                // Correct this.
                                if (ac_import.DistributionRestriction == null)
                                {
                                    ac_import.DistributionRestriction = new List <avm.DistributionRestriction>();
                                }

                                ac_import.DistributionRestriction.Add(new avm.DoDDistributionStatement()
                                {
                                    Type = DoDDistributionStatementEnum.StatementD
                                });
                            }
                            else if (isNotItar)
                            {
                                var itar = ac_import.DistributionRestriction.OfType <avm.ITAR>().FirstOrDefault();
                                if (itar != null)
                                {
                                    ac_import.DistributionRestriction.Remove(itar);
                                }
                            }

                            #endregion

                            String acmDir = Path.GetDirectoryName(inputFilePath);

                            #region File Management

                            // Create a new backend folder
                            String compDirAbsPath = META.ComponentLibraryManager.CreateComponentFolder(project);
                            String compDirRelPath = MetaAvmProject.MakeRelativePath(projRootPath, compDirAbsPath);

                            // Copy the ACM file to the new path
                            String newACMRelPath = Path.Combine(compDirRelPath, ac_import.Name + ".acm");
                            string newACMAbsPath = Path.Combine(compDirAbsPath, ac_import.Name + ".acm");
                            File.Copy(inputFilePath, newACMAbsPath, true);

                            // Now we have to copy in his resources
                            foreach (var resource in ac_import.ResourceDependency)
                            {
                                try
                                {
                                    var dirRelPath = Path.GetDirectoryName(resource.Path);
                                    var dirAbsPath = Path.Combine(compDirAbsPath, dirRelPath);

                                    var orgAbsPath = Path.Combine(acmDir, resource.Path);
                                    var dstAbsPath = Path.Combine(compDirAbsPath, resource.Path);

                                    Directory.CreateDirectory(dirAbsPath);
                                    File.Copy(orgAbsPath, dstAbsPath, true);
                                }
                                catch (FileNotFoundException)
                                {
                                    var message = String.Format("This Component depends on a file which cannot be found in the Component package: {0}", resource.Path);
                                    GMEConsole.Warning.WriteLine(message);
                                }
                                catch (DirectoryNotFoundException)
                                {
                                    var message = String.Format("This Component depends on a file which cannot be found in the Component package: {0}", resource.Path);
                                    GMEConsole.Warning.WriteLine(message);
                                }
                                catch (PathTooLongException)
                                {
                                    var message = String.Format("This Component has a Resource that results in a path that is too long: {0}", resource.Path);
                                    GMEConsole.Warning.WriteLine(message);
                                }
                                catch (NotSupportedException)
                                {
                                    var message = String.Format("This Component has a Resource that could not be loaded: {0}", resource.Path);
                                    GMEConsole.Warning.WriteLine(message);
                                }
                                catch (Exception ex)
                                {
                                    var message = String.Format("Exception while copying Resource {0}: {1}", resource.Path, ex);
                                    GMEConsole.Warning.WriteLine(message);
                                }
                            }
                            #endregion

                            CyPhy.ComponentAssembly cyPhyMLComponentAssembly = null;
                            CyPhy.Components        cyPhyMLComponentsFolder  = null;

                            CyPhy.Component cyPhyReplaceComponent = null;

                            #region Search for Components that should be Replaced by this new one
                            bool replaceeFound = false;
                            if (ac_import.ID != null)
                            {
                                replaceeFound = avmidComponentMap.TryGetValue(ac_import.ID, out cyPhyReplaceComponent);
                            }
                            if (replaceeFound == false)
                            {
                                replaceeFound = nameComponentMap.TryGetValue(ac_import.Name, out cyPhyReplaceComponent);
                            }
                            if (replaceeFound)
                            {
                                bool replace = false;
                                if (!doNotReplaceAll && !replaceAll)
                                {
                                    // Present dialog to see if user wants to replace component with AVMID avmid
                                    // Maybe have a "do all" checkbox (which sets "replaceAll" to "true") if many items are being imported.
                                    // If yes, replace = true;

                                    String s_ExistingName     = cyPhyReplaceComponent.Name;
                                    String s_ExistingAVMID    = cyPhyReplaceComponent.Attributes.AVMID;
                                    String s_ExistingVersion  = cyPhyReplaceComponent.Attributes.Version;
                                    String s_ExistingRevision = cyPhyReplaceComponent.Attributes.Revision;

                                    String s_ExistingDescriptor = cyPhyReplaceComponent.Name;
                                    if (s_ExistingAVMID != "")
                                    {
                                        s_ExistingDescriptor += "\nAVM ID: " + s_ExistingAVMID;
                                    }
                                    if (s_ExistingVersion != "")
                                    {
                                        s_ExistingDescriptor += "\nVersion: " + s_ExistingVersion;
                                    }
                                    if (s_ExistingRevision != "")
                                    {
                                        s_ExistingDescriptor += "\nRevision: " + s_ExistingRevision;
                                    }

                                    String s_NewName = ac_import.Name;
                                    //String s_NewAVMID = ac_import.AVMID;
                                    String s_NewVersion = ac_import.Version;
                                    //String s_NewRevision = ac_import.Revision;

                                    String s_NewDescriptor = ac_import.Name;
                                    //if (s_NewAVMID != "")
                                    //    s_NewDescriptor += "\nAVM ID: " + s_NewAVMID;
                                    if (s_NewVersion != "")
                                    {
                                        s_NewDescriptor += "\nVersion: " + s_NewVersion;
                                    }
                                    //if (s_NewRevision != "")
                                    //    s_NewDescriptor += "\nRevision: " + s_NewRevision;

                                    String s_MessageBoxPromptTemplate = "Would you like to replace\n\n{0}\n\nwith\n\n{1}";
                                    String s_MessageBoxPrompt         = String.Format(s_MessageBoxPromptTemplate, s_ExistingDescriptor, s_NewDescriptor);

                                    using (UpdatePrompt up = new UpdatePrompt())
                                    {
                                        up.DialogText.Text = s_MessageBoxPrompt;
                                        up.ShowDialog();

                                        if (up.DialogResult == DialogResult.Cancel ||
                                            up.DialogResult == DialogResult.None)
                                        {
                                            // Skip this component; Continues the "foreach" loop above.
                                            GMEConsole.Error.WriteLine("Import canceled for {0}", inputFile);
                                            continue;
                                        }

                                        Dictionary <DialogResult, string> d_TranslateResult = new Dictionary <DialogResult, string>()
                                        {
                                            { DialogResult.OK, "Replace" },
                                            { DialogResult.Abort, "Import as New" },
                                        };

                                        if (d_TranslateResult[up.DialogResult] == "Replace")
                                        {
                                            replace = true;
                                            if (up.applyToAll.Checked)
                                            {
                                                replaceAll = true;
                                            }
                                        }
                                        else if (d_TranslateResult[up.DialogResult] == "Import as New")
                                        {
                                            if (up.applyToAll.Checked)
                                            {
                                                doNotReplaceAll = true;
                                            }
                                        }
                                    }
                                }

                                if (!replace && !replaceAll || doNotReplaceAll)
                                {
                                    cyPhyReplaceComponent = null;
                                }
                            }
                            #endregion

                            if (cyPhyReplaceComponent != null)
                            {
                                Object replaceComponentParent = cyPhyReplaceComponent.ParentContainer;
                                if (replaceComponentParent is CyPhy.ComponentAssembly)
                                {
                                    cyPhyMLComponentAssembly = replaceComponentParent as CyPhy.ComponentAssembly;
                                }
                                else
                                {
                                    cyPhyMLComponentsFolder = replaceComponentParent as CyPhy.Components;
                                }
                            }
                            else
                            {
                                cyPhyMLComponentsFolder = GetImportFolder(rootFolder);
                            }

                            // The importer uses a map to resolve unit references.
                            // If this is our second run, we shouldn't waste time rebuilding it.
                            Boolean b_ResetUnitMap;
                            if (b_FirstComponent)
                            {
                                b_ResetUnitMap = true;
                            }
                            else
                            {
                                b_ResetUnitMap = false;
                            }

                            CyPhy.Component c = null;
                            if (cyPhyMLComponentAssembly != null)
                            {
                                c = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cyPhyMLComponentAssembly, ac_import, b_ResetUnitMap, GMEConsole);
                            }
                            else
                            {
                                c = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cyPhyMLComponentsFolder, ac_import, b_ResetUnitMap, GMEConsole);
                            }

                            if (c != null)
                            {
                                importedComponents.Append(c.Impl as MgaFCO);
                                c.Attributes.Path = compDirRelPath;
                            }

                            if (cyPhyReplaceComponent != null)
                            {
                                foreach (IMgaReference reference in (cyPhyReplaceComponent.Impl as IMgaFCO).ReferencedBy)
                                {
                                    ReferenceSwitcher.Switcher.MoveReferenceWithRefportConnections(c.Impl as IMgaFCO, reference, WriteLine);
                                }
                                cyPhyReplaceComponent.Delete();
                            }

                            // If icon available, set it in Preferences.
                            // Relative paths here are from our project root.
                            var iconResource = ac_import.ResourceDependency.Where(x => x.Path.Contains("Icon.png")).FirstOrDefault();
                            //foreach (AVM.File file in ac_import.Files)
                            //{
                            //    if (file.Location.Contains("Icon.png"))
                            //        iconRelativePath = componentModelRelativePath + "/" + file.Location;
                            //}
                            if (iconResource != null)
                            {
                                var iconRelativePath = Path.Combine(compDirRelPath, iconResource.Path);

                                // Remove leading "\"
                                if (iconRelativePath.IndexOf("\\") == 0)
                                {
                                    iconRelativePath = iconRelativePath.Remove(0, 1);
                                }

                                // Shrink double backslash to single
                                iconRelativePath = iconRelativePath.Replace("\\\\", "\\");

                                // Replace / with \
                                iconRelativePath = iconRelativePath.Replace('/', '\\');

                                // If icon exists, set it
                                if (System.IO.File.Exists(iconRelativePath))
                                {
                                    // Set "icon" regnode
                                    (c.Impl as GME.MGA.IMgaFCO).set_RegistryValue("icon", iconRelativePath);
                                }
                            }
                            GMEConsole.Info.WriteLine("Imported {0} to <a href=\"mga:{2}\">{1}</a>", inputFile, SecurityElement.Escape(c.Name), c.ID);
                        }
                        catch (Exception ex)
                        {
                            string error = string.Format("{0} while importing {1}: {2}", ex.GetType().Name, inputFile, ex.Message);
                            GMEConsole.Error.WriteLine(error);
                            this.Errors.Add(error);
                            GMEConsole.Error.WriteLine(ex.StackTrace);
                        }
                    finally
                    {
                    }
                    b_FirstComponent = false;
                }
            }
            finally
            {
                // Reset the "enabled" state of the CLM AddOn
                META.ComponentLibraryManagerAddOn.Enable(b_CLMAddOnStatus, project);
            }

            return(importedComponents);
        }
Beispiel #7
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);
        }
        //[Fact]
        public void TestCodeSample()
        {
            string ProjectConnStr;

            MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr);

            MgaProject project = new MgaProject();
            bool       ro_mode;

            project.Open(ProjectConnStr, out ro_mode);

            MgaHelper.CheckParadigmVersionUpgrade(project);

            try
            {
                List <IMgaFCO> objectsToGetConfigurations = null;

                project.BeginTransactionInNewTerr();
                try
                {
                    // discover objects

                    var allObjects = project
                                     .RootFolder
                                     .ChildFolders
                                     .Cast <MgaFolder>()
                                     .Where(x => x.Name.StartsWith("0"))
                                     .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>())
                                     .Where(x => x.RootFCO == x);

                    // get all objects from folders starts with 0 within the root folder.
                    objectsToGetConfigurations = allObjects.Where(x => x.AbsPath.Contains("TestingGetConfigurations")).ToList();

                    objectsToGetConfigurations.Sort((x, y) =>
                    {
                        return(x.Meta.Name.CompareTo(y.Meta.Name) != 0 ?
                               x.Meta.Name.CompareTo(y.Meta.Name) :
                               x.AbsPath.CompareTo(y.AbsPath));
                    });
                }
                finally
                {
                    project.AbortTransaction();
                }

                Assert.True(objectsToGetConfigurations != null, "There are no object in the project that has to be checked.");

                int numContexts = objectsToGetConfigurations.Count;
                int numSuccess  = 0;
                int numFailures = 0;

                bool success = true;

                foreach (var subject in objectsToGetConfigurations)
                {
                    // single test
                    using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project))
                    {
                        IMgaFCOs configurations = null;

                        Assert.ThrowsDelegate d = () =>
                        {
                            configurations = masterInterpreter.GetConfigurations(subject as MgaModel);
                        };

                        Assert.DoesNotThrow(d);
                        //Assert.True(configurations != null, "GetConfiguration returned with null.");

                        if (configurations == null)
                        {
                            numFailures++;
                        }
                        else
                        {
                            numSuccess++;
                        }

                        // print out nicely in the GME console
                        project.BeginTransactionInNewTerr();
                        try
                        {
                            Console.Out.WriteLine("{0} [{1}] has {2} configurations.", subject.Name, subject.Meta.Name, configurations.Count);
                            foreach (IMgaFCO configuration in configurations)
                            {
                                Console.Out.WriteLine(" > {0} - {1}", configuration.Name, configuration.ID);
                            }
                        }
                        finally
                        {
                            project.AbortTransaction();
                        }
                    }
                }

                if (success)
                {
                    Console.Out.WriteLine("[OK] Got configurations for: {0} test benches. Success: {1}, Failed {2}", numContexts, numSuccess, numFailures);
                }
                else
                {
                    Console.Error.WriteLine("[FAILED] Tried to get configurations for: {0} test benches. Success: {1}, Failed {2}", numContexts, numSuccess, numFailures);
                }

                Assert.True(success, "At least one context was failed to check against the expected results.");
            }
            finally
            {
                project.Close(true);
            }
        }