예제 #1
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                MgaGateway = new MgaGateway(project);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                }, abort: false);
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #2
0
        public void ZipIsMissingACM()
        {
            var zipPath = Path.Combine(testPath, "TestModel_noACM.zip");

            var mgaProject = Common.GetProject(mgaPath);

            Assert.False(mgaProject == null, "Could not load MGA project.");

            var mgaGateway = new MgaGateway(mgaProject);

            mgaGateway.PerformInTransaction(delegate
            {
                var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                importer.Initialize(mgaProject);

                try
                {
                    var result = importer.ImportFile(mgaProject, testPath, zipPath);
                }
                finally
                {
                    importer.DisposeLogger();
                }
            });
        }
예제 #3
0
        public void ImportCADZIP_Spring_Tungsten()
        {
            var zipPath = Path.Combine(testPath, "Spring_Tungsten.zip");

            // Import the ZIP file.
            // Check that we run without exception, have a manifest file,
            // have a folder for the component, and have 2 files in there.

            // Delete manifest and any subfolders
            File.Delete(manifestFilePath);
            if (Directory.Exists(Path.Combine(testPath, "components")))
            {
                Directory.Delete(Path.Combine(testPath, "components"), true);
            }

            var mgaProject = Common.GetProject(mgaPath);

            Assert.True(mgaProject != null, "Could not load MGA project.");

            var mgaGateway = new MgaGateway(mgaProject);

            mgaGateway.PerformInTransaction(delegate
            {
                var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                importer.Initialize(mgaProject);

                var result   = importer.ImportFile(mgaProject, testPath, zipPath);
                var tungsten = result.ChildObjects.Cast <IMgaFCO>().Where(x => x.Meta.Name == "Resource" && x.Name == "TUNGSTEN_SPRING.PRT").FirstOrDefault();
                Assert.Equal("CAD\\TUNGSTEN_SPRING.PRT", tungsten.StrAttrByName["Path"]);
            });
        }
예제 #4
0
        public List <TestBench> GetTestbenchesFromModel(MgaProject project, MgaModel currentobj, string outputBaseDir)
        {
            componentParameters = null;
            //this.logFileName = Path.Combine(
            //    Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)),
            //    "log",
            //    this.ComponentName + "." + System.Diagnostics.Process.GetCurrentProcess().Id + ".log");
            //META.Logger.AddFileListener(this.logFileName, this.ComponentName, project);

            // GMEConsole = GMEConsole.CreateFromProject(project);
            bool disposeLogger = false;

            if (this.Logger == null)
            {
                this.Logger   = new GMELogger(project, this.ComponentName);
                disposeLogger = true;
            }
            MgaGateway = new MgaGateway(project);
            MgaGateway.PerformInTransaction(delegate
            {
                this._GetTestbenchesFromModel(currentobj, outputBaseDir);
            });

            if (this.Logger != null && disposeLogger)
            {
                this.Logger.Dispose();
                this.Logger = null;
            }
            //META.Logger.RemoveFileListener(this.ComponentName);

            return(this.TestBenches);
        }
예제 #5
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                });
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #6
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            gmeConsole.Out.WriteLine("Running Subtree Merge Utility ...");

            string[]     FileNames = null;
            DialogResult dr;

            using (OpenFileDialog ofd = new OpenFileDialog()) {
                ofd.CheckFileExists = true;
                ofd.DefaultExt      = "mga";
                ofd.Multiselect     = false;
                ofd.Filter          = "mga files (*.mga)|*.mga|All files (*.*)|*.*";

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    FileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                MgaGateway.PerformInTransaction(delegate {
                    SubTreeMerge subTreeMerge = new SubTreeMerge();
                    subTreeMerge.gmeConsole   = gmeConsole;
                    subTreeMerge.merge(currentobj, FileNames[0]);
                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);
                return;
            }
            else
            {
                gmeConsole.Warning.WriteLine("Subtree Merge Utility cancelled");
                return;
            }
        }
예제 #7
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #8
0
        public ValueFlowTestFixture()
        {
            String connectionString;

            GME.MGA.MgaUtils.ImportXMEForTest(path_XME, out connectionString);

            Boolean ro_mode;

            Project = new MgaProject();
            Project.Open(connectionString, out ro_mode);
            Project.EnableAutoAddOns(true);

            MgaFilter filter = Project.CreateFilter();

            filter.Kind = "Component";
            filter.Name = "ValueFlow";

            var mgaGateway = new MgaGateway(Project);

            mgaGateway.PerformInTransaction(delegate
            {
                ValueFlow = Project.AllFCOs(filter)
                            .Cast <MgaFCO>()
                            .Select(x => CyPhyC.Component.Cast(x))
                            .First();

                RunFormulaEvaluator(ValueFlow.Impl as MgaFCO);
            },
                                            transactiontype_enum.TRANSACTION_GENERAL,
                                            abort: false);
        }
예제 #9
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                MgaGateway  = new MgaGateway(project);
                this.Logger = new CyPhyGUIs.GMELogger(project, this.GetType().Name);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                }, abort: false);
            }
            finally
            {
                if (Logger != null)
                {
                    Logger.Dispose();
                }
                MgaGateway   = null;
                Logger       = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #10
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            if (currentobj == null)
            {
                MessageBox.Show("Please select the subtree to be replaced (via merge) so that it is displayed in the main window.");
                return;
            }

            currentMgaProject = project;

            try
            {
                gmeConsole = new FlexConsole(FlexConsole.ConsoleType.GMECONSOLE, project);
                MgaGateway = new MgaGateway(project);

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                gmeConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #11
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                MgaGateway = new MgaGateway(project);

                MgaGateway.BeginTransaction(transactiontype_enum.TRANSACTION_NON_NESTED);
                try
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                }
                finally
                {
                    MgaGateway.AbortTransaction();
                }
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #12
0
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            var result = new InterpreterResult();

            result.RunCommand = "runCarSim.bat";
            try
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    if (parameters.CurrentFCO.MetaBase.Name == "CarTestBench")
                    {
                        try
                        {
                            var elaborator    = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter();
                            elaborator.Logger = new GMELogger(parameters.Project);
                            //elaborator.Logger.AddWriter(Logger.Instance);
                            var elaboratorresult = elaborator.RunInTransaction(parameters.Project, parameters.CurrentFCO, parameters.SelectedFCOs, parameters.StartModeParam);
                            if (elaboratorresult == false)
                            {
                                throw new ApplicationException("see elaborator log");
                            }
                        }
                        catch (Exception e)
                        {
                            //Logger.Instance.AddLogMessage("Elaborator exception occurred: " + e.Message, Severity.Error);
                            throw new Exception(e.Message);
                        }
                        var testBench = CyPhyClasses.CarTestBench.Cast(parameters.CurrentFCO);

                        TestBenchProcessor processor = new TestBenchProcessor()
                        {
                            GMEConsole = GMEConsole, OutputDir = parameters.OutputDirectory, ProjectDir = parameters.ProjectDirectory
                        };
                        processor.Process(testBench);
                    }
                    else
                    {
                        GMEConsole.Error.WriteLine("Not a Car Test Bench.");
                        return;
                    }
                },
                                                transactiontype_enum.TRANSACTION_NON_NESTED, abort: true);
                result.Success = true;
            }
            catch (Exception ex)
            {
                GMEConsole.Error.WriteLine("Exception was raised: {0}", ex.ToString());
                result.Success = false;
            }
            finally
            {
//                parameters.Project.AbortTransaction();
                MgaGateway = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return(result);
        }
예제 #13
0
 /// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a transaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     if (Logger == null)
     {
         Logger = new GMELogger(project, ComponentName);
     }
     MgaGateway = new MgaGateway(project);
 }
예제 #14
0
        /// <summary>
        /// This function is called for each interpreter invocation before Main.
        /// Don't perform MGA operations here unless you open a tansaction.
        /// </summary>
        /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
        public void Initialize(MgaProject project)
        {
            // TODO: Add your initialization code here...
            Contract.Requires(project != null);

            GMEConsole = GMEConsole.CreateFromProject(project);
            MgaGateway = new MgaGateway(project);
        }
예제 #15
0
 public FCOChooser(MgaGateway gateway, GMEConsole console)
 {
     this.MgaGateway = gateway;
     this.GMEConsole = console;
     InitializeComponent();
     this.choose1.Click += new EventHandler(choose_Click);
     this.choose2.Click += new EventHandler(choose_Click);
     this.link.Click    += new EventHandler(link_Click);
 }
예제 #16
0
        /// <summary>
        /// No GUI and interactive elements are allowed within this function.
        /// </summary>
        /// <param name="parameters">Main parameters for this run and GUI configuration.</param>
        /// <returns>Result of the run, which contains a success flag.</returns>
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            if (Logger == null)
            {
                Logger = new GMELogger(parameters.Project, ComponentName);
            }

            this.runtime.Clear();
            this.mainParameters = parameters;
            var configSuccess = this.mainParameters != null;

            this.UpdateSuccess("Configuration", configSuccess);
            this.result.Labels = "RF";

            try
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    this.WorkInMainTransaction();
                },
                                                transactiontype_enum.TRANSACTION_NON_NESTED,
                                                abort: true
                                                );

                this.PrintRuntimeStatistics();
                if (this.result.Success)
                {
                    Logger.WriteInfo("Generated files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>", this.mainParameters.OutputDirectory);
                    Logger.WriteInfo("RF simulation has been created. [SUCCESS: {0}, Labels: {1}]", this.result.Success, this.result.Labels);
                }
                else
                {
                    Logger.WriteError("RF simulation cannot be created! See error messages above.");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError("Exception: {0}<br> {1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                MgaGateway = null;
                if (Logger != null)
                {
                    Logger.Dispose();
                    Logger = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            META.Logger.RemoveFileListener(this.ComponentName);

            return(this.result);
        }
예제 #17
0
        private void MainThrows(IInterpreterMainParameters parameters)
        {
            // TODO: remove this line, since this is the old implementation
            //this.OpenWebPageWithChromeOrDefaultBrowser("http://fame-deploy.parc.com:2040/");

            this.mainParameters = parameters as InterpreterMainParameters;

            this.result.Labels     = "";
            this.result.RunCommand = "";
            var config = META.ComComponent.DeserializeConfiguration(
                this.mainParameters.ProjectDirectory,
                typeof(CyPhyReliabilityAnalysisSettings),
                this.ComponentProgID) as CyPhyReliabilityAnalysisSettings;

            if (config != null)
            {
                this.mainParameters.config = config;
            }
            else
            {
                this.mainParameters.config = new CyPhyReliabilityAnalysisSettings();
            }

            if (Directory.Exists(this.mainParameters.OutputDirectory) == false)
            {
                Directory.CreateDirectory(this.mainParameters.OutputDirectory);
            }

            using (StreamWriter writer1 = new StreamWriter(Path.Combine(this.mainParameters.OutputDirectory, "bracket_config.json")))
            {
                writer1.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(
                                      new BracketConfig(this.mainParameters.config as CyPhyReliabilityAnalysisSettings),
                                      Newtonsoft.Json.Formatting.Indented));
            }

            // TODO: call all dependent interpreter

            MgaGateway.PerformInTransaction(() =>
            {
                this.WorkInMainTransaction();
            }, transactiontype_enum.TRANSACTION_NON_NESTED);

            //this.PrintRuntimeStatistics();
            if (this.result.Success)
            {
                this.Logger.WriteInfo("CyPhyReliabilityAnalysis 1.0 finished successfully.");
                this.Logger.WriteInfo("Generated files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>", this.mainParameters.OutputDirectory);
                this.Logger.WriteDebug("[SUCCESS: {0}, Labels: {1}]", this.result.Success, this.result.Labels);
            }
            else
            {
                this.Logger.WriteError("CyPhyReliabilityAnalysis 1.0 failed! See error messages above.");
            }
        }
예제 #18
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string[]     fileNames = null;
            DialogResult dr;

            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists  = true;
                ofd.Multiselect      = true;
                ofd.Filter           = "AVM design files and packages (*.adm;*.adp)|*.adm;*.adp|All files (*.*)|*.*";
                ofd.RestoreDirectory = true;
                if (project.ProjectConnStr.StartsWith("MGA=", true, System.Globalization.CultureInfo.InvariantCulture))
                {
                    ofd.InitialDirectory = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
                }

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    fileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                Model[] result = null;
                var     addons = project.AddOnComponents.Cast <IMgaComponentEx>();
                foreach (var addon in addons)
                {
                    if (addon.ComponentName.ToLowerInvariant() == "CyPhyAddOn".ToLowerInvariant())
                    {
                        // keep the InstanceGUID on imported Component instances
                        addon.ComponentParameter["DontAssignGuidsOnNextTransaction".ToLowerInvariant()] = true;
                    }
                }
                MgaGateway.PerformInTransaction(delegate
                {
                    var importer = new AVMDesignImporter(GMEConsole, project);
                    result       = importer.ImportFiles(fileNames, mode: AVMDesignImporter.DesignImportMode.CREATE_CA_IF_NO_DS_CONCEPTS);
                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);

                if (result.Length > 0 && GMEConsole.gme != null)
                {
                    GMEConsole.gme.ShowFCO((MgaFCO)result[0].Impl);
                }
                return;
            }
            else
            {
                GMEConsole.Warning.WriteLine("Design Importer canceled");
                return;
            }
        }
예제 #19
0
        private CyPhy2CADPCB_Settings InitializeSettingsFromWorkflow(CyPhy2CADPCB_Settings settings)
        {
            // Seed with settings from workflow.
            String str_WorkflowParameters = "";

            try
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    var testBench          = CyPhyClasses.TestBench.Cast(this.mainParameters.CurrentFCO);
                    var workflowRef        = testBench.Children.WorkflowRefCollection.FirstOrDefault();
                    var workflow           = workflowRef.Referred.Workflow;
                    var taskCollection     = workflow.Children.TaskCollection;
                    var myTask             = taskCollection.FirstOrDefault(t => t.Attributes.COMName == this.ComponentProgID);
                    str_WorkflowParameters = myTask.Attributes.Parameters;
                },
                                                transactiontype_enum.TRANSACTION_NON_NESTED,
                                                abort: true
                                                );

                Dictionary <string, string> dict_WorkflowParameters = (Dictionary <string, string>)
                                                                      Newtonsoft.Json.JsonConvert.DeserializeObject(str_WorkflowParameters, typeof(Dictionary <string, string>));

                if (dict_WorkflowParameters != null)
                {
                    settings = new CyPhy2CADPCB_Settings();
                    foreach (var property in settings.GetType().GetProperties()
                             .Where(p => p.GetCustomAttributes(typeof(WorkflowConfigItemAttribute), false).Any())
                             .Where(p => dict_WorkflowParameters.ContainsKey(p.Name)))
                    {
                        if (dict_WorkflowParameters[property.Name] == null)
                        {
                            property.SetValue(settings, dict_WorkflowParameters[property.Name], null);
                        }
                        else
                        {
                            property.SetValue(settings, dict_WorkflowParameters[property.Name].ToLower(), null);
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
                Logger.WriteInfo("Could not find workflow object for CyPhy2CADPCB interpreter.");
            }
            catch (Newtonsoft.Json.JsonReaderException)
            {
                Logger.WriteWarning("Workflow Parameter has invalid Json String: {0}", str_WorkflowParameters);
            }

            return(settings);
        }
예제 #20
0
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            this.OutputDirectory      = parameters.OutputDirectory;
            this.ProjectRootDirectory = parameters.ProjectDirectory;

            result.RunCommand = "PrepareIFab.bat";
            result.Labels     = "Creo&&CADCreoParametricCreateAssembly.exev1.4&&" + JobManager.Job.DefaultLabels;

            PrepareIFabConfig config = (PrepareIFabConfig)parameters.config;

            cadSettings.AuxiliaryDirectory       = config.AuxiliaryDirectory;
            cadSettings.StepFormats              = config.StepFormats;
            cadSettings.OtherDataFormat.STLAscii = true;
            InvokeEx(parameters.Project, parameters.CurrentFCO, parameters.SelectedFCOs, parameters.StartModeParam);

            MgaGateway.PerformInTransaction(() =>
            {
                // TODO: this part needs to be refactored!
                string Parameters = parameters
                                    .CurrentFCO
                                    .ChildObjects
                                    .OfType <MgaReference>()
                                    .FirstOrDefault(x => x.Meta.Name == "WorkflowRef")
                                    .Referred
                                    .ChildObjects
                                    .OfType <MgaAtom>()
                                    .FirstOrDefault(fco => fco.Meta.Name == typeof(CyPhy.Task).Name &&
                                                    String.Equals(CyPhyClasses.Task.Cast(fco).Attributes.COMName, this.ComponentProgID, StringComparison.InvariantCultureIgnoreCase))
                                    .StrAttrByName["Parameters"];

                Dictionary <string, string> workflowParameters = new Dictionary <string, string>();

                try
                {
                    workflowParameters = (Dictionary <string, string>)Newtonsoft.Json.JsonConvert.DeserializeObject(Parameters, typeof(Dictionary <string, string>));
                    if (workflowParameters == null)
                    {
                        workflowParameters = new Dictionary <string, string>();
                    }
                }
                catch (Newtonsoft.Json.JsonReaderException)
                {
                }

                META.AnalysisTool.ApplyToolSelection(this.ComponentProgID, workflowParameters, this.result, parameters);
            }, abort: true);

            result.Success = true;
            return(result);
        }
예제 #21
0
        public void DesertTestBase(MgaProject project, string dsPath, Action <IEnumerable <Configurations> > helperTest, Action <Configurations> exporterTest)
        {
            var  gateway    = new MgaGateway(project);
            Type desertType = Type.GetTypeFromProgID("MGA.Interpreter.DesignSpaceHelper");
            var  desert     = (IMgaComponentEx)Activator.CreateInstance(desertType);

            MgaFCO currentobj = null;

            gateway.PerformInTransaction(() =>
            {
                currentobj         = (MgaFCO)project.RootFolder.ObjectByPath[dsPath];
                var configurations = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(currentobj).Children.ConfigurationsCollection;
                foreach (var configuration in configurations)
                {
                    configuration.Delete();
                }
            }, abort: false);
            Xunit.Assert.True(currentobj != null, string.Format("'{0}' does not exist in model", dsPath));

            desert.Initialize(project);
            desert.InvokeEx(project, currentobj, null, 128);
            Configurations configs = null;

            gateway.PerformInTransaction(() =>
            {
                var configurations = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(currentobj).Children.ConfigurationsCollection;
                configs            = configurations.First();
                helperTest(configurations);
            });

            if (exporterTest != null)
            {
                Type caExporterType = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyCAExporter");
                var  caExporter     = (IMgaComponentEx)Activator.CreateInstance(caExporterType);

                gateway.PerformInTransaction(() =>
                {
                    MgaFCOs selected = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
                    foreach (MgaFCO cwc in configs.Children.CWCCollection.Select(x => (MgaFCO)x.Impl))
                    {
                        selected.Append(cwc);
                    }

                    caExporter.Initialize(project);
                    caExporter.InvokeEx(project, selected[1].ParentModel as MgaFCO, selected, 128);
                    exporterTest(configs);
                });
            }
        }
예제 #22
0
        public void StartAssemblySync(MgaProject project, MgaFCO currentobj, int param)
        {
            // FIXME: possible race between sending MetaLink Bridge INTEREST and it registering it, and Creo sending its INTEREST
            // n.b. the tests call StartAssemblySync directly
            metalinkAddon.assemblySyncPaused = false;
            ProjectDirectory = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
            if (ConnectToMetaLinkBridgeTask == null)
            {
                ConnectToMetaLinkBridge(project, param);
            }
            metalinkAddon.Enable(true);

            CyPhyML.ComponentAssembly topasm = null;
            MgaGateway.PerformInTransaction(delegate
            {
                topasm = Run(project, currentobj, param);
                if (topasm != null)
                {
                    metalinkAddon.AssemblyID = topasm.Guid.ToString();
                }
            });

            ConnectToMetaLinkBridgeTask.Wait();
            if (ConnectToMetaLinkBridgeTask.Result == false)
            {
                return;
            }

            if (topasm == null)
            {
                metalinkAddon.AssemblyID = null;
                GMEConsole.Error.WriteLine("No top level assembly can be found. Open an assembly and try again.");
                return;
            }
            try
            {
                metalinkAddon.CallCyPhy2CADWithTransaction(project,
                                                           (topasm.Impl as MgaFCO),
                                                           param);
            }
            catch (Exception e)
            {
                metalinkAddon.syncedComponents.Remove(metalinkAddon.AssemblyID);
                // FIXME: propagateAddon.LastStartedInstance.Remove
                metalinkAddon.AssemblyID = null;
                GMEConsole.Error.Write(e.Message);
            }
        }
예제 #23
0
        void TestDesignSpaceHelper_ExportXML()
        {
            var targetFile = "test__export.xml";

            // Make sure target export file doesn't exist when we begin
            if (System.IO.File.Exists(targetFile))
            {
                System.IO.File.Delete(targetFile);
            }

            var dsPath = "/@DesignSpaces/@DesignContainer";

            var     gateway    = new MgaGateway(project);
            Type    desertType = Type.GetTypeFromProgID("MGA.Interpreter.DesignSpaceHelper");
            dynamic desert     = Activator.CreateInstance(desertType);

            MgaFCO currentobj = null;

            gateway.PerformInTransaction(() =>
            {
                currentobj         = (MgaFCO)project.RootFolder.ObjectByPath[dsPath];
                var configurations = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(currentobj).Children.ConfigurationsCollection;
                foreach (var configuration in configurations)
                {
                    configuration.Delete();
                }
            }, abort: false);
            Xunit.Assert.True(currentobj != null, string.Format("'{0}' does not exist in model", dsPath));

            desert.Initialize(project);
            desert.ExportDesertXML(project, currentobj, targetFile);
            Xunit.Assert.True(System.IO.File.Exists(targetFile));

            var desertRoot = XElement.Load(Path.Combine(Directory.GetCurrentDirectory(), targetFile));

            var spaces = desertRoot.Elements("Space");

            Xunit.Assert.Equal(1, spaces.Count());

            // Validate that we have the root space
            Xunit.Assert.Equal("DesignSpace", spaces.First().Attribute("name").Value);

            // Now look for a leaf-node component: CompA
            Xunit.Assert.True(
                spaces.First().Descendants("Element").Any(element => element.Attribute("name").Value == "CompA"),
                "Generated DESERT XML is missing components"
                );
        }
예제 #24
0
        /// <summary>
        /// This function is called for each interpreter invocation before Main.
        /// Don't perform MGA operations here unless you open a tansaction.
        /// </summary>
        /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
        public void Initialize(MgaProject project)
        {
            // set up the default component parameters
            this.componentParameters = new SortedDictionary <string, object>();
            this.componentParameters.Add("labels", "");
            this.componentParameters.Add("runCommand", RunCommand);
            this.componentParameters.Add("output_dir", string.Empty);
            this.componentParameters.Add("automation", "false");
            this.componentParameters.Add("do_config", "true");
            this.componentParameters.Add("configuration", string.Empty);
            this.componentParameters.Add("test_bench_name", string.Empty);

            // Mimic CyPET and CyPhy2Modelica_v2
            //GMEConsole = GMEConsole.CreateFromProject(project);
            MgaGateway = new MgaGateway(project);
        }
예제 #25
0
        public void ComponentArchetype_HasNoPath()
        {
            // We expect that the Component Library Manager will create a folder and assign a path.
            var lastWriteTime_Manifest = File.GetLastWriteTime(path_Manifest);
            var orgNumCompDirs         = Directory.EnumerateDirectories(Path.Combine(path_Test, "components"), "*", SearchOption.TopDirectoryOnly).Count();

            var mgaGateway = new MgaGateway(fixture.proj);

            mgaGateway.PerformInTransaction(delegate
            {
                // Load the manifest and check how many components it contains.
                var manifest             = AVM.DDP.MetaAvmProject.Create(fixture.proj.RootFolder.Project);
                var org_NumManifestComps = manifest.Project.Components.Count;

                // Get path and check that it's not empty.
                var comp            = getComponentByPath("RootFolder/Components/HasNoPath");
                var relPath_CompDir = comp.GetDirectoryPath();
                Assert.False(String.IsNullOrWhiteSpace(relPath_CompDir), "Component path should be non-empty.");

                // Grab the resources. We expect the relative paths to be returned without error.
                foreach (var dm in comp.Children.CADModelCollection)
                {
                    var relPath_Resource = "";
                    Assert.True(META.ComponentLibraryManager.TryGetResourcePath(dm,
                                                                                out relPath_Resource,
                                                                                META.ComponentLibraryManager.PathConvention.REL_TO_COMP_DIR),
                                "Could not get Resource relative path for CADModel");
                    Assert.False(String.IsNullOrWhiteSpace(relPath_Resource), "Relative Path for CADModel Resource was empty.");

                    var absPath_Resource = "";
                    Assert.True(META.ComponentLibraryManager.TryGetResourcePath(dm,
                                                                                out absPath_Resource,
                                                                                META.ComponentLibraryManager.PathConvention.ABSOLUTE),
                                "Could not get Resource absolute path for CADModel");
                }

                manifest = AVM.DDP.MetaAvmProject.Create(fixture.proj.RootFolder.Project);
                var new_NumManifestComps = manifest.Project.Components.Count;
                Assert.False(new_NumManifestComps == org_NumManifestComps + 1, "New component entry created in manifest when it shouldn't have been.");
            });

            Assert.True(lastWriteTime_Manifest == File.GetLastWriteTime(path_Manifest), "Manifest was updated by this operation, but shouldn't have been.");

            var finalNumCompDirs = Directory.EnumerateDirectories(Path.Combine(path_Test, "components"), "*", SearchOption.TopDirectoryOnly).Count();

            Assert.True(finalNumCompDirs == 1 + orgNumCompDirs, "No component directory created.");
        }
예제 #26
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                if (currentobj == null)
                {
                    // TODO: Add Ballistic TB here once supported.
                    this.GMEConsole.Error.Write("CyPhyMultiJobRun must be called from either a BlastTestBench, CFDTestBench, or BallisticTestBench.");
                    return;
                }

                MgaGateway = new MgaGateway(project);
                string kindName = null;
                MgaGateway.PerformInTransaction(delegate
                {
                    kindName = currentobj.MetaBase.Name;
                });

                if (kindName == "CFDTestBench" || kindName == "BlastTestBench" || kindName == "BallisticTestBench")
                {
                }
                else
                {
                    this.GMEConsole.Error.Write("CyPhyMultiJobRun must be called from either a BlastTestBench or CFDTestBench, not '{0}'", kindName);
                    return;
                }

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #27
0
        static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                usage();
                return(1);
            }

            MgaProject mainMgaProject = GetProject(args[0]);

            if (mainMgaProject == null)
            {
                return(2);
            }

            int        retval     = 0;
            MgaGateway mgaGateway = new MgaGateway(mainMgaProject);

            mgaGateway.PerformInTransaction(delegate {
                for (int ix = 1; ix < args.Length; ++ix)
                {
                    string[] mergeInfo = args[ix].Split(new string[] { ".mga/" }, 2, StringSplitOptions.None);

                    string filename = mergeInfo[0] + ".mga";
                    string path     = "/" + mergeInfo[1];

                    MgaFCO currentObject = mainMgaProject.get_ObjectByPath(path) as MgaFCO;
                    if (currentObject == null)
                    {
                        Console.Error.WriteLine("Error: could not find object of path \"" + path + "\" in model of file \"" + args[0] + "\", cannot merge file \"" + filename + "\"");
                        retval |= (int)SubTreeMerge.SubTreeMerge.Errors.PathError;
                        continue;
                    }

                    SubTreeMerge.SubTreeMerge subTreeMerge = new SubTreeMerge.SubTreeMerge();
                    subTreeMerge.gmeConsole = new SubTreeMerge.FlexConsole(SubTreeMerge.FlexConsole.ConsoleType.CONSOLE);

                    subTreeMerge.merge(currentObject, filename);
                    retval = (int)subTreeMerge.exitStatus;
                }
            }, abort: false);

            mainMgaProject.Save();

            return(retval);
        }
예제 #28
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string[]     fileNames = null;
            DialogResult dr;

            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists = true;
                ofd.DefaultExt      = "testbench.atm";
                ofd.Multiselect     = true;
                ofd.Filter          = "AVM testbench files (*.atm)|*.atm|All files (*.*)|*.*";

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    fileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    foreach (var fileName in fileNames)
                    {
                        using (var streamReader = new StreamReader(fileName))
                        {
                            var avmTestBench = XSD2CSharp.AvmXmlSerializer.Deserialize <avm.TestBench>(streamReader);
                            CyPhy2TestBenchInterchange.TestBenchInterchange2CyPhy.Convert(avmTestBench, project);
                        }
                    }
                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);

                //if (result.Any() && GMEConsole.gme != null)
                //{
                //    GMEConsole.gme.ShowFCO((MgaFCO)result.First().Impl);
                //}
                return;
            }
            else
            {
                GMEConsole.Warning.WriteLine("TestBench Importer canceled");
                return;
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string[]     fileNames = null;
            DialogResult dr;

            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists  = true;
                ofd.DefaultExt       = "design.adm";
                ofd.Multiselect      = true;
                ofd.Filter           = "AVM design files (*.adm)|*.adm|All files (*.*)|*.*";
                ofd.RestoreDirectory = true;
                if (project.ProjectConnStr.StartsWith("MGA=", true, System.Globalization.CultureInfo.InvariantCulture))
                {
                    ofd.InitialDirectory = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
                }

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    fileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                Model[] result = null;
                MgaGateway.PerformInTransaction(delegate
                {
                    var importer = new AVMDesignImporter(GMEConsole, project);
                    result       = importer.ImportFiles(fileNames, mode: AVMDesignImporter.DesignImportMode.CREATE_CA_IF_NO_DS_CONCEPTS);
                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);

                if (result.Length > 0 && GMEConsole.gme != null)
                {
                    GMEConsole.gme.ShowFCO((MgaFCO)result[0].Impl);
                }
                return;
            }
            else
            {
                GMEConsole.Warning.WriteLine("Design Importer canceled");
                return;
            }
        }
예제 #30
0
        public void ComputePropertyValues(object o)
        {
            MgaFCO        fco   = (MgaFCO)o;
            ISet <string> kinds = new HashSet <string>()
            {
                "Property",
                "Parameter",
                "Metric",
            };
            var project = fco.Project;
            List <Tuple <string, string> > assignments = new List <Tuple <string, string> >();
            MgaGateway gateway = new MgaGateway(fco.Project);

            gateway.PerformInTransaction(() =>
            {
                var descendents = (fco as MgaModel).GetDescendantFCOs(fco.Project.CreateFilter());

                bool success = RunInTransaction(fco.Project, fco, null, 128);
                if (success == false)
                {
                    throw new ApplicationException("Evaluation failed");
                }
                foreach (IMgaFCO descendent in descendents)
                {
                    if (descendent.Status != (int)objectstatus_enum.OBJECT_EXISTS)
                    {
                        continue;
                    }
                    if (kinds.Contains(descendent.Meta.Name) == false)
                    {
                        continue;
                    }
                    assignments.Add(new Tuple <string, string>(descendent.ID, descendent.GetStrAttrByNameDisp("Value")));
                }
            }, abort: true);
            gateway.PerformInTransaction(() =>
            {
                foreach (var assignment in assignments)
                {
                    project.GetFCOByID(assignment.Item1).SetStrAttrByNameDisp("Value", assignment.Item2);
                }
            }, abort: false);
        }