Example #1
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;
            }
        }
 public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
 {
     // create a checker instance
     var ch = new Framework.Checker(currentobj, project, null);
     var checkerWindow = new RuleView(ch);
     checkerWindow.ShowDialog();
 }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            this.Logger.WriteInfo("Running Component Authoring interpreter.");

            // verify we are running in a component and that it is not an instance or library
            string return_msg;
            if (!CheckPreConditions(currentobj, out return_msg))
            {
                this.Logger.WriteFailed(return_msg);
                return;
            }

            // assuming a component is open
            // stash off the project, currentobj and CurrentComponent parameters for use in the event handlers
            StashProject = project;
            StashCurrentObj = currentobj;
            StashCurrentComponent = CyPhyClasses.Component.Cast(currentobj);

            // use reflection to populate the dialog box objects
            PopulateDialogBox();

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);			
        }
Example #4
0
        public void Main(
            MgaProject project,
            MgaFCO currentobj,
            MgaFCOs selectedobjs,
            ComponentStartMode startMode)
        {
            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

            GMEConsole.Out.WriteLine("Running interpreter...");

            if (project.RootMeta.Name == "MetaGME")
            {
                GMEConsole.Out.WriteLine("Generating .NET API code");
                GenerateDotNetCode(project, currentobj, selectedobjs, startMode);
            }

            GMEConsole.Out.WriteLine("Elapsed time: {0}", sw.Elapsed.ToString("c"));
        }
        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;
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string OutputBaseDir = (string)componentParameters["output_dir"];

            SotConfig sotConfig = new SotConfig();
            sotConfig.MultiJobRun = true;
            sotConfig.OriginalProjectFileName = project.ProjectConnStr.Substring("MGA=".Length);
            sotConfig.ProjectFileName = Path.Combine(OutputBaseDir, Path.GetFileName(sotConfig.OriginalProjectFileName));
            // can't be in a tx and save the project
            project.AbortTransaction();
            project.Save("MGA=" + sotConfig.ProjectFileName, true);
            project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED);
            MgaGateway.PerformInTransaction(delegate
            {
                sotConfig.SoTID = currentobj.ID;
            }, transactiontype_enum.TRANSACTION_READ_ONLY);
            using (StreamWriter writer = new StreamWriter(Path.Combine(OutputBaseDir, "manifest.sot.json")))
            {
                writer.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(sotConfig, Newtonsoft.Json.Formatting.Indented));
            }

            string configsDir = Path.Combine(Path.GetDirectoryName((string)componentParameters["original_project_file"]), "config");
            if (Directory.Exists(configsDir))
            {
                var configs = Directory.EnumerateFiles(configsDir, "*xml").ToList();
                string sotConfigDir = Path.Combine(OutputBaseDir, "config");
                Directory.CreateDirectory(sotConfigDir);
                foreach (var config in configs)
                {
                    File.Copy(config, Path.Combine(sotConfigDir, Path.GetFileName(config)));
                }
            }

            //componentParameters["labels"] = "";
            //componentParameters["runCommand"] = ;
            //componentParameters["results_zip_py"] as string;
            // result.LogFileDirectory = Path.Combine(MainParameters.ProjectDirectory, "log");
            // componentParameters["build_query"] as string;

        }
Example #8
0
        public MgaFCO Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            IMgaFolder rootFolder = project.RootFolder;

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

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


            return((MgaFCO)component);
        }
Example #9
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            if (currentobj.Meta.Name == "TestBench")
            {
                CyPhy.TestBench tb = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.TestBench>(currentobj as MgaObject);

                //var sut = tb.Children.TopLevelSystemUnderTestCollection.FirstOrDefault();
                //String s_sutName = sut.Name;

                CyPhy.ComponentAssembly sut = null;
                foreach (CyPhy.ComponentAssembly ca in tb.Children.ComponentAssemblyCollection)
                {
                    if ((ca.Impl as MgaFCO).get_RegistryValue("ElaboratedModel") != "")
                        sut = ca;
                }

                if (sut != null)
                {
                    var dm = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(sut);
                    //dm = MakeFakeModel();
                    //String json = dm.Serialize();
                    String json = XSD2CSharp.AvmXmlSerializer.Serialize(dm);
                    int json_len = json.Length;
                    dm.SaveToFile(Path.Combine(OutputDirectory, dm.Name + ".adm"));

                    Complexity.Design cd = METADesignInterchange2ComplexityLib.METADesign2Complexity.Design2Complexity(dm);
                    Dictionary<string,string> dCSV_output = cd.SerializeToCSVFormat();

                    foreach (KeyValuePair<string, string> kvp in dCSV_output)
                    {
                        String s_filePath = Path.Combine(OutputDirectory, kvp.Key);
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s_filePath))
                        {
                            sw.Write(kvp.Value);
                        }
                    }

                    string mainPythonFilename = Path.Combine(OutputDirectory, "ComplexityMain.py");
                    string mainCmdFilename = Path.Combine(OutputDirectory, "RunComplexityEvaluator.cmd");

                    using (StreamWriter writer = new StreamWriter(mainPythonFilename))
                    {
                        writer.WriteLine(CyPhyComplexity.Properties.Resources.ComplexityMain);
                    }
                    using (StreamWriter writer = new StreamWriter(mainCmdFilename))
                    {
                        writer.WriteLine("call \"{0}\"", META_PATH_PYTHON_ACTIVATE);
                        writer.WriteLine("python {0}  Components.csv Connections.csv 1", mainPythonFilename);

                        //writer.WriteLine(CyPhyComplexity.Properties.Resources.RunComplexityEvaluator);
                    }

                    if (dCSV_output.Count == 2)
                    {
                        result.RunCommand = "RunComplexityEvaluator.cmd";
                    }

                    GMEConsole.Info.WriteLine(
                        "Result files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>.",
                        Path.GetFullPath(OutputDirectory));

                }
                                        
            }
        }
Example #10
0
        private void GenerateDotNetCode(
            MgaProject project,
            MgaFCO currentobj,
            MgaFCOs selectedobjs,
            ComponentStartMode startMode)
        {
            // speed up the generation process
            CSharpDSMLGenerator.Generator.FCO.derivedClassCache.Clear();

            string projectDir      = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
            string paradigmXmpFile = Path.Combine(projectDir, project.RootFolder.Name);

            paradigmXmpFile = Path.ChangeExtension(paradigmXmpFile, "xmp");
            if (!File.Exists(paradigmXmpFile))
            {
                string error = String.Format("Paradigm file '{0}' does not exist.", paradigmXmpFile);
                if (startMode == ComponentStartMode.GME_SILENT_MODE)
                {
                    throw new Exception(error);
                }
                DialogResult yesno = MessageBox.Show(error + "\n\nDo you want to run the Meta Interpreter?",
                                                     "Paradigm file missing", MessageBoxButtons.YesNo);
                if (yesno != DialogResult.Yes)
                {
                    throw new Exception(error);
                }
                MgaGateway.AbortTransaction();
                IMgaComponentEx metaInterpreter = (IMgaComponentEx)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Interpreter.MetaInterpreter"));
                metaInterpreter.InvokeEx(project, null, null, (int)ComponentStartMode.GME_SILENT_MODE);
                MgaGateway.BeginTransaction();
            }

            string outputDir = ".";

            if (project.ProjectConnStr.StartsWith("MGA="))
            {
                outputDir = Path.GetDirectoryName(project.ProjectConnStr.Substring(4));
            }
            GeneratorMode mode;

            if (startMode != ComponentStartMode.GME_SILENT_MODE)
            {
                ApiGenerator apiForm = new ApiGenerator();
                apiForm.txtOutputDir.Text =
                    Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));

                DialogResult dr = apiForm.ShowDialog();
                if (dr != DialogResult.OK)
                {
                    return;
                }

                mode = ((ApiGenerator.ModeItem)apiForm.cbMode.SelectedItem).Mode;
            }
            else
            {
                mode = GeneratorMode.Namespaces;
            }
            var compileUnit = GenerateDotNetCode(project, paradigmXmpFile, outputDir, mode);

            CompileDll(outputDir, compileUnit);
        }
Example #11
0
        public bool Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            //GMEConsole.Clear();
            GMEConsole.Out.WriteLine("Running CyPhy2CAD interpreter...");

            // TODO: show how to initialize DSML-generated classes
            // Get RootFolder
            //IMgaFolder rootFolder = project.RootFolder;
            //GMEConsole.Out.WriteLine(rootFolder.Name);


            // Check Model
            // Grab all components
            // Create Intermediate Data Representations
            // Walk representation + find islands
            // Convert to DAG

            try
            {
                // META-1971: ADM + ACM file export for blast + ballistics
                // ACM
                {
                    CallComponentExporter(project, currentobj);
                }
                result.Success = true;
                ProcessCAD(currentobj);
                Logger.Instance.DumpLog(GMEConsole, LogDir);
                GMEConsole.Out.WriteLine("Finished CyPhy2CAD with " + (result.Success ? "success" : "failure"));
                return(result.Success);
            }
            catch (Exception ex)
            {
                Logger.Instance.AddLogMessage(ex.Message, Severity.Error);
                Logger.Instance.DumpLog(GMEConsole, LogDir);
                GMEConsole.Out.WriteLine(ex.StackTrace.ToString());
                GMEConsole.Out.WriteLine("Finished CyPhy2CAD with failure. Exception encountered.");
                return(false);
            }
        }
        public bool Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            this.Logger.WriteInfo("CyPhyElaborate 2.0 started.");
            System.Windows.Forms.Application.DoEvents();

            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.");
                System.Windows.Forms.Application.DoEvents();

                // 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.");
                System.Windows.Forms.Application.DoEvents();

                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";

                // call the formula evaluator and update all parameters starting from the current object
                try
                {
                    formulaEval.InvokeEx(project, currentobj, selectedObjs, 128);
                    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"));

            this.Logger.WriteInfo("CyPhyElaborate 2.0 finished.");
            System.Windows.Forms.Application.DoEvents();

            return success;
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            if (currentobj == null)
            {
                GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName);
                return;
            }
            else if (currentobj.Meta.Name != "TestBench")
            {
                GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName);
                return;
            }

            GMEConsole.Info.WriteLine("Running {0} on TestBench '{1}'", ComponentName, currentobj.Name);

            // get root folder
            IMgaFolder rootFolder = project.RootFolder;
            
            // create a filter for components
            MgaFilter filter = project.CreateFilter();
            filter.Kind = "Component";

            // get all components
            var components = project.AllFCOs(filter).OfType<IMgaModel>().Cast<IMgaModel>().ToList();

            // store components that may have an option (e.g. MM1, MM2)
            List<IMgaModel> componentsToShow = new List<IMgaModel>();

            // iterate through all components
            // select only those which has more than one modelica model in it
            foreach (var component in components)
            {
                var modelicaModels = component.ChildFCOs.Cast<IMgaFCO>().Where(x => x.Meta.Name == "ModelicaModel");
                if (modelicaModels.Count() > 1)
                {
                    componentsToShow.Add(component);
                }
            }

            using (FidelitySelectorForm fsf = new FidelitySelectorForm())
            {

                // show the form for the user
                foreach (var component in componentsToShow)
                {
                    if (fsf.componentItems.FirstOrDefault(
                        x => x.Classification == component.StrAttrByName["Classifications"]) == null)
                    {
                        fsf.componentItems.Add(new ComponentItem(component));
                    }
                }

                // get the current fidelity settings from the Testbench registry
                fsf.FidelitySettings = currentobj.RegistryValue["FidelitySettings"];

                fsf.PopulateDgv();
                fsf.ShowDialog();

                foreach (string msg in fsf.consoleMessages)
                {
                    GMEConsole.Info.WriteLine(msg);
                }

                // Check where the new fidelity settings should be applied:
                if (fsf.rbThisTestbench.Checked)
                {
                    // Write the updated fidelity settings back to the Testbench registry
                    currentobj.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;
                }
                else if (fsf.rbThisFolder.Checked)
                {
                    // Get all testbenches in the same folder as currentobj
                    var thisTestingFolder = currentobj.ParentFolder;
                    var siblingTBs =
                        thisTestingFolder.ChildFCOs.Cast<IMgaFCO>().Where(x => x.Meta.Name == "TestBench").ToList();

                    GMEConsole.Info.WriteLine(
                        "Applying these FidelitySettings to all TestBenches in folder '{0}':", thisTestingFolder.Name);

                    // Go through each one and set the fidelity settings
                    foreach (MgaFCO testbench in siblingTBs)
                    {
                        testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;

                        GMEConsole.Info.WriteLine("=> {0}", testbench.Name); 
                    }
                }
                else if (fsf.rbThisProject.Checked)
                {
                    // Get all testbenches in the entire project
                    MgaFilter testbenchFilter = project.CreateFilter();
                    testbenchFilter.Kind = "TestBench";

                    // get all testbenches
                    var testbenches = project.AllFCOs(testbenchFilter).OfType<IMgaModel>().Cast<IMgaModel>().ToList();

                    GMEConsole.Info.WriteLine(
                        "Applying these FidelitySettings to all TestBenches in project '{0}':", project.Name);

                    // Go through each one and set the fidelity settings
                    foreach (MgaFCO testbench in testbenches)
                    {
                        testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;

                        GMEConsole.Info.WriteLine("=> {0}", testbench.Name); 
                    }
                }
            }


            GMEConsole.Info.WriteLine("{0} finished.", ComponentName);
        }
Example #14
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;

            #region Prompt for Output Path
            // Get an output path from the user.
            String s_outPath;
            using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
            {
                Description = "Choose a path for the generated files.",
                //ShowNewFolderButton = true,
                SelectedPath = Environment.CurrentDirectory,
            })
            {
                DialogResult dr = fbd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    s_outPath = fbd.SelectedPath;
                }
                else
                {
                    GMEConsole.Warning.WriteLine("Design Exporter cancelled");
                    return;
                }
            }
            #endregion

            GMEConsole.Info.WriteLine("Beginning Export...");
            var testBanches = new List <CyPhy.TestBench>();

            if (currentobj != null &&
                currentobj.Meta.Name == "TestBench")
            {
                testBanches.Add(CyPhyClasses.TestBench.Cast(currentobj));
            }
            else if (selectedobjs.Count > 0)
            {
                foreach (MgaFCO mf in selectedobjs)
                {
                    if (mf.Meta.Name == "TestBench")
                    {
                        testBanches.Add(CyPhyClasses.TestBench.Cast(mf));
                    }
                }
            }
            else
            {
                CyPhy.RootFolder root = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);

                MgaFilter filter = project.CreateFilter();
                filter.Kind = "TestBench";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        testBanches.Add(CyPhyClasses.TestBench.Cast(item));
                    }
                }
            }

            foreach (var tb in testBanches)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    ExportToFile(tb, s_outPath);
                }
                catch (Exception ex)
                {
                    GMEConsole.Error.WriteLine("{0}: Exception encountered ({1})", tb.Name, ex.Message);
                }
                GMEConsole.Info.WriteLine("{0}: {1}", tb.Name, s_outPath);
            }
        }
Example #15
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            GMEConsole.Clear();
            GMEConsole.Out.WriteLine("Running interpreter...");
			
			// Get RootFolder
			IMgaFolder rootFolder = project.RootFolder;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Json Files (*.json)|*.json";
            
            var userClickedOK = openFileDialog1.ShowDialog();

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

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


                    // create material folders                    
                    if (materialKeys.Count() > 0)
                    {

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


                    }
                   
                }
            }
            else
                return;
            
            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);			
        }
Example #16
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string projroot = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));

            // TODO: Add your interpreter code
            Logger.WriteInfo("Running {0}...", this.ComponentName);

            string[]     FileNames = null;
            DialogResult dr;

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

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    FileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    ImportFiles(project, projroot, FileNames);
                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);

                Logger.WriteSuccess("{0} complete", this.ComponentName);
                return;
            }
            else
            {
                Logger.WriteFailed("Component Importer canceled");
            }

            return;
        }
Example #17
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;
            }
        }
        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;
            }
        }
Example #19
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            GMEConsole.Out.WriteLine("Running interpreter...");

            // Get RootFolder
            $GET_ROOTFOLDER_CODE$

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Interfaces;" to the top of this file
            // if (currentobj != null && currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);
        }
Example #20
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string projroot = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));

            // TODO: Add your interpreter code
            GMEConsole.Out.WriteLine("Running Component Importer...");

            string[]     FileNames = null;
            DialogResult dr;

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

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    FileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    ImportFiles(project, projroot, FileNames);
                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);
                return;
            }
            else
            {
                GMEConsole.Warning.WriteLine("Component Importer canceled");
                return;
            }

            // Get RootFolder
            //IMgaFolder rootFolder = project.RootFolder;
            //GMEConsole.Out.WriteLine(rootFolder.Name);
        }
Example #21
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // Check if OpenModelica is installed properly
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENMODELICAHOME")))
            {
                this.Logger.WriteFailed(
                    "OpenModelica is probably not installed. OPENMODELICAHOME environment variable needs to be set. <a href=\"https://openmodelica.org\">https://openmodelica.org</a>");

                return;
            }

            // nothing is open, import multiple components to folder 'ModelicaImports'
            if (currentobj == null)
            {
                MessageBox.Show(
                    "New Components/TestComponents will be created in the folder 'ModelicaImports'.",
                    "For Your Information",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                this.Logger.WriteInfo("New Components/TestComponents will be created in the folder 'ModelicaImports'.");

                // call ModelicaModelPicker with selectMultiple = true
                using (ModelicaModelPicker modelpicker = new ModelicaModelPicker(true, project, this.Logger))
                {
                    var dialogResult = modelpicker.ShowDialog();
                    if (dialogResult != System.Windows.Forms.DialogResult.OK)
                    {
                        this.Logger.WriteInfo("Modelica import was cancelled by the user.");
                        return;
                    }
                }
            }
            else
            {
                if ((currentobj.Meta.Name != typeof(CyPhy.Component).Name &&
                     currentobj.Meta.Name != typeof(CyPhy.TestComponent).Name))
                {
                    this.Logger.WriteError("Please open a Component or TestComponent and try again.");
                    return;
                }

                if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
                {
                    var childObjects = currentobj.ChildObjects;

                    foreach (MgaObject child in childObjects)
                    {
                        if (child.MetaBase.Name == "ModelicaModel")
                        {
                            this.Logger.WriteError("TestComponent {0} already has a ModelicaModel. Only one is allowed.", currentobj.Name);
                            return;
                        }
                    }
                }

                CyPhy.ComponentType cyphyComponent = null;
                if (currentobj.Meta.Name == typeof(CyPhy.Component).Name)
                {
                    cyphyComponent = CyPhyClasses.Component.Cast(currentobj);
                }
                else if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
                {
                    cyphyComponent = CyPhyClasses.TestComponent.Cast(currentobj);
                }

                // per META-2674
                if (cyphyComponent.IsLib)
                {
                    this.Logger.WriteError("Cannot modify a model in an attached Library; please select a valid Component or TestComponent.");
                    return;
                }

                // per META-2673
                if (cyphyComponent.IsInstance)
                {
                    this.Logger.WriteError("Cannot modify an Instance; please select a non-Instance Component or TestComponent.");
                    return;
                }

                string message = string.Format("All selected Modelica models will be added to {0}.", currentobj.Name);

                MessageBox.Show(
                    message,
                    "For Your Information",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                this.Logger.WriteInfo(message);

                // call ModelicaModelPicker with selectMultiple = false
                using (ModelicaModelPicker modelpicker = new ModelicaModelPicker(false, project, this.Logger, cyphyComponent))
                {
                    var dialogResult = modelpicker.ShowDialog();
                    if (dialogResult != System.Windows.Forms.DialogResult.OK)
                    {
                        this.Logger.WriteInfo("Modelica import was cancelled by the user.");
                        return;
                    }
                }
            }
        }
Example #22
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            GMEConsole.Clear();
            GMEConsole.Out.WriteLine("Running interpreter...");

            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

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

            var userClickedOK = openFileDialog1.ShowDialog();

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

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


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

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);
        }
Example #23
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: show how to initialize DSML-generated classes

            myMig = new myMigrator(project);
            mig   = new Migrator(project);

            if (currentobj != null)
            {
                if (currentobj is MgaModel)
                {
                    GMEConsole.Info.WriteLine(
                        "Migrating {0}... (To migrate the whole project, close all models and try again)",
                        currentobj.Name);

                    //myMig.migrateModel(currentobj as MgaModel);
                    mig.findOldPortTypes(project, false);

                    try
                    {
                        mig.migrateModel(currentobj as MgaModel);
                    }
                    catch (Exception ex)
                    {
                        GMEConsole.Error.WriteLine("{0}", ex.Message);
                        GMEConsole.Info.WriteLine("{0}", ex.StackTrace);
                    }
                }
            }
            else
            {
                //mig.convertFluidParameters(project);

                GMEConsole.Info.WriteLine("Migrating the entire project...");
                myMig.migrateProject();

                mig.findOldPortTypes(project, false);
                mig.migrateCyPhy2ModelicaWorkflow(project);

                List <string> kinds = new List <string>()
                {
                    "TestBench",
                    "ComponentAssembly",
                    "DesignContainer",
                    "TestComponent",
                    "Component",
                    "Environment"
                };

                MgaFilter cyPhyModelFilter = project.CreateFilter();

                cyPhyModelFilter.ObjType = objtype_enum.OBJTYPE_MODEL.ToString();

                var objectsToMigrate = project
                                       .AllFCOs(cyPhyModelFilter)
                                       .OfType <MgaModel>()
                                       .Where(x => x.ParentModel == null &&
                                              kinds.Contains(x.Meta.Name));

                foreach (var objectToMigrate in objectsToMigrate)
                {
                    //GMEConsole.Info.WriteLine(
                    //    "== Migrating <a href=\"mga:{0}\">{1}</a>",
                    //    objectToMigrate.ID,
                    //    objectToMigrate.Name);
                    try
                    {
                        mig.migrateModel(objectToMigrate);
                    }
                    catch (Exception ex)
                    {
                        GMEConsole.Error.WriteLine("{0}", ex.Message);
                        GMEConsole.Info.WriteLine("{0}", ex.StackTrace);
                    }
                }
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            if (currentobj == null)
            {
                GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName);
                return;
            }
            else if (currentobj.Meta.Name != "TestBench")
            {
                GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName);
                return;
            }

            GMEConsole.Info.WriteLine("Running {0} on TestBench '{1}'", ComponentName, currentobj.Name);

            // get root folder
            IMgaFolder rootFolder = project.RootFolder;

            // create a filter for components
            MgaFilter filter = project.CreateFilter();

            filter.Kind = "Component";

            // get all components
            var components = project.AllFCOs(filter).OfType <IMgaModel>().Cast <IMgaModel>().ToList();

            // store components that may have an option (e.g. MM1, MM2)
            List <IMgaModel> componentsToShow = new List <IMgaModel>();

            // iterate through all components
            // select only those which has more than one modelica model in it
            foreach (var component in components)
            {
                var modelicaModels = component.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "ModelicaModel");
                if (modelicaModels.Count() > 1)
                {
                    componentsToShow.Add(component);
                }
            }

            using (FidelitySelectorForm fsf = new FidelitySelectorForm())
            {
                // show the form for the user
                foreach (var component in componentsToShow)
                {
                    if (fsf.componentItems.FirstOrDefault(
                            x => x.Classification == component.StrAttrByName["Classifications"]) == null)
                    {
                        fsf.componentItems.Add(new ComponentItem(component));
                    }
                }

                // get the current fidelity settings from the Testbench registry
                fsf.FidelitySettings = currentobj.RegistryValue["FidelitySettings"];

                fsf.PopulateDgv();
                fsf.ShowDialog();

                foreach (string msg in fsf.consoleMessages)
                {
                    GMEConsole.Info.WriteLine(msg);
                }

                // Check where the new fidelity settings should be applied:
                if (fsf.rbThisTestbench.Checked)
                {
                    // Write the updated fidelity settings back to the Testbench registry
                    currentobj.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;
                }
                else if (fsf.rbThisFolder.Checked)
                {
                    // Get all testbenches in the same folder as currentobj
                    var thisTestingFolder = currentobj.ParentFolder;
                    var siblingTBs        =
                        thisTestingFolder.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "TestBench").ToList();

                    GMEConsole.Info.WriteLine(
                        "Applying these FidelitySettings to all TestBenches in folder '{0}':", thisTestingFolder.Name);

                    // Go through each one and set the fidelity settings
                    foreach (MgaFCO testbench in siblingTBs)
                    {
                        testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;

                        GMEConsole.Info.WriteLine("=> {0}", testbench.Name);
                    }
                }
                else if (fsf.rbThisProject.Checked)
                {
                    // Get all testbenches in the entire project
                    MgaFilter testbenchFilter = project.CreateFilter();
                    testbenchFilter.Kind = "TestBench";

                    // get all testbenches
                    var testbenches = project.AllFCOs(testbenchFilter).OfType <IMgaModel>().Cast <IMgaModel>().ToList();

                    GMEConsole.Info.WriteLine(
                        "Applying these FidelitySettings to all TestBenches in project '{0}':", project.Name);

                    // Go through each one and set the fidelity settings
                    foreach (MgaFCO testbench in testbenches)
                    {
                        testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;

                        GMEConsole.Info.WriteLine("=> {0}", testbench.Name);
                    }
                }
            }


            GMEConsole.Info.WriteLine("{0} finished.", ComponentName);
        }
 public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
 {
     GMEConsole.Error.WriteLine("This interpreter doesn't run in console mode.");
 }
Example #26
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;
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            Boolean disposeLogger = false;
            if (Logger == null)
            {
                Logger = new CyPhyGUIs.GMELogger(project, "CyPhyDesignExporter");
                disposeLogger = true;
            }

            // TODO: Add your interpreter code
            Logger.WriteInfo("Running Design Exporter...");

            #region Prompt for Output Path
            // Get an output path from the user.
            if (this.OutputDir == null)
            {
                using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
                {
                    Description = "Choose a path for the generated files.",
                    //ShowNewFolderButton = true,
                    SelectedPath = Environment.CurrentDirectory,
                })
                {

                    DialogResult dr = fbd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        OutputDir = fbd.SelectedPath;
                    }
                    else
                    {
                        Logger.WriteWarning("Design Exporter cancelled");
                        return;
                    }
                }
            }
            #endregion

            Logger.WriteInfo("Beginning Export...");
            List<CyPhy.DesignEntity> lde_allCAandDC = new List<CyPhy.DesignEntity>();
            List<CyPhy.TestBenchType> ltbt_allTB = new List<CyPhy.TestBenchType>();
            
            if (currentobj != null && 
                currentobj.Meta.Name == "ComponentAssembly")
            {
                lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(currentobj));
            }
            else if (currentobj != null &&
                     currentobj.Meta.Name == "DesignContainer")
            {
                lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(currentobj));
            }
            else if (currentobj != null &&
                IsTestBenchType(currentobj.MetaBase.Name))
            {
                ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(currentobj));
            }
            else if (selectedobjs != null && selectedobjs.Count > 0)
            {
                foreach (MgaFCO mf in selectedobjs)
                {
                    if (mf.Meta.Name == "ComponentAssembly")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(mf));
                    }
                    else if (mf.Meta.Name == "DesignContainer")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(mf));
                    }
                    else if (IsTestBenchType(mf.MetaBase.Name))
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(mf));
                    }
                }
            }
            else
            {
                CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);

                MgaFilter filter = project.CreateFilter();
                filter.Kind = "ComponentAssembly";
                foreach (var item in project.AllFCOs(filter).Cast<MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(item));
                    }
                }

                filter = project.CreateFilter();
                filter.Kind = "DesignContainer";
                foreach (var item in project.AllFCOs(filter).Cast<MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(item));
                    }
                }

                filter = project.CreateFilter();
                filter.Kind = "TestBenchType";
                foreach (var item in project.AllFCOs(filter).Cast<MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(item));
                    }
                }
            }

            foreach (CyPhy.DesignEntity de in lde_allCAandDC)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    if (de is CyPhy.ComponentAssembly)
                    {
                        ExportToPackage(de as CyPhy.ComponentAssembly, OutputDir);
                    }
                    else
                    {
                        ExportToFile(de, OutputDir);
                    }
                } 
                catch (Exception ex) 
                {
                    Logger.WriteError("{0}: Exception encountered ({1})",de.Name,ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", de.Name, OutputDir);
            }

            foreach (CyPhy.TestBenchType tbt in ltbt_allTB)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    ExportToFile(tbt, OutputDir);
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", tbt.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", tbt.Name, OutputDir);
            }

            Logger.WriteInfo(String.Format("{0} model(s) exported", lde_allCAandDC.Count + ltbt_allTB.Count));
            Logger.WriteInfo("Design Exporter finished");

            if (disposeLogger)
            {
                DisposeLogger();
            }
        }
Example #28
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            GMEConsole = GMEConsole.CreateFromProject(project);
            GMEConsole.Out.WriteLine("Running the AddConnector interpreter...");

            Boolean ownLogger = false;

            if (Logger == null)
            {
                ownLogger = true;
                Logger    = new CyPhyGUIs.GMELogger(project, "AddConnector");
            }

            GMEConsole.Out.WriteLine("\n======================================================================================================================================\n");

            using (Logger)  // Ensure Logger is disposed if there is an unexpected exception. MOT-84
            {
                Logger.WriteInfo("Starting AddConnector.");

                AddConnector(currentobj, selectedobjs);

                Logger.WriteInfo("The AddConnector interpreter has finished.");
            }

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
Example #29
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: show how to initialize DSML-generated classes

            myMig = new myMigrator(project);
            mig = new Migrator(project);

            if (currentobj != null)
            {
                if (currentobj is MgaModel)
                {
                    GMEConsole.Info.WriteLine(
                        "Migrating {0}... (To migrate the whole project, close all models and try again)",
                        currentobj.Name);

                    //myMig.migrateModel(currentobj as MgaModel);
                    mig.findOldPortTypes(project, false);

                    try
                    {
                        mig.migrateModel(currentobj as MgaModel);
                    }
                    catch (Exception ex)
                    {
                        GMEConsole.Error.WriteLine("{0}", ex.Message);
                        GMEConsole.Info.WriteLine("{0}", ex.StackTrace);
                    }
                }
            }
            else
            {
                //mig.convertFluidParameters(project);

                GMEConsole.Info.WriteLine("Migrating the entire project...");
                myMig.migrateProject();

                mig.findOldPortTypes(project, false);
                mig.migrateCyPhy2ModelicaWorkflow(project);

                List<string> kinds = new List<string>()
                    {
                        "TestBench",
                        "ComponentAssembly",
                        "DesignContainer",
                        "TestComponent",
                        "Component",
                        "Environment"
                    };

                MgaFilter cyPhyModelFilter = project.CreateFilter();

                cyPhyModelFilter.ObjType = objtype_enum.OBJTYPE_MODEL.ToString();

                var objectsToMigrate = project
                    .AllFCOs(cyPhyModelFilter)
                    .OfType<MgaModel>()
                    .Where(x => x.ParentModel == null &&
                        kinds.Contains(x.Meta.Name));

                foreach (var objectToMigrate in objectsToMigrate)
                {
                    //GMEConsole.Info.WriteLine(
                    //    "== Migrating <a href=\"mga:{0}\">{1}</a>",
                    //    objectToMigrate.ID,
                    //    objectToMigrate.Name);
                    try
                    {
                        mig.migrateModel(objectToMigrate);
                    }
                    catch (Exception ex)
                    {
                        GMEConsole.Error.WriteLine("{0}", ex.Message);
                        GMEConsole.Info.WriteLine("{0}", ex.StackTrace);
                    }

                }
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            GMEConsole.Out.WriteLine("Running Cyber Component Exporter...");
			
            //// Get RootFolder
            //IMgaFolder rootFolder = project.RootFolder;
            //GMEConsole.Out.WriteLine(rootFolder.Name);
            
            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);			

            // Adapted from CyPhyComponentExporter.cs
            //#region Prompt for Output Path

            //string startupPath = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));

            // Make sure Cyber output paths exist.
            String s_outPath = ".";
            if (!Directory.Exists(s_outPath + "\\Cyber"))
            {
                Directory.CreateDirectory(s_outPath + "\\Cyber");
            }

            
            //#endregion

            GMEConsole.Info.WriteLine("Beginning Export...");

            string filename = project.ProjectConnStr;
            if (filename.Length > 4)
            {
                filename = filename.Substring(4);
            }
            else
            {
                GMEConsole.Info.WriteLine("Invalid MGA connection string for project. Can not determine file name. Bailing out...");
                throw new System.Exception("Invalid MGA connection string.");
            }

            HashSet<Cyber.ModelicaComponent> cyberComponentSet = null;
            if (currentobj != null)
            {
                cyberComponentSet = ComponentLister.getCyberComponentSet(currentobj);
            }
            else if (selectedobjs.Count > 0)
            {
                cyberComponentSet = new HashSet<Cyber.ModelicaComponent>();
                foreach (MgaFCO mf in selectedobjs)
                {
                    cyberComponentSet.UnionWith(ComponentLister.getCyberComponentSet(mf));
                }
            }
            else
            {
                cyberComponentSet = ComponentLister.getCyberComponentSet(project.RootFolder);
            }

            // Debug
            foreach (Cyber.ModelicaComponent cyberComponent in cyberComponentSet)
            {
                GMEConsole.Info.WriteLine("");
                GMEConsole.Info.Write("Processing Component ... " + cyberComponent.Path);
                AVMComponentBuilder avmComponentBuilder = new AVMComponentBuilder();
                avmComponentBuilder.GMEConsole = GMEConsole;
                avmComponentBuilder.createAVMCyberModel(cyberComponent, filename);
                String s_outFilePath = String.Format("{0}\\{1}.component.acm", s_outPath, META2AVM_Util.UtilFuncs.Safeify(cyberComponent.Name));
                META2AVM_Util.UtilFuncs.SerializeAvmComponent(avmComponentBuilder.getAVMComponent(), s_outFilePath);
                GMEConsole.Info.Write("... Exported " + cyberComponent.Path + " to " + s_outFilePath);
            }

            try
            {
                string[] path_parts = filename.Split('\\');
                string filename_part = path_parts[path_parts.Length - 1];
                path_parts[path_parts.Length - 1] = "Cyber";
                string path_part = System.IO.Path.Combine(path_parts);
                //GMEConsole.Info.Write("Copying " + filename + " to " + System.IO.Path.Combine(path_part, filename_part) );
                GMEConsole.Info.Write("Copying " + filename_part + " to " + System.IO.Path.Combine("Cyber", filename_part));
                // copy the project file to the Cyber subdirectory
                System.IO.File.Copy(filename_part, System.IO.Path.Combine("Cyber", filename_part), true);
            }
            catch (Exception err_copy_model_file)
            {
                GMEConsole.Error.Write("Error copying model file to Cyber subdirectory: " + err_copy_model_file.Message);
                return;
            }

            // Try to create the corresponding XML file
            InvokeUDMCopy invokeUdmCopy = new InvokeUDMCopy();
            if (invokeUdmCopy.GenerateXML(project, filename) == true)
            {
                GMEConsole.Out.WriteLine("Finished XML generation.");
            }
            else
            {
                GMEConsole.Out.WriteLine("XML not generated.");
            }

            GMEConsole.Info.WriteLine("Cyber Component Exporter finished!");
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // This is the main ShowNet interpreter code
            Boolean ownLogger = false;
            if (Logger == null)
            {
                ownLogger = true;
                Logger = new CyPhyGUIs.GMELogger(project, "ShowNet");
            }
            GMEConsole.Out.WriteLine("\n======================================================================================================================================\n");
            Logger.WriteInfo("Starting ShowNet.");

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

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

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

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

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

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

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

                NetworkManager portNetworkManager = new NetworkManager();

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

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

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

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

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

                NetworkManager connectorNetworkManager = new NetworkManager();

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

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

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

                // Display all the networks.

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

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

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

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

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

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);

            // TODO: find model editor window and open form inside it. Would be nice to find it based on  C++ class.
            var mainHwd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

            IntPtr mdiClient = IntPtr.Zero;

            foreach (var childHwd in GetChildWindows(mainHwd))
            {
                StringBuilder sb = new StringBuilder(100);
                GetClassName(childHwd, sb, 100);
                if ("MDIClient" == sb.ToString())
                {
                    mdiClient = childHwd;
                    break;
                }
            }

            //GMEConsole.Warning.WriteLine("Name: '{0}' Position: {1} {2} {3} {4}", name, rr.Top, rr.Left, rr.Bottom, rr.Right);

            List <string> supportedKinds = new List <string>()
            {
                typeof(CyPhy.Component).Name,
                typeof(CyPhy.ComponentAssembly).Name,
                typeof(CyPhy.TestComponent).Name,
                typeof(CyPhy.DesignContainer).Name,
                typeof(CyPhy.TestBench).Name,
                typeof(CyPhy.BlastTestBench).Name,
                typeof(CyPhy.BallisticTestBench).Name,
                typeof(CyPhy.CADTestBench).Name,
                typeof(CyPhy.CFDTestBench).Name,
                typeof(CyPhy.TestBenchSuite).Name,
            };

            if (currentobj == null ||
                supportedKinds.Contains(currentobj.Meta.Name) == false)
            {
                GMEConsole.Warning.WriteLine("One of the following object types must be open in the editor: {0}", string.Join(", ", supportedKinds));
                return;
            }

            List <ComponentParameterItem> parameterItems = new List <ComponentParameterItem>();

            if (currentobj.Meta.Name == typeof(CyPhy.Component).Name ||
                currentobj.Meta.Name == typeof(CyPhy.ComponentAssembly).Name)
            {
                var component = CyPhyClasses.DesignElement.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }
            else if (currentobj.Meta.Name == typeof(CyPhy.DesignContainer).Name)
            {
                var component = CyPhyClasses.DesignContainer.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }
            else if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
            {
                var component = CyPhyClasses.TestComponent.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.MetricCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        //GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        //continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }

            else if (currentobj.Meta.Name == typeof(CyPhy.TestBench).Name ||
                     currentobj.Meta.Name == typeof(CyPhy.BlastTestBench).Name ||
                     currentobj.Meta.Name == typeof(CyPhy.BallisticTestBench).Name ||
                     currentobj.Meta.Name == typeof(CyPhy.CADTestBench).Name ||
                     currentobj.Meta.Name == typeof(CyPhy.CFDTestBench).Name)
            {
                var component = CyPhyClasses.TestBenchType.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.MetricCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        //GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        //continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }
            else if (currentobj.Meta.Name == typeof(CyPhy.TestBenchSuite).Name)
            {
                var component = CyPhyClasses.TestBenchSuite.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.MetricCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        //GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        //continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }

            parameterItems.Sort((x, y) => x.Name.CompareTo(y.Name));

            if (parameterItems.Any() == false)
            {
                GMEConsole.Warning.WriteLine("Please insert at least one non-derived Parameter/Property in the model.");
                return;
            }

            using (ComponentParameterForm cpForm = new ComponentParameterForm(currentobj))
            {
                cpForm.dgvParameters.DataSource = new BindingList <ComponentParameterItem>(parameterItems);
                if (mdiClient != IntPtr.Zero)
                {
                    // TODO: would be nice to attach the form to the MDIClient window.
                    var parentWindow = new NativeWindowWrapper(mdiClient);
                    var dialogResult = cpForm.ShowDialog(parentWindow);
                }
                else
                {
                    var dialogResult = cpForm.ShowDialog();
                }
            }
        }
 public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
 {
     throw new NotImplementedException("Function Main(MgaProject, MgaFCO, MgaFCOs, ComponentStartMode) not implemented.");
 }
Example #34
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            if (currentobj.Meta.Name == "TestBench")
            {
                CyPhy.TestBench tb = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.TestBench>(currentobj as MgaObject);

                //var sut = tb.Children.TopLevelSystemUnderTestCollection.FirstOrDefault();
                //String s_sutName = sut.Name;

                CyPhy.ComponentAssembly sut = null;
                foreach (CyPhy.ComponentAssembly ca in tb.Children.ComponentAssemblyCollection)
                {
                    if ((ca.Impl as MgaFCO).get_RegistryValue("ElaboratedModel") != "")
                    {
                        sut = ca;
                    }
                }

                if (sut != null)
                {
                    var dm = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(sut);
                    //dm = MakeFakeModel();
                    //String json = dm.Serialize();
                    String json     = XSD2CSharp.AvmXmlSerializer.Serialize(dm);
                    int    json_len = json.Length;
                    dm.SaveToFile(Path.Combine(OutputDirectory, dm.Name + ".adm"));

                    Complexity.Design           cd          = METADesignInterchange2ComplexityLib.METADesign2Complexity.Design2Complexity(dm);
                    Dictionary <string, string> dCSV_output = cd.SerializeToCSVFormat();

                    foreach (KeyValuePair <string, string> kvp in dCSV_output)
                    {
                        String s_filePath = Path.Combine(OutputDirectory, kvp.Key);
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s_filePath))
                        {
                            sw.Write(kvp.Value);
                        }
                    }

                    string mainPythonFilename = Path.Combine(OutputDirectory, "ComplexityMain.py");
                    string mainCmdFilename    = Path.Combine(OutputDirectory, "RunComplexityEvaluator.cmd");

                    using (StreamWriter writer = new StreamWriter(mainPythonFilename))
                    {
                        writer.WriteLine(CyPhyComplexity.Properties.Resources.ComplexityMain);
                    }
                    using (StreamWriter writer = new StreamWriter(mainCmdFilename))
                    {
                        writer.WriteLine("call \"{0}\"", META_PATH_PYTHON_ACTIVATE);
                        writer.WriteLine("python {0}  Components.csv Connections.csv 1", mainPythonFilename);

                        //writer.WriteLine(CyPhyComplexity.Properties.Resources.RunComplexityEvaluator);
                    }

                    if (dCSV_output.Count == 2)
                    {
                        result.RunCommand = "RunComplexityEvaluator.cmd";
                    }

                    GMEConsole.Info.WriteLine(
                        "Result files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>.",
                        Path.GetFullPath(OutputDirectory));
                }
            }
        }
Example #35
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);
        }
Example #36
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            Boolean disposeLogger = false;

            if (Logger == null)
            {
                Logger        = new CyPhyGUIs.GMELogger(project, "CyPhyDesignExporter");
                disposeLogger = true;
            }

            // TODO: Add your interpreter code
            Logger.WriteInfo("Running Design Exporter...");

            #region Prompt for Output Path
            // Get an output path from the user.
            if (this.OutputDir == null)
            {
                using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
                {
                    Description = "Choose a path for the generated files.",
                    //ShowNewFolderButton = true,
                    SelectedPath = Environment.CurrentDirectory,
                })
                {
                    DialogResult dr = fbd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        OutputDir = fbd.SelectedPath;
                    }
                    else
                    {
                        Logger.WriteWarning("Design Exporter cancelled");
                        return;
                    }
                }
            }
            #endregion

            Logger.WriteInfo("Beginning Export...");
            List <CyPhy.DesignEntity>  lde_allCAandDC = new List <CyPhy.DesignEntity>();
            List <CyPhy.TestBenchType> ltbt_allTB     = new List <CyPhy.TestBenchType>();

            if (currentobj != null &&
                currentobj.Meta.Name == "ComponentAssembly")
            {
                lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(currentobj));
            }
            else if (currentobj != null &&
                     currentobj.Meta.Name == "DesignContainer")
            {
                lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(currentobj));
            }
            else if (currentobj != null &&
                     IsTestBenchType(currentobj.MetaBase.Name))
            {
                ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(currentobj));
            }
            else if (selectedobjs != null && selectedobjs.Count > 0)
            {
                foreach (MgaFCO mf in selectedobjs)
                {
                    if (mf.Meta.Name == "ComponentAssembly")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(mf));
                    }
                    else if (mf.Meta.Name == "DesignContainer")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(mf));
                    }
                    else if (IsTestBenchType(mf.MetaBase.Name))
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(mf));
                    }
                }
            }
            else
            {
                CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);

                MgaFilter filter = project.CreateFilter();
                filter.Kind = "ComponentAssembly";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(item));
                    }
                }

                filter      = project.CreateFilter();
                filter.Kind = "DesignContainer";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(item));
                    }
                }

                filter      = project.CreateFilter();
                filter.Kind = "TestBenchType";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(item));
                    }
                }
            }

            foreach (CyPhy.DesignEntity de in lde_allCAandDC)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    if (de is CyPhy.ComponentAssembly)
                    {
                        ExportToPackage(de as CyPhy.ComponentAssembly, OutputDir);
                    }
                    else
                    {
                        ExportToFile(de, OutputDir);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", de.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", de.Name, OutputDir);
            }

            foreach (CyPhy.TestBenchType tbt in ltbt_allTB)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    ExportToFile(tbt, OutputDir);
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", tbt.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", tbt.Name, OutputDir);
            }

            Logger.WriteInfo(String.Format("{0} model(s) exported", lde_allCAandDC.Count + ltbt_allTB.Count));
            Logger.WriteInfo("Design Exporter finished");

            if (disposeLogger)
            {
                DisposeLogger();
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {

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

            // TODO: find model editor window and open form inside it. Would be nice to find it based on  C++ class.
            var mainHwd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

            IntPtr mdiClient = IntPtr.Zero;

            foreach (var childHwd in GetChildWindows(mainHwd))
            {
                StringBuilder sb = new StringBuilder(100);
                GetClassName(childHwd, sb, 100);
                if ("MDIClient" == sb.ToString())
                {
                    mdiClient = childHwd;
                    break;
                }
            }

            //GMEConsole.Warning.WriteLine("Name: '{0}' Position: {1} {2} {3} {4}", name, rr.Top, rr.Left, rr.Bottom, rr.Right);

            List<string> supportedKinds = new List<string>()
            {
                typeof(CyPhy.Component).Name,
                typeof(CyPhy.ComponentAssembly).Name,
                typeof(CyPhy.TestComponent).Name,
                typeof(CyPhy.DesignContainer).Name,
                typeof(CyPhy.TestBench).Name,
                typeof(CyPhy.BlastTestBench).Name,
                typeof(CyPhy.BallisticTestBench).Name,
                typeof(CyPhy.CADTestBench).Name,
                typeof(CyPhy.CFDTestBench).Name,
                typeof(CyPhy.TestBenchSuite).Name,
            };

            if (currentobj == null ||
                supportedKinds.Contains(currentobj.Meta.Name) == false)
            {
                GMEConsole.Warning.WriteLine("One of the following object types must be open in the editor: {0}", string.Join(", ", supportedKinds));
                return;
            }

            List<ComponentParameterItem> parameterItems = new List<ComponentParameterItem>();

            if (currentobj.Meta.Name == typeof(CyPhy.Component).Name ||
                currentobj.Meta.Name == typeof(CyPhy.ComponentAssembly).Name)
            {
                var component = CyPhyClasses.DesignElement.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }
            else if (currentobj.Meta.Name == typeof(CyPhy.DesignContainer).Name)
            {
                var component = CyPhyClasses.DesignContainer.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

            }
            else if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
            {
                var component = CyPhyClasses.TestComponent.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.MetricCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        //GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        //continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }

            else if (currentobj.Meta.Name == typeof(CyPhy.TestBench).Name ||
                currentobj.Meta.Name == typeof(CyPhy.BlastTestBench).Name ||
                currentobj.Meta.Name == typeof(CyPhy.BallisticTestBench).Name ||
                currentobj.Meta.Name == typeof(CyPhy.CADTestBench).Name ||
                currentobj.Meta.Name == typeof(CyPhy.CFDTestBench).Name)
            {
                var component = CyPhyClasses.TestBenchType.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.PropertyCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.MetricCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        //GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        //continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }
            else if (currentobj.Meta.Name == typeof(CyPhy.TestBenchSuite).Name)
            {
                var component = CyPhyClasses.TestBenchSuite.Cast(currentobj);

                foreach (var item in component.Children.ParameterCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not  shown in list.", item.Name);
                        continue;
                    }

                    parameterItems.Add(parameterItem);
                }

                foreach (var item in component.Children.MetricCollection)
                {
                    var parameterItem = new ComponentParameterItem(item.Impl as MgaFCO);

                    if (item.SrcConnections.ValueFlowCollection.Where(x => x.ParentContainer.ID == item.ParentContainer.ID).Count() > 0)
                    {
                        // skip derived parameters
                        //GMEConsole.Info.WriteLine("{0} is a derived parameter; it is not shown in list.", item.Name);
                        //continue;
                    }

                    parameterItems.Add(parameterItem);
                }
            }

            parameterItems.Sort((x, y) => x.Name.CompareTo(y.Name));

            if (parameterItems.Any() == false)
            {
                GMEConsole.Warning.WriteLine("Please insert at least one non-derived Parameter/Property in the model.");
                return;
            }

            using (ComponentParameterForm cpForm = new ComponentParameterForm(currentobj))
            {
                cpForm.dgvParameters.DataSource = new BindingList<ComponentParameterItem>(parameterItems);
                if (mdiClient != IntPtr.Zero)
                {
                    // TODO: would be nice to attach the form to the MDIClient window.
                    var parentWindow = new WindowWrapper(mdiClient);
                    var dialogResult = cpForm.ShowDialog(parentWindow);
                }
                else
                {
                    var dialogResult = cpForm.ShowDialog();
                }
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
			// Get RootFolder
			IMgaFolder rootFolder = project.RootFolder;

            #region Prompt for Output Path
            // Get an output path from the user.
            String s_outPath;
            using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
            {
                Description = "Choose a path for the generated files.",
                //ShowNewFolderButton = true,
                SelectedPath = Environment.CurrentDirectory,
            })
            {

                DialogResult dr = fbd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    s_outPath = fbd.SelectedPath;
                }
                else
                {
                    GMEConsole.Warning.WriteLine("Design Exporter cancelled");
                    return;
                }
            }
            #endregion

            GMEConsole.Info.WriteLine("Beginning Export...");
            var testBanches = new List<CyPhy.TestBench>();

            if (currentobj != null &&
                currentobj.Meta.Name == "TestBench")
            {
                testBanches.Add(CyPhyClasses.TestBench.Cast(currentobj));
            }
            else if (selectedobjs.Count > 0)
            {
                foreach (MgaFCO mf in selectedobjs)
                {
                    if (mf.Meta.Name == "TestBench")
                    {
                        testBanches.Add(CyPhyClasses.TestBench.Cast(mf));
                    }
                }
            }
            else
            {
                CyPhy.RootFolder root = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);

                MgaFilter filter = project.CreateFilter();
                filter.Kind = "TestBench";
                foreach (var item in project.AllFCOs(filter).Cast<MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        testBanches.Add(CyPhyClasses.TestBench.Cast(item));
                    }
                }
            }

            foreach (var tb in testBanches)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    ExportToFile(tb, s_outPath);
                }
                catch (Exception ex)
                {
                    GMEConsole.Error.WriteLine("{0}: Exception encountered ({1})", tb.Name, ex.Message);
                }
                GMEConsole.Info.WriteLine("{0}: {1}", tb.Name, s_outPath);
            }

        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            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 (*.*)|*.*";

                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);

                if (result.Length > 0 && GMEConsole.gme != null)
                {
                    GMEConsole.gme.ShowFCO((MgaFCO)result[0].Impl);
                }
                return;
            }
            else
            {
                GMEConsole.Warning.WriteLine("Design Importer canceled");
                return;
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            GMEConsole.Clear();
            System.Windows.Forms.Application.DoEvents();

            IMgaFCO selectedObj = null;

            bool isContextValid = CheckForValidContext(currentobj);

            if (isContextValid == false)
            {
                return;
            }

            // get all the ComponentRefs in the DesignContainer
            var crefs = (currentobj as IMgaModel).
                ChildFCOs.
                Cast<IMgaFCO>().
                Where(x => x.MetaBase.Name == "ComponentRef");

            // If there is exactly '1', select it
            if (crefs.Count() == 1)
            {
                selectedObj = crefs.FirstOrDefault();
            }

            if (selectedObj == null)
            {
                if (selectedobjs.Count != 1)
                {
                    GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
                    return;
                }
                selectedObj = selectedobjs.Cast<IMgaFCO>().FirstOrDefault();
            }

            if (selectedObj == null)
            {
                GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
                return;
            }

            if (selectedObj.MetaBase.Name != "ComponentRef")
            {
                GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
                return;
            }

            if ((selectedObj as IMgaReference).Referred == null)
            {
                GMEConsole.Error.WriteLine("Selected ComponentRef is a null reference.");
                return;
            }

            GMEConsole.Info.WriteLine("Running CLM_light...");

            // everything is checked we can operate on the objects
            IMgaFCO designContainer = currentobj;
            IMgaFCO componentRef = selectedObj;
            IMgaModel component = (selectedObj as IMgaReference).Referred as IMgaModel;

            GMEConsole.Info.WriteLine("Discovering components.");

            //GMEConsole.Info.WriteLine("{0} components were found.", components.Count);

            // TODO: filter detected components if needed
            using (ComponentSelectionForm csf = new ComponentSelectionForm(component, currentobj as IMgaModel, GMEConsole.Error, GMEConsole.Info))
            {
                var dialogresult = csf.ShowDialog();

                if (dialogresult == System.Windows.Forms.DialogResult.OK)
                {
                    GMEConsole.Info.WriteLine("Inserting new components.");

                    List<IMgaFCO> components = new List<IMgaFCO>();

                    foreach (var item in csf.dgvSelector.SelectedRows)
                    {
                        var dgvr = item as System.Windows.Forms.DataGridViewRow;
                        var cli = dgvr.DataBoundItem as ComponentListItem;
                        components.Add(cli.Fco);
                    }

                    GMEConsole.Info.WriteLine("{0} components were selected.", components.Count);

                    List<KeyValuePair<IMgaFCO, string>> messages = new List<KeyValuePair<IMgaFCO, string>>();

                    var insertedComponents = InsertComponents(designContainer, componentRef, components, messages);
                }
            }
            GMEConsole.Info.WriteLine("Done.");
        }
 public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
 {
     GMEConsole.Error.WriteLine("This interpreter doesn't run in console mode.");
 }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            GMEConsole.Info.WriteLine("Running Component Exporter...");

            #region Prompt for Output Path

            GMEConsole.Info.WriteLine("Beginning Export...");
            int i_count = 0;
            HashSet <CyPhy.Component> cyPhyComponentSet = null;
            if (currentobj != null)
            {
                cyPhyComponentSet = CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet(currentobj);
            }
            else if (selectedobjs != null && selectedobjs.Count > 0)
            {
                cyPhyComponentSet = new HashSet <CyPhy.Component>();
                foreach (MgaFCO mf in selectedobjs)
                {
                    cyPhyComponentSet.UnionWith(CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet(mf));
                }
            }
            else
            {
                cyPhyComponentSet = CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet(project.RootFolder);
            }

            if (cyPhyComponentSet.Count == 0)
            {
                GMEConsole.Warning.WriteLine("Nothing to export.");
                return;
            }

            string startupPath;

            if (false == String.IsNullOrWhiteSpace(previousExportPath) &&
                Directory.Exists(previousExportPath))
            {
                startupPath = previousExportPath;
            }
            else
            {
                startupPath = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
            }

            // Get an output path from the user.
            if (this.OutputDir == null)
            {
                using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
                {
                    Description = "Choose a path for the generated files.",
                    //ShowNewFolderButton = true,
                    SelectedPath = startupPath,
                })
                {
                    DialogResult dr = fbd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        OutputDir          = fbd.SelectedPath;
                        previousExportPath = OutputDir;
                    }
                    else
                    {
                        GMEConsole.Warning.WriteLine("Component Exporter cancelled");
                        return;
                    }
                }
            }
            #endregion

            var ruleChecker = new DesignConsistencyChecker.Framework.Checker(currentobj, project);
            ruleChecker.RegisterRuleDll("DesignConsistencyChecker.dll");
            var uniqueNameRule = ruleChecker.GetRegisteredRules.FirstOrDefault(x => x.Name == "UniquePPMNames");

            foreach (CyPhy.Component c in cyPhyComponentSet)
            {
                if (uniqueNameRule != null)
                {
                    var feedBacks = uniqueNameRule.Check((MgaFCO)c.Impl).ToList();
                    if (feedBacks.Any(x => x.FeedbackType == FeedbackTypes.Error))
                    {
                        foreach (var fb in feedBacks.Where(x => x.FeedbackType == FeedbackTypes.Error))
                        {
                            GMEConsole.Error.WriteLine("Rule {0} failed: {1}", uniqueNameRule.Name, fb.Message);
                        }
                        continue;
                    }
                }

                try
                {
                    ExportComponentPackage(c, OutputDir);
                    i_count++;
                }
                catch (ApplicationException ex)
                {
                    GMEConsole.Error.WriteLine(ex.Message);
                }
                catch (Exception ex)
                {
                    GMEConsole.Error.WriteLine("{0} encountered while exporting {1}: {2}", ex.GetType().Name, c.Name, ex.Message);
                }
            }

            GMEConsole.Info.WriteLine(String.Format("{0} Component(s) exported", i_count));
            GMEConsole.Info.WriteLine("Component Exporter finished");
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // Check if OpenModelica is installed properly
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENMODELICAHOME")))
            {
                this.Logger.WriteFailed(
                    "OpenModelica is probably not installed. OPENMODELICAHOME environment variable needs to be set. <a href=\"https://openmodelica.org\">https://openmodelica.org</a>");

                return;
            }

            // nothing is open, import multiple components to folder 'ModelicaImports'
            if (currentobj == null)
            {
                MessageBox.Show(
                    "New Components/TestComponents will be created in the folder 'ModelicaImports'.",
                    "For Your Information",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                this.Logger.WriteInfo("New Components/TestComponents will be created in the folder 'ModelicaImports'.");

                // call ModelicaModelPicker with selectMultiple = true
                using (ModelicaModelPicker modelpicker = new ModelicaModelPicker(true, project, this.Logger))
                {
                    var dialogResult = modelpicker.ShowDialog();
                    if (dialogResult != System.Windows.Forms.DialogResult.OK)
                    {
                        this.Logger.WriteInfo("Modelica import was cancelled by the user.");
                        return;
                    }
                }
            }
            else
            {
                if ((currentobj.Meta.Name != typeof(CyPhy.Component).Name &&
                    currentobj.Meta.Name != typeof(CyPhy.TestComponent).Name))
                {
                    this.Logger.WriteError("Please open a Component or TestComponent and try again.");
                    return;
                }

                if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
                {
                    var childObjects = currentobj.ChildObjects;

                    foreach (MgaObject child in childObjects)
                    {
                        if (child.MetaBase.Name == "ModelicaModel")
                        {
                            this.Logger.WriteError("TestComponent {0} already has a ModelicaModel. Only one is allowed.", currentobj.Name);
                            return;
                        }
                    }
                }

                CyPhy.ComponentType cyphyComponent = null;
                if (currentobj.Meta.Name == typeof(CyPhy.Component).Name)
                {
                    cyphyComponent = CyPhyClasses.Component.Cast(currentobj);
                }
                else if (currentobj.Meta.Name == typeof(CyPhy.TestComponent).Name)
                {
                    cyphyComponent = CyPhyClasses.TestComponent.Cast(currentobj);
                }

                // per META-2674
                if (cyphyComponent.IsLib)
                {
                    this.Logger.WriteError("Cannot modify a model in an attached Library; please select a valid Component or TestComponent.");
                    return;
                }

                // per META-2673
                if (cyphyComponent.IsInstance)
                {
                    this.Logger.WriteError("Cannot modify an Instance; please select a non-Instance Component or TestComponent.");
                    return;
                }

                string message = string.Format("All selected Modelica models will be added to {0}.", currentobj.Name);

                MessageBox.Show(
                    message,
                    "For Your Information",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                this.Logger.WriteInfo(message);

                // call ModelicaModelPicker with selectMultiple = false
                using (ModelicaModelPicker modelpicker = new ModelicaModelPicker(false, project, this.Logger, cyphyComponent))
                {
                    var dialogResult = modelpicker.ShowDialog();
                    if (dialogResult != System.Windows.Forms.DialogResult.OK)
                    {
                        this.Logger.WriteInfo("Modelica import was cancelled by the user.");
                        return;
                    }
                }
            }
        }
Example #44
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {


        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            GMEConsole.Info.WriteLine("Running Component Exporter...");

            #region Prompt for Output Path

            GMEConsole.Info.WriteLine("Beginning Export...");
            int i_count = 0;
            HashSet<CyPhy.Component> cyPhyComponentSet = null;
            if (currentobj != null)
            {
                cyPhyComponentSet = CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet(currentobj);
            }
            else if (selectedobjs != null && selectedobjs.Count > 0)
            {
                cyPhyComponentSet = new HashSet<CyPhy.Component>();
                foreach (MgaFCO mf in selectedobjs)
                {
                    cyPhyComponentSet.UnionWith(CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet(mf));
                }
            }
            else
            {
                cyPhyComponentSet = CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet(project.RootFolder);
            }

            if (cyPhyComponentSet.Count == 0)
            {
                GMEConsole.Warning.WriteLine("Nothing to export.");
                return;
            }

            // MOT-387: Remember the path used previously
            string startupPath;

            if (false == String.IsNullOrWhiteSpace(previousExportPath)
                 && Directory.Exists(previousExportPath))
            {
                 startupPath = previousExportPath;
            }
            else
            {
                startupPath = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
            }
                        
            // Get an output path from the user.
            if (this.OutputDir == null)
            {
                using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
                {
                    Description = "Choose a path for the generated files.",
                    //ShowNewFolderButton = true,
                    SelectedPath = startupPath,
                })
                {

                    DialogResult dr = fbd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        OutputDir = fbd.SelectedPath;
                        previousExportPath = OutputDir;
                    }
                    else
                    {
                        GMEConsole.Warning.WriteLine("Component Exporter cancelled");
                        return;
                    }
                }
            }
            #endregion

            var ruleChecker = new DesignConsistencyChecker.Framework.Checker(currentobj, project);
            ruleChecker.RegisterRuleDll("DesignConsistencyChecker.dll");
            var uniqueNameRule = ruleChecker.GetRegisteredRules.FirstOrDefault(x => x.Name == "UniquePPMNames");

            foreach (CyPhy.Component c in cyPhyComponentSet)
            {
                if (uniqueNameRule != null)
                {
                    var feedBacks = uniqueNameRule.Check((MgaFCO)c.Impl).ToList();
                    if (feedBacks.Any(x => x.FeedbackType == FeedbackTypes.Error))
                    {
                        foreach (var fb in feedBacks.Where(x => x.FeedbackType == FeedbackTypes.Error))
                        {
                            GMEConsole.Error.WriteLine("Rule {0} failed: {1}", uniqueNameRule.Name, fb.Message);
                        }
                        continue;
                    }
                }

                try
                {
                    ExportComponentPackage(c, OutputDir);                    
                    i_count++;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("{0} encountered while exporting {1}: {2}", ex.GetType().Name, c.Name, ex.Message);
                }
            }

            GMEConsole.Info.WriteLine(String.Format("{0} Component(s) exported", i_count));
            GMEConsole.Info.WriteLine("Component Exporter finished");			
        }
        public bool Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            //GMEConsole.Clear();
            GMEConsole.Out.WriteLine("Running CyPhy2CAD interpreter...");
			
            // TODO: show how to initialize DSML-generated classes
            // Get RootFolder
            //IMgaFolder rootFolder = project.RootFolder;
            //GMEConsole.Out.WriteLine(rootFolder.Name);


            // Check Model
            // Grab all components
            // Create Intermediate Data Representations
            // Walk representation + find islands
            // Convert to DAG

            try
            {

                // META-1971: ADM + ACM file export for blast + ballistics
                // ACM
                {
                    CallComponentExporter(project, currentobj);
                }
                result.Success = true;
                ProcessCAD(currentobj);
                Logger.Instance.DumpLog(GMEConsole, LogDir);
                GMEConsole.Out.WriteLine("Finished CyPhy2CAD with " + (result.Success ? "success" : "failure"));
                return result.Success;
            }
            catch (Exception ex)
            {
                Logger.Instance.AddLogMessage(ex.Message, Severity.Error);
                Logger.Instance.DumpLog(GMEConsole, LogDir);
                GMEConsole.Out.WriteLine("Finished CyPhy2CAD with failure.");
                return false;
            }
        }
Example #47
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;
            }
        }
Example #48
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code

            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;

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

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

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

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

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

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

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

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

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

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

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

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

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

                                    var valueString = "complexResults[" + complexResultsCount++ + "]";
                                    newKnownElements.Add(f.guid);
                                    values.Add(f.guid, valueString);
                                    count++;
                                }
                                else if (f.type == Function.FunctionType.PYTHON)
                                {
                                    var functionName = Path.GetFileNameWithoutExtension(f.python_filename);
                                    file.WriteLine("\nimport " + functionName);
                                    file.WriteLine("pythonResults.append(" + functionName + "." + functionName + "(");
                                    file.Write("    " + String.Join(",\n    ", f.dependencies.Select(x => values[x]).ToList()));
                                    file.WriteLine("))\n");
                                    int outputIndex = 0;
                                    foreach (var output in f.outputs)
                                    {
                                        var valueString = "pythonResults[" + pythonResultsCount + "][" + outputIndex++ + "]";
                                        newKnownElements.Add(output);
                                        values.Add(output, valueString);
                                        count++;
                                    }
                                    newKnownElements.Add(f.guid);
                                    pythonResultsCount++;
                                }
                            }
                        }
                        knownElements.AddRange(newKnownElements);
                        newKnownElements = new List <Guid>();
                    }
                    file.WriteLine("#------ Done! (No new values found.) -------");
                    file.WriteLine("");
                    file.WriteLine("print json.dumps(parameters, indent=2, sort_keys=True)");
                    file.WriteLine("");
                    file.WriteLine("with open('output.json', 'w') as f_out:");
                    file.WriteLine("    json.dump(parameters, f_out, indent=2, sort_keys=True)");
                }
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string projroot = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));

            // TODO: Add your interpreter code
            Logger.WriteInfo("Running {0}...", this.ComponentName);

            string[] FileNames = null;
            DialogResult dr;
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists = true;
                ofd.DefaultExt = "component.acm";
                ofd.Multiselect = true;
                ofd.Filter = "component files (*.acm;*.component.acm;*.zip)|*.acm;*.component.acm;*.zip|All files (*.*)|*.*";

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    FileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    ImportFiles(project, projroot, FileNames);
                }, transactiontype_enum.TRANSACTION_NON_NESTED);

                Logger.WriteSuccess("{0} complete", this.ComponentName);
            }
            else
            {
                Logger.WriteFailed("Component Importer canceled");
            }
            
            return;
        }
Example #50
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            GMEConsole.Clear();
            System.Windows.Forms.Application.DoEvents();

            IMgaFCO selectedObj = null;

            bool isContextValid = CheckForValidContext(currentobj);

            if (isContextValid == false)
            {
                return;
            }

            // get all the ComponentRefs in the DesignContainer
            var crefs = (currentobj as IMgaModel).
                        ChildFCOs.
                        Cast <IMgaFCO>().
                        Where(x => x.MetaBase.Name == "ComponentRef");

            // If there is exactly '1', select it
            if (crefs.Count() == 1)
            {
                selectedObj = crefs.FirstOrDefault();
            }

            if (selectedObj == null)
            {
                if (selectedobjs.Count != 1)
                {
                    GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
                    return;
                }
                selectedObj = selectedobjs.Cast <IMgaFCO>().FirstOrDefault();
            }

            if (selectedObj == null)
            {
                GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
                return;
            }

            if (selectedObj.MetaBase.Name != "ComponentRef")
            {
                GMEConsole.Error.WriteLine(SelectedObjErrorMessage);
                return;
            }

            if ((selectedObj as IMgaReference).Referred == null)
            {
                GMEConsole.Error.WriteLine("Selected ComponentRef is a null reference.");
                return;
            }

            GMEConsole.Info.WriteLine("Running CLM_light...");

            // everything is checked we can operate on the objects
            IMgaFCO   designContainer = currentobj;
            IMgaFCO   componentRef    = selectedObj;
            IMgaModel component       = (selectedObj as IMgaReference).Referred as IMgaModel;

            GMEConsole.Info.WriteLine("Discovering components.");

            //GMEConsole.Info.WriteLine("{0} components were found.", components.Count);

            // TODO: filter detected components if needed
            using (ComponentSelectionForm csf = new ComponentSelectionForm(component, currentobj as IMgaModel, GMEConsole.Error, GMEConsole.Info))
            {
                var dialogresult = csf.ShowDialog();

                if (dialogresult == System.Windows.Forms.DialogResult.OK)
                {
                    GMEConsole.Info.WriteLine("Inserting new components.");

                    List <IMgaFCO> components = new List <IMgaFCO>();

                    foreach (var item in csf.dgvSelector.SelectedRows)
                    {
                        var dgvr = item as System.Windows.Forms.DataGridViewRow;
                        var cli  = dgvr.DataBoundItem as ComponentListItem;
                        components.Add(cli.Fco);
                    }

                    GMEConsole.Info.WriteLine("{0} components were selected.", components.Count);

                    List <KeyValuePair <IMgaFCO, string> > messages = new List <KeyValuePair <IMgaFCO, string> >();

                    var insertedComponents = InsertComponents(designContainer, componentRef, components, messages);
                }
            }
            GMEConsole.Info.WriteLine("Done.");
        }
Example #51
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // This is the main ShowNet interpreter code
            Boolean ownLogger = false;

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

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

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

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

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

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

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

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

                NetworkManager portNetworkManager = new NetworkManager();

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

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

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

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

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

                NetworkManager connectorNetworkManager = new NetworkManager();

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

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

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

                // Display all the networks.

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

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

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

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

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

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string projroot = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));

            // TODO: Add your interpreter code
            GMEConsole.Out.WriteLine("Running Component Importer...");

            string[] FileNames = null;
            DialogResult dr;
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists = true;
                ofd.DefaultExt = "component.acm";
                ofd.Multiselect = true;
                ofd.Filter = "component files (*.acm;*.component.acm;*.zip)|*.acm;*.component.acm;*.zip|All files (*.*)|*.*";

                dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    FileNames = ofd.FileNames;
                }
            }
            if (dr == DialogResult.OK)
            {
                MgaGateway.PerformInTransaction(delegate
                {
                    ImportFiles(project, projroot, FileNames);
                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);
                return;
            }
            else
            {
                GMEConsole.Warning.WriteLine("Component Importer canceled");
                return;
            }

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

        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // TODO: Add your interpreter code
            Logger.WriteDebug("Running interpreter...");
			
			// Get RootFolder
			IMgaFolder rootFolder = project.RootFolder;
			Logger.WriteDebug(rootFolder.Name);
            
            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);			
                        
        }
Example #54
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            this.Logger.WriteInfo("Running Component Authoring interpreter.");

            /*if (currentobj != null &&
             *  currentobj.Meta.Name == typeof(CyPhy.ComponentAssembly).Name)
             * {
             *  CyPhy.ComponentAssembly ca = CyPhyClasses.ComponentAssembly.Cast(currentobj);
             *  string fileName = null;
             *  DialogResult dr;
             *  using (OpenFileDialog ofd = new OpenFileDialog())
             *  {
             *      ofd.CheckFileExists = true;
             *      ofd.Multiselect = false;
             *      ofd.Filter = "SVG files (*.svg)|*.svg*|All files (*.*)|*.*";
             *      ofd.AutoUpgradeEnabled = true;
             *      dr = ofd.ShowDialog();
             *      if (dr == DialogResult.OK)
             *      {
             *          fileName = ofd.FileName;
             *      }
             *  }
             *  if (fileName == null)
             *  {
             *      this.Logger.WriteError("No file was selected.  Add Custom Icon will not complete.");
             *      return;
             *  }
             *
             *  string IconFileDestPath = META.ComponentLibraryManager.EnsureComponentAssemblyFolder(ca);
             *  IconFileDestPath = ca.GetDirectoryPath(META.ComponentLibraryManager.PathConvention.ABSOLUTE);
             *
             *  System.IO.File.Copy(fileName, System.IO.Path.Combine(IconFileDestPath, "icon.svg"), true);
             *  this.Logger.WriteInfo("Successfully added icon.svg to " + currentobj.Name);
             *  return;
             * }*/
            // verify we are running in a component and that it is not an instance or library
            string return_msg;

            if (!CheckPreConditions(currentobj, out return_msg))
            {
                this.Logger.WriteFailed(return_msg);
                return;
            }

            // assuming a component is open
            // stash off the project, currentobj and CurrentComponent parameters for use in the event handlers
            StashProject    = project;
            StashCurrentObj = currentobj;

            if (currentobj.Meta.Name == typeof(CyPhy.Component).Name)
            {
                StashCurrentComponent = CyPhyClasses.Component.Cast(currentobj);
            }
            else if (currentobj.Meta.Name == typeof(CyPhy.ComponentAssembly).Name)
            {
                StashCurrentComponent = CyPhyClasses.ComponentAssembly.Cast(currentobj);
            }
            else
            {
                throw new ArgumentException("Invalid design element passed to authoring tool");
            }


            SupportedDesignEntityType designElementType;

            if (StashCurrentComponent is CyPhy.Component)
            {
                designElementType = SupportedDesignEntityType.Component;
            }
            else if (StashCurrentComponent is CyPhy.ComponentAssembly)
            {
                designElementType = SupportedDesignEntityType.ComponentAssembly;
            }
            else
            {
                throw new ArgumentException("Invalid design element passed to authoring tool");
            }

            // use reflection to populate the dialog box objects
            PopulateDialogBox(designElementType);

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // create a checker instance
            var ch            = new Framework.Checker(currentobj, project, null);
            var checkerWindow = new RuleView(ch);

            checkerWindow.ShowDialog();
        }
Example #56
0
 public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
 {
     throw new NotImplementedException("Function Main(MgaProject, MgaFCO, MgaFCOs, ComponentStartMode) not implemented.");
 }
Example #57
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string OutputBaseDir = (string)componentParameters["output_dir"];

            SotConfig sotConfig = new SotConfig();

            sotConfig.MultiJobRun             = true;
            sotConfig.OriginalProjectFileName = project.ProjectConnStr.Substring("MGA=".Length);
            sotConfig.ProjectFileName         = Path.Combine(OutputBaseDir, Path.GetFileName(sotConfig.OriginalProjectFileName));
            // can't be in a tx and save the project
            project.AbortTransaction();
            project.Save("MGA=" + sotConfig.ProjectFileName, true);
            project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED);
            MgaGateway.PerformInTransaction(delegate
            {
                sotConfig.SoTID = currentobj.ID;
            }, transactiontype_enum.TRANSACTION_READ_ONLY);
            using (StreamWriter writer = new StreamWriter(Path.Combine(OutputBaseDir, "manifest.sot.json")))
            {
                writer.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(sotConfig, Newtonsoft.Json.Formatting.Indented));
            }

            string configsDir = Path.Combine(Path.GetDirectoryName((string)componentParameters["original_project_file"]), "config");

            if (Directory.Exists(configsDir))
            {
                var    configs      = Directory.EnumerateFiles(configsDir, "*xml").ToList();
                string sotConfigDir = Path.Combine(OutputBaseDir, "config");
                Directory.CreateDirectory(sotConfigDir);
                foreach (var config in configs)
                {
                    File.Copy(config, Path.Combine(sotConfigDir, Path.GetFileName(config)));
                }
            }

            //componentParameters["labels"] = "";
            //componentParameters["runCommand"] = ;
            //componentParameters["results_zip_py"] as string;
            // result.LogFileDirectory = Path.Combine(MainParameters.ProjectDirectory, "log");
            // componentParameters["build_query"] as string;
        }