Example #1
0
        private void PropagateValueFlow()
        {
            //this.OpenProject();

            try
            {
                Trace.TraceInformation("BEGIN: Value flow propagation using formula evaluator");

                Type            tFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator");
                IMgaComponentEx formulaEval  = Activator.CreateInstance(tFormulaEval) as IMgaComponentEx;

                Type    tMgaFCOs     = Type.GetTypeFromProgID("Mga.MgaFCOs");
                MgaFCOs selectedObjs = Activator.CreateInstance(tMgaFCOs) as MgaFCOs;

                formulaEval.Initialize(this.Project);
                formulaEval.InvokeEx(this.Project, this.CurrentObj, selectedObjs, 128);
                Trace.TraceInformation("END: Value flow propagation using formula evaluator ");
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                throw new JobFailure(ex.Message, ex);
            }

            //this.SaveAndCloseProject();
        }
Example #2
0
        private void CallOldElaborator(MgaProject project, MgaFCO currentobj)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            this.Logger.WriteInfo("CyPhyElaborator 1.0 started");
            try
            {
                Type            typeElaborator = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate");
                IMgaComponentEx oldElaborator  = Activator.CreateInstance(typeElaborator) as IMgaComponentEx;

                Type    typeMgaFCOs  = Type.GetTypeFromProgID("Mga.MgaFCOs");
                MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs;

                oldElaborator.Initialize(project);
                oldElaborator.ComponentParameter["automation"]       = "true";
                oldElaborator.ComponentParameter["console_messages"] = "off";
                oldElaborator.ComponentParameter["expanded"]         = "true";

                sw.Start();
                oldElaborator.InvokeEx(project, currentobj, selectedObjs, 128);
                this.Logger.WriteInfo("CyPhyElaborator 1.0 finished");
            }
            catch (Exception ex)
            {
                this.Logger.WriteInfo("CyPhyElaborator 1.0 failed");
                this.Logger.WriteDebug(ex.ToString());
            }
            finally
            {
                sw.Stop();
                this.Logger.WriteDebug("CyPhyElaborator 1.0 runtime: {0}", sw.Elapsed.ToString("c"));
            }
        }
        /// <summary>
        /// Runs the Component Assembly exporter. Exports CWC configurations into Component Assemblies.
        /// </summary>
        /// <param name="cwcs">Set of CWCs to export.</param>
        /// <returns>Exported Component Assembly references.</returns>
        public IEnumerable <MgaReference> RunCAExporter(IEnumerable <MgaFCO> cwcs)
        {
            if (cwcs == null)
            {
                throw new ArgumentNullException("cwcs");
            }

            List <MgaReference> exportedConfigurations = new List <MgaReference>();

            if (cwcs.Any())
            {
                IMgaComponentEx componentAssemblyExporter = (IMgaComponentEx)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Interpreter.CyPhyCAExporter"));

                MgaFCOs selected = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
                foreach (MgaFCO cwc in cwcs)
                {
                    selected.Append(cwc);
                }

                componentAssemblyExporter.Initialize(cwcs.First().Project);
                componentAssemblyExporter.InvokeEx(cwcs.First().Project, cwcs.First().ParentModel as MgaFCO, selected, 128);
                var traceability = (CyPhyCOMInterfaces.IMgaTraceability)componentAssemblyExporter.ComponentParameter["traceability"];
                traceability.CopyTo(Traceability);
                foreach (MgaFCO cwc in cwcs)
                {
                    foreach (MgaConnPoint cp in cwc.PartOfConns)
                    {
                        MgaSimpleConnection configuration2ComponentAssembly = cp.Owner as MgaSimpleConnection;
                        exportedConfigurations.Add(configuration2ComponentAssembly.Dst as MgaReference);
                    }
                }
            }

            return(exportedConfigurations);
        }
Example #4
0
        public static void RunUdmInterpreter(MgaFCO currentobj, String ProgID)
        {
            // create interpreter type
            Type            typeUdmInterpreter = Type.GetTypeFromProgID(ProgID);
            IMgaComponentEx udmInterpreter     = Activator.CreateInstance(typeUdmInterpreter) as IMgaComponentEx;

            // empty selected object set
            Type    typeMgaFCOs  = Type.GetTypeFromProgID("Mga.MgaFCOs");
            MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs;

            // initialize interpreter
            udmInterpreter.Initialize(currentobj.Project);

            // automation means no UI element shall be shown by the interpreter
            udmInterpreter.ComponentParameter["automation"] = "true";

            // do not write to the console
            udmInterpreter.ComponentParameter["console_messages"] = "off";

            // do not expand nor collapse the model
            udmInterpreter.ComponentParameter["expanded"] = "true";

            // call the formula evaluator and update all parameters starting from the current object
            udmInterpreter.InvokeEx(currentobj.Project, currentobj, selectedObjs, 16);
        }
Example #5
0
        public static void RunDSRefactorer(MgaFCO currentobj, List <MgaFCO> selected, String refactoredType)
        {
            // create interpreter type
            Type            typeInterpreter       = Type.GetTypeFromProgID("MGA.Interpreter.CyphyDesignSpaceRefactor");
            IMgaComponentEx dsRefactorInterpreter = Activator.CreateInstance(typeInterpreter) as IMgaComponentEx;

            // empty selected object set
            Type    typeMgaFCOs  = Type.GetTypeFromProgID("Mga.MgaFCOs");
            MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs;

            foreach (MgaFCO fco in selected)
            {
                selectedObjs.Append(fco);
            }

            // initialize interpreter
            dsRefactorInterpreter.Initialize(currentobj.Project);

            // automation means no UI element shall be shown by the interpreter
            dsRefactorInterpreter.ComponentParameter["automation"] = "true";
            dsRefactorInterpreter.ComponentParameter["refactored_type_or_action"] = refactoredType;

            // do not write to the console
            dsRefactorInterpreter.ComponentParameter["console_messages"] = "off";

            // do not expand nor collapse the model
            dsRefactorInterpreter.ComponentParameter["expanded"] = "true";

            // call the formula evaluator and update all parameters starting from the current object
            dsRefactorInterpreter.InvokeEx(currentobj.Project, currentobj, selectedObjs, 16);
        }
Example #6
0
        public string[] RunFormulaEvaluator(MgaFCO currentobj, string automation = "true")
        {
            // create formula evaluator type
            Type            typeFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator");
            IMgaComponentEx formulaEval     = Activator.CreateInstance(typeFormulaEval) as IMgaComponentEx;

            // empty selected object set
            Type    typeMgaFCOs  = Type.GetTypeFromProgID("Mga.MgaFCOs");
            MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs;

            // initialize formula evaluator
            formulaEval.Initialize(fixture.proj);

            // automation means no UI element shall be shown by the interpreter
            formulaEval.ComponentParameter["automation"] = automation;

            // do not write to the console
            formulaEval.ComponentParameter["console_messages"] = "off";

            // do not generate the post processing python scripts
            // FIXME: Why should we generate them ???
            formulaEval.ComponentParameter["do_not_generate_post_processing"] = "true";

            // call the formula evaluator and update all parameters starting from the current object
            formulaEval.InvokeEx(fixture.proj, currentobj, selectedObjs, 16);

            string[] numericLeafNodes = (string[])formulaEval.ComponentParameter["numericLeafNodes"];
            return(numericLeafNodes);
        }
Example #7
0
        public void RunFormulaEvaluator(MgaFCO currentobj, bool expanded = true)
        {
            // create formula evaluator type
            // FIXME: calling the elaborator is faster than calling the formula evaluator
            Type            typeFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator");
            IMgaComponentEx formulaEval     = Activator.CreateInstance(typeFormulaEval) as IMgaComponentEx;

            // empty selected object set
            Type    typeMgaFCOs  = Type.GetTypeFromProgID("Mga.MgaFCOs");
            MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs;

            // initialize formula evauator
            formulaEval.Initialize(Project);

            // automation means no UI element shall be shown by the interpreter
            formulaEval.ComponentParameter["automation"] = "true";

            // do not write to the console
            formulaEval.ComponentParameter["console_messages"] = "off";

            // do not expand nor collapse the model
            formulaEval.ComponentParameter["expanded"] = expanded ? "true" : "false";

            // do not generate the post processing python scripts
            // FIXME: Why should we generate them ???
            formulaEval.ComponentParameter["do_not_generate_post_processing"] = "true";

            // call the formula evaluator and update all parameters starting from the current object
            formulaEval.InvokeEx(Project, currentobj, selectedObjs, 16);
        }
Example #8
0
        public void InvokeExShouldNotThrowIfCurrentObjNull()
        {
            Assert.True(File.Exists(this.mgaFile), "Project file does not exist.");
            string ProjectConnStr = "MGA=" + Path.GetFullPath(this.mgaFile);

            MgaProject project = new MgaProject();

            project.OpenEx(ProjectConnStr, "CyPhyML", null);
            try
            {
                var terr    = project.BeginTransactionInNewTerr();
                var testObj = project.ObjectByPath["/@TestBenches|kind=Testing|relpos=0/@DesignSpace|kind=Testing|relpos=0/@Dynamics|kind=Testing|relpos=0/@MSD_om_DS|kind=TestBench|relpos=0"] as MgaFCO;
                project.AbortTransaction();

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

                IMgaComponentEx interpreter = GetInterpreterByProgID(ProgID);
                Assert.DoesNotThrow(() => { interpreter.Initialize(project); });
                Assert.DoesNotThrow(() => { interpreter.InvokeEx(project, null, fcos, 128); });
            }
            finally
            {
                project.Close(true);
            }
        }
Example #9
0
        public void NullObjectAndInteractiveMode()
        {
            MgaProject project    = null;
            MgaFCO     currentObj = null;
            MgaFCOs    fcos       = null;

            MgaObject  obj  = null;
            MgaObjects objs = null;


            IMgaComponentEx interpreter = GetInterpreterByProgID(ProgID);

            Assert.Throws <ArgumentNullException>(() => { interpreter.Initialize(project); });
            Assert.Throws <NotImplementedException>(() => { interpreter.ObjectsInvokeEx(project, obj, objs, 128); });
            Assert.Throws <ArgumentNullException>(() => { interpreter.InvokeEx(project, currentObj, fcos, 128); });

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

            project = new MgaProject();
            project.OpenEx(ProjectConnStr, "CyPhyML", null);
            try
            {
                // project is set, but fcos are not
                Assert.DoesNotThrow(() => { interpreter.Initialize(project); });
                Assert.Throws <ArgumentNullException>(() => { interpreter.InvokeEx(project, currentObj, fcos, 128); });

                // fcos are set
                fcos = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
                Assert.DoesNotThrow(() => { interpreter.InvokeEx(project, currentObj, fcos, 128); });
                Assert.True(interpreter.InteractiveMode == false, "Interactive is not set correctly. (128) silent mode");
                Assert.DoesNotThrow(() => { interpreter.InvokeEx(project, currentObj, fcos, 16); });
                Assert.True(interpreter.InteractiveMode == true, "Interactive is not set correctly. (16)");
            }
            finally
            {
                project.Close(true);
            }
        }
Example #10
0
        private void ElaborateModel(MgaProject project,
                                    MgaFCO currentobj,
                                    MgaFCOs selectedobjs,
                                    int param)
        {
            // call elaborator and expand the references
            Type            t          = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate");
            IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx;

            elaborator.Initialize(project);
            elaborator.ComponentParameter["automated_expand"] = "true";
            elaborator.ComponentParameter["console_messages"] = "off";

            elaborator.InvokeEx(project, currentobj, selectedobjs, param);
        }
Example #11
0
        public static void RunFormulaEvaluator(this ISIS.GME.Dsml.CyPhyML.Interfaces.Component component)
        {
            var project    = component.Impl.Project;
            var currentobj = component.Impl as MgaFCO;

            // create formula evaluator type
            // FIXME: calling the elaborator is faster than calling the formula evaluator
            Type            typeFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator");
            IMgaComponentEx formulaEval     = Activator.CreateInstance(typeFormulaEval) as IMgaComponentEx;

            // empty selected object set
            Type    typeMgaFCOs  = Type.GetTypeFromProgID("Mga.MgaFCOs");
            MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs;

            // initialize formula evauator
            formulaEval.Initialize(project);

            // automation means no UI element shall be shown by the interpreter
            formulaEval.ComponentParameter["automation"] = "true";

            // do not write to the console
            formulaEval.ComponentParameter["console_messages"] = "off";

            // do not expand nor collapse the model
            formulaEval.ComponentParameter["expanded"] = "true";

            // do not generate the post processing python scripts
            // FIXME: Why should we generate them ???
            formulaEval.ComponentParameter["do_not_generate_post_processing"] = "true";

            // call the formula evaluator and update all parameters starting from the current object
            try
            {
                formulaEval.InvokeEx(project, currentobj, selectedObjs, 128);
            }
            catch (COMException)
            {
                // FIXME: handle this exception properly
                // success = false;
                // this.Logger.WriteError(exceptionMessage);
                // this.Logger.WriteError("CyPhyFormulaEvaluator 1.0 finished with errors");
            }
        }
Example #12
0
        private void CallElaboratorAndMain(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            META_PATH = META.VersionInfo.MetaPath;

            GMEConsole = GMEConsole.CreateFromProject(project);

            #region Elaborate the TestBench
            // call elaborator and expand the references
            Type            t          = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate");
            IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx;
            elaborator.Initialize(project);
            elaborator.ComponentParameter["automated_expand"] = "true";
            elaborator.ComponentParameter["console_messages"] = "off";
            elaborator.InvokeEx(project, currentobj, selectedobjs, (int)ComponentStartMode.GME_SILENT_MODE);
            #endregion

            MgaGateway.PerformInTransaction(delegate
            {
                Main(project, currentobj, selectedobjs, Convert(param));
            });
        }
Example #13
0
        // Running CAD flattener on the assembly
        void TestCadFlattener()
        {
            SetupTest();

            RunCyPhyMLSync(
                (project, propagate, interpreter) =>
            {
                project.BeginTransactionInNewTerr();
                CyPhyML.ComponentAssembly assembly = CyPhyMLClasses.ComponentAssembly.Cast(GetTestAssembly(project));

                Type t = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborateCS");
                IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx;
                DateTime t1 = DateTime.Now;
                elaborator.Initialize(project);
                elaborator.ComponentParameter["automated_expand"] = "true";
                elaborator.ComponentParameter["console_messages"] = "off";
                elaborator.InvokeEx(project, GetTestAssembly(project), (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")), 0);

                CyPhy2CAD_CSharp.Logger.Instance.Reset();
                CyPhy2CAD_CSharp.CADFlatDataCreator datacreator = new CyPhy2CAD_CSharp.CADFlatDataCreator("", Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)),
                                                                                                          CyPhyMLClasses.CADModel.AttributesClass.FileFormat_enum.Creo, metalink: true);

                datacreator.CreateFlatData(assembly);
                CyPhy2CAD_CSharp.DataRep.CADContainer cadcontainer = datacreator.CreateCADDataContainer(assembly.Guid.ToString(), CyPhy2CAD_CSharp.UtilityHelpers.CleanString2(assembly.Name));

                // IF this is an empty design, add a root component
                if (cadcontainer.assemblies.Count == 0)
                {
                    cadcontainer.AddRootComponent(assembly);
                }

                Xunit.Assert.Equal(CyPhy2CAD_CSharp.Logger.Instance.ErrorCnt, 0);

                project.AbortTransaction();
            }
                );
        }
Example #14
0
        private void GenerateCADAssemblyXml(MgaProject project, MgaFCO currentobj, int param)
        {
            int origPrefs = project.Preferences;

            try
            {
                project.Preferences = project.Preferences | (int)GME.MGA.preference_flags.MGAPREF_IGNORECONNCHECKS | (int)GME.MGA.preference_flags.MGAPREF_FREEINSTANCEREFS;
                CyPhyML.ComponentAssembly assembly  = CyPhyMLClasses.ComponentAssembly.Cast(currentobj);
                List <string>             errorList = new List <string>();
                if (!VerifyAssembly(assembly, errorList))
                {
                    foreach (string s in errorList)
                    {
                        GMEConsole.Warning.WriteLine(s);
                    }
                    System.Windows.Forms.MessageBox.Show("Model verification failed for Meta-Link and it may not work properly for this model.", "Warning", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                }
                SyncedComponentData syncedCompData;
                if (!syncedComponents.TryGetValue(assembly.Guid.ToString(), out syncedCompData))
                {
                    throw new Exception("Internal error in GenerateCADAssemblyXml, can't find data for guid " + assembly.Guid);
                }

                HashSet <CyPhyML.Component> comps = CyphyMetaLinkUtils.CollectComponentsRecursive(assembly);

                // Prepare Meta-Link specific data based on the original model
                CyPhy2CAD_CSharp.MetaLinkData metaLinkData = new CyPhy2CAD_CSharp.MetaLinkData();
                try
                {
                    PrepareMetaLinkData(metaLinkData, assembly, "");
                }
                catch (Exception ex)
                {
                    throw new Exception("Error during collecting metalink data." + ex.Message);
                }

                DateTime t1 = DateTime.Now;
                // call elaborator and expand the references
                // Please note that elaborator will change "currentobj"'s internal structure
                Type t = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborateCS");
                if (t == null)
                {
                    throw new NullReferenceException("Cannot find MGA.Interpreter.CyPhyElaborate. Is it registered?");
                }
                IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx;
                elaborator.Initialize(project);
                elaborator.ComponentParameter["automated_expand"] = "true";
                elaborator.ComponentParameter["console_messages"] = "off";

                elaborator.InvokeEx(project, currentobj, (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")), param);
                TimeSpan ts = DateTime.Now - t1;
                GMEConsole.Info.WriteLine("Elaborator was running for " + ts.TotalMilliseconds + "ms");

                CyPhy2CAD_CSharp.CyPhy2CADSettings cadSettings = new CyPhy2CAD_CSharp.CyPhy2CADSettings();
                cadSettings.AuxiliaryDirectory = syncedCompData.AuxDir;
                cadSettings.OutputDirectory    = syncedCompData.WorkingDir;
                cadSettings._metaLink          = true;

                CyPhy2CAD_CSharp.Logger.Instance.Reset();
                CyPhy2CAD_CSharp.CADFlatDataCreator datacreator = new CyPhy2CAD_CSharp.CADFlatDataCreator(cadSettings.OutputDirectory, GetProjectDir(), CadFormat, metalink: true);

                datacreator.CreateFlatData(assembly);
                CyPhy2CAD_CSharp.DataRep.CADContainer cadcontainer = datacreator.CreateCADDataContainer(assembly.Guid.ToString(), CyPhy2CAD_CSharp.UtilityHelpers.CleanString2(assembly.Name));

                cadcontainer.MergeAssemblies();

                // IF this is an empty design, add a root component
                if (cadcontainer.assemblies.Count == 0)
                {
                    cadcontainer.AddRootComponent(assembly);
                }

                cadcontainer.InjectMetaLinkData(assembly, metaLinkData);


                CyPhy2CAD_CSharp.TestBenchModel.TestBenchBase testbenchbase = new CyPhy2CAD_CSharp.TestBenchModel.TestBenchBase(cadSettings, cadSettings.OutputDirectory, GetProjectDir());
                testbenchbase.cadDataContainer = cadcontainer;
                testbenchbase.CollectDirectories();

                testbenchbase.GenerateCADXMLOutput();
                testbenchbase.GenerateScriptFiles();
                bool stop = CyPhy2CAD_CSharp.Logger.Instance.ErrorCnt > 0;
                CyPhy2CAD_CSharp.Logger.Instance.DumpLog(GMEConsole, "");
                if (stop)
                {
                    throw new Exception("There were errors during processing the model. Please look at the console log and fix these.");
                }

                string CADAssembly = File.ReadAllText(Path.Combine(cadSettings.OutputDirectory, CyPhy2CAD_CSharp.TestBenchModel.TestBenchBase.CADAssemblyFile));
                string designId    = new Guid(currentobj.GetGuidDisp()).ToString("D");
                SendInterest(null, syncedCompData.InstanceId);
                foreach (var comp in comps)
                {
                    //  SendInterest(null, ComponentTopic, comp.Attributes.AVMID);
                }
                SaveCadAssemblyXml(CADAssembly, designId);
            }
            finally
            {
                project.Preferences = origPrefs;
            }
        }
Example #15
0
        private bool CallElaborator(
            MgaProject project,
            MgaFCO currentobj,
            MgaFCOs selectedobjs,
            int param,
            bool expand = true)
        {
            try
            {
                // call elaborator and expand the references
                Type            t          = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate");
                IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx;
                elaborator.Initialize(project);

                if (expand)
                {
                    elaborator.ComponentParameter["automated_expand"] = "true";
                }
                else
                {
                    elaborator.ComponentParameter["automated_collapse"] = "true";
                }

                elaborator.ComponentParameter["console_messages"] = "off";

                //GMEConsole.Info.WriteLine("Elaborating model...");
                //System.Windows.Forms.Application.DoEvents();

                elaborator.InvokeEx(project, currentobj, selectedobjs, param);

                CyPhyCOMInterfaces.IMgaTraceability traceability = elaborator.ComponentParameter["traceability"] as CyPhyCOMInterfaces.IMgaTraceability;

                this.Traceability = new META.MgaTraceability();

                if (traceability != null)
                {
                    traceability.CopyTo(this.Traceability);
                }

                //GMEConsole.Info.WriteLine("Elaboration is done.");
                //System.Windows.Forms.Application.DoEvents();

                // TODO: get exception message(s) from elaborator
                string msgs = elaborator.ComponentParameter["exception"] as string;
                if (string.IsNullOrWhiteSpace(msgs) == false)
                {
                    if (this.Logger != null)
                    {
                        this.Logger.WriteError("Elaborator exception occured: {0}", msgs);
                    }
                    else
                    {
                        GMEConsole.Error.WriteLine("Elaborator exception occured: {0}", msgs);
                    }
                    System.Windows.Forms.Application.DoEvents();
                    throw new Exception(msgs);
                }
            }
            catch (Exception ex)
            {
                GMEConsole.Error.WriteLine(ex);
                return(false);
            }

            return(true);
        }
Example #16
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);
        }
Example #17
0
        public bool Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            this.Logger.WriteInfo("CyPhyElaborate 2.0 started.");
            PumpMessages();

            bool success = this.Check(currentobj);

            if (success == false)
            {
                this.Logger.WriteError("CyPhyElaborate 2.0 context is invalid.");
                return(success);
            }

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            try
            {
                this.ElaborateContext(currentobj);
            }
            catch (ElaboratorException ex)
            {
                this.Logger.WriteError(ex.Message);
                this.Logger.WriteError("CyPhyElaborate 2.0 finished with errors.");
                PumpMessages();

                // make sure we abort the transaction
                throw ex;
            }
            catch (NotSupportedException ex)
            {
                this.Logger.WriteError(ex.Message);
                this.Logger.WriteError("CyPhyElaborate 2.0 finished with errors.");
                PumpMessages();

                throw ex;
            }

            sw.Stop();
            this.Logger.WriteDebug("Time: {0}", sw.Elapsed.ToString("c"));

            sw.Restart();
            this.Logger.WriteInfo("CyPhyFormulaEvaluator 1.0 started");
            try
            {
                // create formula evaluator type
                // FIXME: calling the elaborator is faster than calling the formula evaluator
                Type            typeFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator");
                IMgaComponentEx formulaEval     = Activator.CreateInstance(typeFormulaEval) as IMgaComponentEx;

                // empty selected object set
                Type    typeMgaFCOs  = Type.GetTypeFromProgID("Mga.MgaFCOs");
                MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs;

                // initialize formula evauator
                formulaEval.Initialize(project);

                // automation means no UI element shall be shown by the interpreter
                formulaEval.ComponentParameter["automation"] = "true";

                // do not write to the console
                formulaEval.ComponentParameter["console_messages"] = "off";

                // do not expand nor collapse the model
                formulaEval.ComponentParameter["expanded"] = "true";

                // do not generate the post processing python scripts
                // FIXME: Why should we generate them ???
                formulaEval.ComponentParameter["do_not_generate_post_processing"] = "true";

                formulaEval.ComponentParameter["traceability"] = Traceability;

                // call the formula evaluator and update all parameters starting from the current object
                try
                {
                    formulaEval.InvokeEx(project, currentobj, selectedObjs, 128);
                    numericLeafNodes = (string[])formulaEval.ComponentParameter["numericLeafNodes"];
                    this.Logger.WriteInfo("CyPhyFormulaEvaluator 1.0 finished");
                }
                catch (COMException e)
                {
                    success = false;
                    this.Logger.WriteError(e.Message);
                    this.Logger.WriteError("CyPhyFormulaEvaluator 1.0 finished with errors");
                }
            }
            catch (Exception ex)
            {
                this.Logger.WriteInfo("CyPhyFormulaEvaluator 1.0 failed");
                this.Logger.WriteDebug(ex.ToString());
            }

            sw.Stop();
            this.Logger.WriteDebug("Formula evaluator runtime: {0}", sw.Elapsed.ToString("c"));


            if (UnrollConnectors)
            {
                sw.Restart();
                this.Logger.WriteInfo("ConnectorUnroller started");
                try
                {
                    var kindCurrentObj = currentobj.MetaBase.Name;
                    if (kindCurrentObj == "ComponentAssembly")
                    {
                        using (Unroller unroller = new Unroller(currentobj.Project, Traceability, Logger))
                        {
                            unroller.UnrollComponentAssembly(currentobj as MgaModel);
                        }
                    }
                    else if (kindCurrentObj == "TestBench")
                    {
                        using (Unroller unroller = new Unroller(currentobj.Project, Traceability, Logger))
                        {
                            unroller.UnrollTestBench(currentobj as MgaModel);
                        }
                    }


                    this.Logger.WriteInfo("ConnectorUnroller finished");
                }
                catch (Exception ex)
                {
                    this.Logger.WriteInfo(ex.Message);
                    this.Logger.WriteDebug(ex.ToString());
                    this.Logger.WriteError("ConnectorUnroller failed. Check " + SmartLogger.GetGMEConsoleFileLink(this.Logger.LogFilenames[0], "detailed log") + " for details.");
                    success = false;
                }
                sw.Stop();
                this.Logger.WriteDebug("ConnectorUnroller runtime: {0}", sw.Elapsed.ToString("c"));
            }

            this.Logger.WriteInfo("CyPhyElaborate 2.0 finished.");
            PumpMessages();

            return(success);
        }