public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); MgaGateway.PerformInTransaction(delegate { Main(project, currentobj, selectedobjs, Convert(param)); }, abort: true); } finally { if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public static void ImportXME(string xmePath, string mgaPath, bool enableAutoAddons=false) { MgaParser parser = new MgaParser(); string paradigm; string paradigmVersion; object paradigmGuid; string basename; string version; parser.GetXMLInfo(xmePath, out paradigm, out paradigmVersion, out paradigmGuid, out basename, out version); parser = new MgaParser(); MgaProject project = new MgaProject(); MgaResolver resolver = new MgaResolver(); resolver.IsInteractive = false; dynamic dynParser = parser; dynParser.Resolver = resolver; project.Create("MGA=" + Path.GetFullPath(mgaPath), paradigm); if (enableAutoAddons) { project.EnableAutoAddOns(true); } try { parser.ParseProject(project, xmePath); project.Save(); } finally { project.Close(); } }
public static bool RunElaborator(string projectPath, string absPath) { bool result = false; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(projectPath); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; if (testObj == null) { throw new ApplicationException(absPath + " not found in " + project.ProjectConnStr); } project.AbortTransaction(); MgaFCOs fcos = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter(); result = elaborator.RunInTransaction(project, testObj, fcos, 128); } finally { project.Close(true); } return result; }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { if (Logger == null) { Logger = new GMELogger(project, this.ComponentName); } }
/* Copied/Adapted from CyPhyCompomponentExporterCL Proj */ public static MgaProject GetProject(String mgaFilename) { MgaProject result = null; if (mgaFilename != null && mgaFilename != "") { if (Path.GetExtension(mgaFilename) == ".mga") { result = new MgaProject(); if (System.IO.File.Exists(mgaFilename)) { Console.Out.Write("Opening {0} ... ", mgaFilename); bool ro_mode = true; result.Open("MGA=" + Path.GetFullPath(mgaFilename), out ro_mode); Console.Out.WriteLine("Done."); } else { Console.Error.WriteLine("{0} file must be an existing mga project.", mgaFilename); } } else { Console.Error.WriteLine("{0} file must be an mga project.", mgaFilename); } } else { Console.Error.WriteLine("Please specify an Mga project."); } return result; }
public myMigrator(MgaProject p) { project = p; GMEConsole = GMEConsole.CreateFromProject(p); oldToNewRole = new Dictionary<string, string>() { { "StructuralInterface" , "Connector" }, {"AxisGeometry", "Axis"}, {"SurfaceGeometry", "Surface"}, {"PointGeometry", "Point"}, {"CoordinateSystemGeometry", "CoordinateSystem"}, {"StructuralInterfaceForwarder", "Connector"}, {"FeatureMap", "PortComposition"}, {"AnalysisPointMap", "PortComposition"}, {"AnalysisPoint", "Point"}, {"JoinStructures", "ConnectorComposition"}, //{"FeatureMap", "SurfaceReverseMap"}, //special, not general case //{"CADModel", ""}, //special, addition not replacement }; oldToNewFCO = new Dictionary<MgaFCO, MgaFCO>(); oldConnsAndRefs = new List<MgaFCO>(); oldSubsAndInstances = new List<MgaFCO>(); migratedModels = new List<MgaModel>(); foreach (MgaFolder child in project.RootFolder.ChildFolders) if (child.MetaFolder.Name == "Components") { List<MgaFolder> folders = getAllFolders(child); foreach (MgaFolder folder in folders) foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>()) createNewFCOs(model); } }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { if (Logger == null) Logger = new CyPhyGUIs.GMELogger(project, ComponentName); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); }
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) { 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); }
public static bool RunContextCheck(string projectPath, string absPath) { bool result = false; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(projectPath); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { CyPhyMasterInterpreter.Rules.ContextCheckerResult[] contextCheckerResults = null; // check context result = masterInterpreter.TryCheckContext(testObj as MgaModel, out contextCheckerResults); } } finally { project.Close(true); } return result; }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for /// which the interpreter was called.</param> public void Initialize(MgaProject project) { if (project == null) { throw new ArgumentNullException("project"); } }
public static bool GetConfigurations(string projectPath, string absPath) { bool result = false; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(projectPath); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { IMgaFCOs configurations = null; Assert.ThrowsDelegate d = () => { configurations = masterInterpreter.GetConfigurations(testObj as MgaModel); }; Assert.DoesNotThrow(d); } } finally { project.Close(true); } return result; }
public void Initialize(MgaProject project) { try { Configuration = MetaLinkConfiguration.Create(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "metalink.config")); } catch (Exception e) { GMEConsole.Warning.WriteLine("Unable to read Meta-Link configuration: " + e.Message); Configuration = new MetaLinkConfiguration(); } // Creating addon project.CreateAddOn(this, out addon); // Setting event mask (see ComponentConfig.eventMask) unchecked { addon.EventMask = (uint)ComponentConfig_Addon.eventMask; } // DISABLE BY DEFAULT Enable(false); // Create the proxy windows control which sends-receives messages this.SyncControl = new System.Windows.Forms.Control(); IntPtr handle = SyncControl.Handle; // If the handle has not yet been created, referencing this property will force the handle to be created. }
public static void RunFormulaEvaluate(string projectPath, string absPath, bool automation) { Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(projectPath); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); MgaFCOs fcos = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); Type tFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator"); var formulaEval = Activator.CreateInstance(tFormulaEval) as GME.MGA.IMgaComponentEx; formulaEval.ComponentParameter["automation"] = automation ? "true" : "false"; formulaEval.ComponentParameter["console_messages"] = "on"; formulaEval.ComponentParameter["expanded"] = "true"; //formulaEval.Initialize(project); formulaEval.InvokeEx(project, testObj, fcos, 16); } finally { project.Close(true); } }
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(); }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // TODO: Add your initialization code here... Contract.Requires(project != null); GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a transaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // TODO: Add your initialization code here... GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); }
/// <summary> /// Calls CyPhy2Modelica using early bindings /// </summary> /// <param name="outputdirname">xme folder from trunk/models/DynamicsTeam</param> /// <param name="projectPath">name of mga-file</param> /// <param name="absPath">Folder-path to test-bench</param> /// <returns>Boolean - True -> interpreter call was successful</returns> public static bool Run(string outputdirname, string projectPath, string absPath) { bool result = false; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + projectPath; //Type CyPhy2Modelica_v2Interpreter = Type.GetTypeFromProgID("MGA.Interpreter.CyPhy2Modelica_v2"); //Type MainParametersType = Type.GetTypeFromProgID("ISIS.CyPhyML.InterpreterConfiguration"); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); string OutputDir = Path.Combine(Path.GetDirectoryName(projectPath), outputdirname); if (Directory.Exists(OutputDir)) { Test.DeleteDirectory(OutputDir); } Directory.CreateDirectory(OutputDir); //dynamic interpreter = Activator.CreateInstance(CyPhy2Modelica_v2Interpreter); var interpreter = new CyPhy2Modelica_v2.CyPhy2Modelica_v2Interpreter(); interpreter.Initialize(project); //dynamic mainParameters = Activator.CreateInstance(MainParametersType); var mainParameters = new CyPhyGUIs.InterpreterMainParameters(); mainParameters.Project = project; mainParameters.CurrentFCO = testObj; mainParameters.SelectedFCOs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); mainParameters.StartModeParam = 128; mainParameters.ConsoleMessages = false; mainParameters.ProjectDirectory = Path.GetDirectoryName(projectPath); mainParameters.OutputDirectory = OutputDir; //dynamic results = interpreter.Main(mainParameters); var results = interpreter.MainThrows(mainParameters); Assert.True(File.Exists(ProjectConnStr.Substring("MGA=".Length))); result = results.Success; if (result == false) { Test.DeleteDirectory(OutputDir); } } finally { project.Close(true); } return result; }
public static string GetProjectDir(MgaProject project) { string workingDir = Path.GetTempPath(); if (project.ProjectConnStr.StartsWith("MGA=")) { workingDir = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)); } return workingDir; }
public ExporterFixture() { String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(pathXME, out mgaConnectionString); proj = new MgaProject(); bool ro_mode; proj.Open(mgaConnectionString, out ro_mode); proj.EnableAutoAddOns(true); }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a transaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // initialize collections if (this.componentParameters == null) { // this is not a constructor, if somebody writes the parameters before calling the initialize // then we do not want to overwrite their saved results. Therefore initialize the collection only // if it is not initialized already. this.componentParameters = new SortedDictionary<string, object>(); } }
public GMEProjectFixtureBase() { String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(xmePath, out mgaConnectionString); var mgaPath = mgaConnectionString.Substring("MGA=".Length); Assert.True(File.Exists(Path.GetFullPath(mgaPath)), String.Format("{0} not found. Model import may have failed.", mgaPath)); proj = new MgaProject(); bool ro_mode; proj.Open("MGA=" + Path.GetFullPath(mgaPath), out ro_mode); proj.EnableAutoAddOns(true); }
public static void Main(string[] args) { try { // parse command line arguments string projectConnStr = args[0]; string originalSubjectID = args[1]; string[] configIDs = args.Skip(2).ToArray(); if (projectConnStr.StartsWith("MGA=") == false) { // use the full absolute path projectConnStr = "MGA=" + Path.GetFullPath(projectConnStr); } MgaProject project = new MgaProject(); bool ro_mode; project.Open(projectConnStr, out ro_mode); try { // get an instance of the master interpreter using (var master = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { // create a configuration for the run var configLight = new CyPhyMasterInterpreter.ConfigurationSelectionLight(); configLight.ContextId = originalSubjectID; configLight.SelectedConfigurationIds = configIDs; configLight.KeepTemporaryModels = false; configLight.PostToJobManager = true; // run master interpreter on configuration var results = master.RunInTransactionWithConfigLight(configLight); // summarize results master.WriteSummary(results); } } finally { project.Close(true); } } catch (Exception e) { System.Console.Error.WriteLine(e.ToString()); System.Environment.Exit(5); } }
public void InvokeEx2(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { string projectPath = Path.GetDirectoryName(project.ProjectConnStr.Substring(4)); // skip mga= string projectName = Path.GetFileNameWithoutExtension(project.ProjectConnStr.Substring(4)); string cyphyFilename = project.ProjectConnStr.Substring(4); baseOutputDir = Path.Combine(projectPath, projectName + "_PRISMATIC"); GME.CSharp.GMEConsole console = GME.CSharp.GMEConsole.CreateFromProject(project); console.Out.WriteLine("Output directory is " + baseOutputDir); META_PATH = GetMetaPathValue(); if (!Directory.Exists(META_PATH)) { throw new ApplicationException("META_PATH='" + META_PATH + "' doesn't exist. Please install the META toolchain and restart GME."); } string metaPath = Path.Combine( META_PATH, "meta" ); if (!Directory.Exists(metaPath)) { throw new ApplicationException(metaPath + " doesn't exist"); } ensureDir(baseOutputDir); string CyPhyML_udm_xml_path = Path.Combine(metaPath, "CyPhyML_udm.xml"); if (!File.Exists(CyPhyML_udm_xml_path)) { CyPhyML_udm_xml_path = Path.Combine(metaPath, @"..\generated\CyPhyML\models\CyPhyML_udm.xml"); } string CyPhyML_xsd_path = Path.Combine(metaPath, "CyPhyML.xsd"); if (!File.Exists(CyPhyML_xsd_path)) { CyPhyML_xsd_path = Path.Combine(metaPath, @"..\generated\CyPhyML.xsd"); } console.Out.WriteLine("Extracting XML model..."); runProgram( Path.Combine(metaPath, @"..\bin\UdmCopy.exe"), new string[] { "-f", cyphyFilename, Path.Combine( baseOutputDir, projectName + ".xml" ), CyPhyML_udm_xml_path, CyPhyML_xsd_path } ); console.Out.WriteLine("Generating Prismatic files..."); runProgram( "C:\\Python26\\python.exe", new string[] { META_PATH + "\\bin\\Prismatic\\" + "cmc.py", Path.Combine( baseOutputDir, projectName + ".xml" ), baseOutputDir } ); console.Out.WriteLine("Running Prismatic..."); runProgram( "C:\\Python27\\python.exe", new string[] { baseOutputDir + "\\prismatic.py" }); console.Out.WriteLine("Prismatic work done."); }
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 convertFluidParameters(MgaProject project) { MgaFilter modelicaFluidPortFilter = project.CreateFilter(); modelicaFluidPortFilter.ObjType = "OBJTYPE_MODEL"; modelicaFluidPortFilter.Kind = "ModelicaConnector"; var modelicaFluidPortArchetypes = project .AllFCOs(modelicaFluidPortFilter) .Cast<MgaModel>() .Where(x => x.ChildFCOs.OfType<MgaAtom>().ToList().Count() != 0 && x.ParentModel != null && x.ArcheType == null); //.ToList() //GMEConsole.Info.WriteLine("Number of FluidPort Archetypes: {0}", modelicaFluidPortArchetypes.Count()); foreach (var port in modelicaFluidPortArchetypes) { //GMEConsole.Out.WriteLine("{0}", port.StrAttrByName["Class"]); try { MgaAtom packageParameter = port.ChildFCOs.OfType<MgaAtom>() .Where(x => x.Name == "redeclare package Medium").FirstOrDefault(); if (packageParameter != null) { MgaFCO modelicaRedeclare = makeFCO(port, "ModelicaRedeclare"); modelicaRedeclare.Name = "Medium"; modelicaRedeclare.StrAttrByName["ModelicaRedeclareType"] = "Package"; modelicaRedeclare.StrAttrByName["Value"] = packageParameter.StrAttrByName["Value"]; } } catch (Exception ex) { GMEConsole.Warning.WriteLine( "Could not make ModelicaRedeclare block within {0}.{1}", port.ParentModel.Name, port.Name); GMEConsole.Error.WriteLine("{0}", ex.Message); GMEConsole.Info.WriteLine("{0}", ex.StackTrace); } } }
public static bool Run(string outputdirname, MgaProject project, MgaFCO testObj, bool copycomponents) { bool status = true; try { if (copycomponents) { CopyDirectory(Path.Combine(GetProjectDir(project),"components"), Path.Combine(outputdirname, "components")); } var interpreter = new CyPhy2CAD_CSharp.CyPhy2CAD_CSharpInterpreter(); interpreter.Initialize(project); var mainParameters = new CyPhyGUIs.InterpreterMainParameters(); var cadSettings = new CyPhy2CAD_CSharp.CyPhy2CADSettings(); cadSettings.OutputDirectory = outputdirname; cadSettings.AuxiliaryDirectory = ""; mainParameters.config = cadSettings; mainParameters.Project = project; mainParameters.CurrentFCO = testObj; mainParameters.SelectedFCOs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); mainParameters.StartModeParam = 128; mainParameters.ConsoleMessages = false; mainParameters.ProjectDirectory = Path.GetDirectoryName(GetProjectDir(project)); mainParameters.OutputDirectory = outputdirname; interpreter.Main(mainParameters); } catch (Exception) { status = false; } finally { project.Close(); } return status; }
public static void CheckParadigmVersionUpgrade(MgaProject project) { GME.Util.MgaRegistrar registar = new GME.Util.MgaRegistrar(); string MetaConnStr; object MetaGuid = null; object ProjectMetaGuid; project.BeginTransactionInNewTerr(); try { registar.QueryParadigm(project.MetaName, out MetaConnStr, ref MetaGuid, GME.Util.regaccessmode_enum.REGACCESS_BOTH); ProjectMetaGuid = project.MetaGUID; } finally { project.AbortTransaction(); } if (((Array)ProjectMetaGuid).Cast<byte>().SequenceEqual(((Array)MetaGuid).Cast<byte>()) == false) { Xunit.Assert.True(false, string.Format("Please upgrade {0} to the latest registered {1} paradigm", project.ProjectConnStr, project.MetaName)); } }
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; }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { this.ManufacturingManifestData = new DesignManufactureManifest(); this.ComponentManufacturingDataList = new List <ComponentManufacturingData>(); }
public static void PerformInTransaction(this MgaProject project, MgaGateway.voidDelegate del) { var mgaGateway = new MgaGateway(project); mgaGateway.PerformInTransaction(del, abort: false); }
public IMgaFCO ImportFile(MgaProject project, string projroot, string FileName) { // this function can be called from python return(this.ImportFiles(project, projroot, new string[] { FileName }).Cast <IMgaFCO>().FirstOrDefault()); }
public IMgaFCOs ImportFiles(MgaProject project, string projRootPath, string[] FileNames, bool alwaysReplace = false, bool doNotReplaceAll = false) { Boolean b_CLMAddOnStatus = META.ComponentLibraryManagerAddOn.GetEnabled(project); META.ComponentLibraryManagerAddOn.Enable(false, project); var addons = project.AddOnComponents.Cast <IMgaComponentEx>(); foreach (var addon in addons) { if (addon.ComponentName.ToLowerInvariant() == "CyPhyAddOn".ToLowerInvariant()) { addon.ComponentParameter["DontAssignGuidsOnNextTransaction".ToLowerInvariant()] = true; } } Boolean bCreatedLogger = false; if (Logger == null) { InitializeLogger(project); bCreatedLogger = true; } IMgaFCOs importedComponents = (IMgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); try { bool replaceAll = alwaysReplace; CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject); Dictionary <string, CyPhy.Component> avmidComponentMap = getCyPhyMLComponentDictionary_ByAVMID(rootFolder); Dictionary <string, CyPhy.Component> nameComponentMap = getCyPhyMLComponentDictionary_ByName(rootFolder); Boolean b_FirstComponent = true; foreach (String inputFile in FileNames) { var inputFilePath = inputFile; /* Disable validation for now #region Check validation rules * * var errorMessages = new List<string>(); * ComponentImportRules.CheckUniqueNames(inputXMLFile, ref errorMessages); * var isValid = ComponentImportRules.ValidateXsd(inputXMLFile, ref errorMessages); * * foreach (var errorMessage in errorMessages) * { * GMEConsole.Error.WriteLine(errorMessage); * } * * if (!isValid) * { * GMEConsole.Info.WriteLine("XML is not valid. Skip file: {0}", inputXMLFile); * continue; * } #endregion */ Logger.WriteDebug("Importing {0}", inputFilePath); // If ZIP file, unzip it to a temporary directory, then import as usual UnzipToTemp unzip = null; bool bZipArchive = (Path.GetExtension(inputFilePath) == ".zip"); if (bZipArchive) { unzip = new UnzipToTemp(Logger); List <string> entries = unzip.UnzipFile(inputFilePath); inputFilePath = entries.Where(entry => Path.GetDirectoryName(entry) == "" && entry.EndsWith(".acm")).FirstOrDefault(); if (inputFilePath != null) { inputFilePath = Path.Combine(unzip.TempDirDestination, inputFilePath); } } using (unzip) { try { if (inputFilePath == null) // may be null if .zip didn't contain .acm { throw new FileNotFoundException("No ACM file not found in root directory of ZIP file."); } avm.Component ac_import = null; /* META-3003: Check for old-style ITAR statement */ bool isDistributionD = false; bool isNotItar = false; #region Check for old-style ITAR statements XmlDocument doc = new XmlDocument(); doc.Load(inputFilePath); XmlNode root = doc.DocumentElement; XmlNodeList nodeList = root.SelectNodes("//*[local-name()='DistributionRestriction' and @Level='ITARDistributionD']"); if (nodeList.Count > 0) { isDistributionD = true; } else { nodeList = root.SelectNodes("//*[local-name()='DistributionRestriction' and @Level='NotITAR']"); if (nodeList.Count > 0) { isNotItar = true; } } #endregion using (StreamReader streamReader = new StreamReader(inputFilePath)) { ac_import = this.DeserializeAvmComponentXml_NonStatic(streamReader); } if (ac_import == null) { throw new Exception("Could not load ACM file."); } /* Throw warning if from an unexpected schema version */ CheckAndWarnOnSchemaVersion(ac_import); /* META-3003: Strip old-style ITAR statement */ #region Strip old-style ITAR statements if (isDistributionD) { // Correct this. if (ac_import.DistributionRestriction == null) { ac_import.DistributionRestriction = new List <avm.DistributionRestriction>(); } ac_import.DistributionRestriction.Add(new avm.DoDDistributionStatement() { Type = DoDDistributionStatementEnum.StatementD }); } else if (isNotItar) { var itar = ac_import.DistributionRestriction.OfType <avm.ITAR>().FirstOrDefault(); if (itar != null) { ac_import.DistributionRestriction.Remove(itar); } } #endregion String acmDir = Path.GetDirectoryName(inputFilePath); #region File Management // Create a new backend folder String compDirAbsPath = META.ComponentLibraryManager.CreateComponentFolder(project); String compDirRelPath = MetaAvmProject.MakeRelativePath(projRootPath, compDirAbsPath); // Copy the ACM file to the new path String newACMRelPath = Path.Combine(compDirRelPath, ac_import.Name + ".acm"); string newACMAbsPath = Path.Combine(compDirAbsPath, ac_import.Name + ".acm"); File.Copy(inputFilePath, newACMAbsPath, true); // Now we have to copy in his resources foreach (var resource in ac_import.ResourceDependency) { try { var dirRelPath = Path.GetDirectoryName(resource.Path); var dirAbsPath = Path.Combine(compDirAbsPath, dirRelPath); var orgAbsPath = Path.Combine(acmDir, resource.Path); var dstAbsPath = Path.Combine(compDirAbsPath, resource.Path); Directory.CreateDirectory(dirAbsPath); File.Copy(orgAbsPath, dstAbsPath, true); } catch (FileNotFoundException) { Logger.WriteWarning("This Component depends on a file which cannot be found in the Component package: {0}", resource.Path); } catch (DirectoryNotFoundException) { Logger.WriteWarning("This Component depends on a file which cannot be found in the Component package: {0}", resource.Path); } catch (PathTooLongException) { var message = String.Format("This Component has a Resource that results in a path that is too long: {0}", resource.Path); Logger.WriteWarning(message); } catch (NotSupportedException) { var message = String.Format("This Component has a Resource that could not be loaded: {0}", resource.Path); Logger.WriteWarning(message); } catch (Exception ex) { var message = String.Format("Exception while copying Resource {0}: {1}", resource.Path, ex); Logger.WriteWarning(message); } } #endregion CyPhy.ComponentAssembly cyPhyMLComponentAssembly = null; CyPhy.Components cyPhyMLComponentsFolder = null; CyPhy.Component cyPhyReplaceComponent = null; #region Search for Components that should be Replaced by this new one bool replaceeFound = false; if (ac_import.ID != null) { replaceeFound = avmidComponentMap.TryGetValue(ac_import.ID, out cyPhyReplaceComponent); } if (replaceeFound == false) { replaceeFound = nameComponentMap.TryGetValue(ac_import.Name, out cyPhyReplaceComponent); } if (replaceeFound) { bool replace = false; if (!doNotReplaceAll && !replaceAll) { // Present dialog to see if user wants to replace component with AVMID avmid // Maybe have a "do all" checkbox (which sets "replaceAll" to "true") if many items are being imported. // If yes, replace = true; String s_ExistingName = cyPhyReplaceComponent.Name; String s_ExistingAVMID = cyPhyReplaceComponent.Attributes.AVMID; String s_ExistingVersion = cyPhyReplaceComponent.Attributes.Version; String s_ExistingRevision = cyPhyReplaceComponent.Attributes.Revision; String s_ExistingDescriptor = cyPhyReplaceComponent.Name; if (s_ExistingAVMID != "") { s_ExistingDescriptor += "\nAVM ID: " + s_ExistingAVMID; } if (s_ExistingVersion != "") { s_ExistingDescriptor += "\nVersion: " + s_ExistingVersion; } if (s_ExistingRevision != "") { s_ExistingDescriptor += "\nRevision: " + s_ExistingRevision; } String s_NewName = ac_import.Name; //String s_NewAVMID = ac_import.AVMID; String s_NewVersion = ac_import.Version; //String s_NewRevision = ac_import.Revision; String s_NewDescriptor = ac_import.Name; //if (s_NewAVMID != "") // s_NewDescriptor += "\nAVM ID: " + s_NewAVMID; if (s_NewVersion != "") { s_NewDescriptor += "\nVersion: " + s_NewVersion; } //if (s_NewRevision != "") // s_NewDescriptor += "\nRevision: " + s_NewRevision; String s_MessageBoxPromptTemplate = "Would you like to replace\n\n{0}\n\nwith\n\n{1}"; String s_MessageBoxPrompt = String.Format(s_MessageBoxPromptTemplate, s_ExistingDescriptor, s_NewDescriptor); using (UpdatePrompt up = new UpdatePrompt()) { up.DialogText.Text = s_MessageBoxPrompt; up.ShowDialog(); if (up.DialogResult == DialogResult.Cancel || up.DialogResult == DialogResult.None) { // Skip this component; Continues the "foreach" loop above. Logger.WriteError("Import canceled for {0}", inputFile); continue; } Dictionary <DialogResult, string> d_TranslateResult = new Dictionary <DialogResult, string>() { { DialogResult.OK, "Replace" }, { DialogResult.Abort, "Import as New" }, }; if (d_TranslateResult[up.DialogResult] == "Replace") { replace = true; if (up.applyToAll.Checked) { replaceAll = true; } } else if (d_TranslateResult[up.DialogResult] == "Import as New") { if (up.applyToAll.Checked) { doNotReplaceAll = true; } } } } if (!replace && !replaceAll || doNotReplaceAll) { cyPhyReplaceComponent = null; } } #endregion if (cyPhyReplaceComponent != null) { Object replaceComponentParent = cyPhyReplaceComponent.ParentContainer; if (replaceComponentParent is CyPhy.ComponentAssembly) { cyPhyMLComponentAssembly = replaceComponentParent as CyPhy.ComponentAssembly; } else { cyPhyMLComponentsFolder = replaceComponentParent as CyPhy.Components; } } else { cyPhyMLComponentsFolder = DetermineAndEnsureFolderForComponent(rootFolder, ac_import); } // The importer uses a map to resolve unit references. // If this is our second run, we shouldn't waste time rebuilding it. Boolean b_ResetUnitMap; if (b_FirstComponent) { b_ResetUnitMap = true; } else { b_ResetUnitMap = false; } CyPhy.Component c = null; if (cyPhyMLComponentAssembly != null) { c = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cyPhyMLComponentAssembly, ac_import, b_ResetUnitMap, Logger); } else { c = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cyPhyMLComponentsFolder, ac_import, b_ResetUnitMap, Logger); } if (c != null) { importedComponents.Append(c.Impl as MgaFCO); c.Attributes.Path = compDirRelPath; } if (cyPhyReplaceComponent != null) { foreach (IMgaReference reference in (cyPhyReplaceComponent.Impl as IMgaFCO).ReferencedBy) { ReferenceSwitcher.Switcher.MoveReferenceWithRefportConnections(c.Impl as IMgaFCO, reference, WriteLine); } cyPhyReplaceComponent.Delete(); } // If icon available, set it in Preferences. // Relative paths here are from our project root. var iconResource = ac_import.ResourceDependency.Where(x => x.Path.Contains("Icon.png")).FirstOrDefault(); //foreach (AVM.File file in ac_import.Files) //{ // if (file.Location.Contains("Icon.png")) // iconRelativePath = componentModelRelativePath + "/" + file.Location; //} if (iconResource != null) { var iconRelativePath = Path.Combine(compDirRelPath, iconResource.Path); // Remove leading "\" if (iconRelativePath.IndexOf("\\") == 0) { iconRelativePath = iconRelativePath.Remove(0, 1); } // Shrink double backslash to single iconRelativePath = iconRelativePath.Replace("\\\\", "\\"); // Replace / with \ iconRelativePath = iconRelativePath.Replace('/', '\\'); // If icon exists, set it if (System.IO.File.Exists(iconRelativePath)) { // Set "icon" regnode (c.Impl as GME.MGA.IMgaFCO).set_RegistryValue("icon", iconRelativePath); } } Logger.WriteInfo("Imported <a href=\"mga:{0}\">{1}</a> to folder <i>{2}</i>", c.ID, c.Name, cyPhyMLComponentsFolder.Path); } catch (Exception ex) { string error = string.Format("{0} while importing {1}: {2}", ex.GetType().Name, inputFile, ex.Message); Logger.WriteError(error); this.Errors.Add(error); Logger.WriteError(ex.StackTrace); } finally { } } b_FirstComponent = false; } } finally { // Reset the "enabled" state of the CLM AddOn META.ComponentLibraryManagerAddOn.Enable(b_CLMAddOnStatus, project); } if (bCreatedLogger) { DisposeLogger(); } return(importedComponents); }
private void InitializeLogger(MgaProject project) { Logger = new GMELogger(project, this.ComponentName); }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // TODO: Add your interpreter code GMEConsole.Out.WriteLine("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 { GMEConsole.Warning.WriteLine("Design Exporter cancelled"); return; } } } #endregion GMEConsole.Info.WriteLine("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)) //CyPhyClasses.TestBenchType.Cast(currentobj) != null) { 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 { ExportToFile(de, OutputDir); } catch (Exception ex) { GMEConsole.Error.WriteLine("{0}: Exception encountered ({1})", de.Name, ex.Message); } GMEConsole.Info.WriteLine("{0}: {1}", de.Name, OutputDir); } foreach (CyPhy.TestBenchType tbt in ltbt_allTB) { System.Windows.Forms.Application.DoEvents(); try { ExportToFile(tbt, OutputDir); } catch (Exception ex) { GMEConsole.Error.WriteLine("{0}: Exception encountered ({1})", tbt.Name, ex.Message); } GMEConsole.Info.WriteLine("{0}: {1}", tbt.Name, OutputDir); } GMEConsole.Info.WriteLine(String.Format("{0} model(s) exported", lde_allCAandDC.Count + ltbt_allTB.Count)); GMEConsole.Info.WriteLine("Design Exporter finished"); }
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); } }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a transaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE; //bool runNewImplementationOnly = true; //runNewImplementationOnly = false; //if (runNewImplementationOnly) //{ // this.NewMasterInterpreterImplementationFull(currentobj); // return; //} List <IMgaFCO> objectsToCheck = new List <IMgaFCO>(); List <IMgaFCO> objectsToGetConfigurations = new List <IMgaFCO>(); MgaGateway.PerformInTransaction(() => { if (currentobj == null) { var allObjects = project .RootFolder .ChildFolders .Cast <MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingContextChecker"))); objectsToGetConfigurations.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingGetConfigurations"))); } else { objectsToCheck.Add(currentobj); //objectsToGetConfigurations.Add(currentobj); } objectsToCheck.Sort((x, y) => { return(x.Meta.Name.CompareTo(y.Meta.Name) != 0 ? x.Meta.Name.CompareTo(y.Meta.Name) : x.AbsPath.CompareTo(y.AbsPath)); }); }); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; StringBuilder sbAssumptions = new StringBuilder(); sbAssumptions.Append("Implemented".PadToCenter(11)); sbAssumptions.Append("Valid".PadToCenter(11)); sbAssumptions.Append("Context".PadToCenter(30)); sbAssumptions.Append("Assumption"); sbAssumptions.AppendLine(); foreach (var subject in objectsToCheck) { var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); IEnumerable <CyPhyMasterInterpreter.Rules.ContextCheckerResult> contextCheckerResults = null; // check context var checkerSuccess = masterInterpreter.TryCheckContext(subject as MgaModel, out contextCheckerResults); List <CyPhyMasterInterpreter.Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList(); // sort results Passed, Failed, then alphabetically based on message. sortedResults.Sort((x, y) => { return(x.Success == y.Success ? x.Message.CompareTo(y.Message) : y.Success.CompareTo(x.Success)); }); // print out nicely in the GME console MgaGateway.PerformInTransaction(() => { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var successExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; sbAssumptions.AppendFormat("{0}{1}{2}{3}", (successExpected == checkerSuccess).ToString().PadToCenter(11), successExpected.ToString().PadToCenter(11), subject.Meta.Name.PadToCenter(30), subject.Name.ToSentenceCase()); sbAssumptions.AppendLine(); if (successExpected == checkerSuccess) { numSuccess++; //GMEConsole.Info.WriteLine("OK"); if (currentobj != null) { foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name); sb.Append(result.Message); tw.WriteLine(sb); } } } else { foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name); sb.Append(result.Message); tw.WriteLine(sb); } numFailures++; GMEConsole.Error.WriteLine("========= FAILED =========="); GMEConsole.Error.WriteLine("= {0}", subject.Name); GMEConsole.Error.WriteLine("= {0}", subject.AbsPath); GMEConsole.Error.WriteLine("==========================="); } }); if (currentobj != null) { CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; MgaGateway.PerformInTransaction(() => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel); }); GMEConsole.Info.WriteLine("AnalysisProcessor type: {0}", analysisModelProcessor.GetType().Name); GMEConsole.Info.WriteLine("Interpreters: {0}", string.Join(", ", analysisModelProcessor.Interpreters)); GMEConsole.Info.WriteLine("InterpretersToConfigure: {0}", string.Join(", ", analysisModelProcessor.InterpretersToConfiguration)); MgaFCO configuration = null; configuration = masterInterpreter.GetConfigurations(subject as MgaModel).Cast <MgaFCO>().FirstOrDefault(); var results = masterInterpreter.RunInTransaction(subject as MgaModel, configuration, keepTempModels: true); MgaGateway.PerformInTransaction(() => { foreach (var result in results) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[<b style=\"color:darkgreen\">Passed</b>]"); tw = GMEConsole.Info; } else { sb.Append("[<b style=\"color:red\">Failed</b>]"); tw = GMEConsole.Error; } sb.AppendFormat(" <i>{0}</i> {1} ", result.Context.Name, result.Configuration.Name); sb.Append(result.Message); tw.WriteLine(sb); } }); } } File.WriteAllText("master_interpreter_assumptions.txt", sbAssumptions.ToString()); foreach (var subject in objectsToGetConfigurations) { var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); // we are not checking the models again, these test models must be valid enough to get configurations from them var configurations = masterInterpreter.GetConfigurations(subject as MgaModel); // print out nicely in the GME console MgaGateway.PerformInTransaction(() => { GMEConsole.Info.WriteLine("{0} has {1} configurations.", subject.Name, configurations.Count); //GMEConsole.Info.WriteLine("- {0}", string.Join(", ", configurations.Cast<MgaFCO>().Select(x => x.Name))); }); //CyPhyMasterInterpreter.MasterInterpreterResult[] masterInterpreterResults = null; //using (var progressDialog = new CyPhyMasterInterpreter.ProgressDialog()) //{ // masterInterpreter.MultipleConfigurationProgress += progressDialog.MultipleConfigurationProgressHandler; // masterInterpreter.SingleConfigurationProgress += progressDialog.SingleConfigurationProgressHandler; // progressDialog.ShowWithDisabledMainWindow(); // masterInterpreterResults = masterInterpreter.RunInTransaction(subject as IMgaModel, configurations); //} } GMEConsole.Info.WriteLine("ContextChecks: {0}", numContexts); GMEConsole.Info.WriteLine("Successful : {0}", numSuccess); GMEConsole.Info.WriteLine("Failures : {0}", numFailures); if (numContexts == numSuccess) { GMEConsole.Info.WriteLine("ALL GREEN :-)"); } else { GMEConsole.Error.WriteLine("You need to work more on the code..."); } GMEConsole.Info.WriteLine( "Duration: {0}.", sw.Elapsed.ToString("c")); } finally { System.Windows.Forms.Application.DoEvents(); if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
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 (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 Dispose() { proj.Close(abort: true); proj = null; }
public static int Main(String[] args) { if (args.Length < 1) { Console.Out.WriteLine("Usage: <program> CyPhyMLFile.mga [-f] [outputDirectory]"); return(1); } MgaProject mgaProject = null; string outputDirectory = "."; bool flat = false; for (int ix = 0; ix < args.Length; ++ix) { if (args[ix] == "-f") { flat = true; } else if (mgaProject == null) { mgaProject = GetProject(args[ix]); } else { outputDirectory = args[ix]; } } if (mgaProject == null) { Console.Out.WriteLine("Usage: <program> CyPhyMLFile.mga [-f] [outputDirectory]"); return(1); } MgaGateway mgaGateway = new MgaGateway(mgaProject); bool bExceptionOccurred = false; mgaGateway.PerformInTransaction(delegate { try { CyPhyML.RootFolder cyPhyMLRootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyMLClasses.RootFolder>(mgaProject.RootFolder); HashSet <CyPhyML.Component> cyPhyMLComponentSet = CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet(cyPhyMLRootFolder); var ruleChecker = new DesignConsistencyChecker.Framework.Checker(null, mgaProject); ruleChecker.RegisterRuleDll("DesignConsistencyChecker.dll"); var uniqueNameRule = ruleChecker.GetRegisteredRules.FirstOrDefault(x => x.Name == "UniquePPMNames"); int i_Counter = 1; foreach (var cyPhyMLComponent in cyPhyMLComponentSet) { try { if (uniqueNameRule != null) { var feedBacks = uniqueNameRule.Check((MgaFCO)cyPhyMLComponent.Impl).ToList(); if (feedBacks.Any(x => x.FeedbackType == FeedbackTypes.Error)) { foreach (var fb in feedBacks.Where(x => x.FeedbackType == FeedbackTypes.Error)) { Console.Error.WriteLine("Rule {0} failed: {1}", uniqueNameRule.Name, fb.Message); } continue; } } //foreach (CyPhyML.Component cyPhyMLComponent in cyPhyMLComponentList) { avm.Component avmComponent = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(cyPhyMLComponent); string componentPath = null; if (flat) { componentPath = outputDirectory; } else { componentPath = cyPhyMLComponent.Path; componentPath = outputDirectory + "/" + componentPath.Substring(componentPath.IndexOf("/")); } Directory.CreateDirectory(componentPath); if (!flat) { Directory.CreateDirectory(componentPath + "/images"); //Directory.CreateDirectory( componentPath + "/CyPhyML" ); Directory.CreateDirectory(componentPath + "/doc"); Directory.CreateDirectory(componentPath + "/CAD"); } String s_outFilePath = String.Format("{0}/{1}.component.acm", componentPath, Safeify(cyPhyMLComponent.Name)); using (FileStream stream = new FileStream(s_outFilePath, FileMode.Create)) { OpenMETA.Interchange.AvmXmlSerializer.Serialize(avmComponent, stream); stream.Close(); } Console.Out.WriteLine(string.Format("({0}/{1}) {2}", i_Counter++, cyPhyMLComponentSet.Count, Safeify(cyPhyMLComponent.Name))); //} } catch (Exception ex) { Console.Error.WriteLine("Exception: {0}", ex.Message.ToString()); Console.Error.WriteLine("Stack: {0}", ex.StackTrace.ToString()); bExceptionOccurred = true; } } } catch (Exception ex) { Console.Error.WriteLine("Exception: {0}", ex.Message.ToString()); Console.Error.WriteLine("Stack: {0}", ex.StackTrace.ToString()); bExceptionOccurred = true; } }, abort: false); mgaProject.Close(); if (bExceptionOccurred) { return(-1); } return(0); }
//[Fact] public void DesignSpaceWithRefs() { var fullTestPath = Path.Combine(_exportModelDirectory, "DesignSpaceWithRefs"); var xmeFilePath = Path.Combine(fullTestPath, "DesignSpaceWithRefs.xme"); var pathExportedDesign = Path.Combine(fullTestPath, "DesignSpace.adm"); // delete design file if it already exists if (File.Exists(pathExportedDesign)) { File.Delete(pathExportedDesign); } String connectionString; GME.MGA.MgaUtils.ImportXMEForTest(xmeFilePath, out connectionString); var proj = new MgaProject(); bool ro_mode; proj.Open(connectionString, out ro_mode); proj.EnableAutoAddOns(true); try { var designExporter = new CyPhyDesignExporter.CyPhyDesignExporterInterpreter(); designExporter.Initialize(proj); var mgaGateway = new MgaGateway(proj); MgaFCO currentFCO = null; mgaGateway.PerformInTransaction(delegate { currentFCO = proj.get_ObjectByPath("/@DesignSpaces|kind=DesignSpace|relpos=0/@DesignSpace|kind=DesignContainer|relpos=0") as MgaFCO; Assert.NotNull(currentFCO); }); var parameters = new CyPhyGUIs.InterpreterMainParameters() { CurrentFCO = currentFCO, Project = proj, OutputDirectory = fullTestPath }; var result = designExporter.Main(parameters); var design = avm.Design.LoadFromFile(pathExportedDesign); /// Add assert statements to check structure var root = design.RootContainer; Assert.NotNull(root); Assert.Equal(1, root.Container1.Count(c => c.Name == "AltContainer")); var AltContainer = root.Container1.First(c => c.Name == "AltContainer"); Assert.Equal(1, AltContainer.ComponentInstance.Count(ci => ci.Name == "CompA_5")); Assert.Equal(1, AltContainer.ComponentInstance.Count(ci => ci.Name == "CompA_6")); Assert.Equal(1, AltContainer.ComponentInstance.Count(ci => ci.Name == "CompA_7")); Assert.Equal(1, root.Container1.Count(c => c.Name == "DesignContainer")); var DesignContainer = root.Container1.First(c => c.Name == "DesignContainer"); Assert.Equal(1, DesignContainer.ComponentInstance.Count(ci => ci.Name == "CompA3")); Assert.Equal(1, DesignContainer.Container1.Count(c => c.Name == "Assembly1")); var Assembly1 = DesignContainer.Container1.First(c => c.Name == "Assembly1"); Assert.Equal(1, Assembly1.ComponentInstance.Count(ci => ci.Name == "CompA1")); Assert.Equal(1, Assembly1.ComponentInstance.Count(ci => ci.Name == "CompA2")); Assert.Equal(1, root.Container1.Count(c => c.Name == "ReusableContainer")); var ReusableContainer = root.Container1.First(c => c.Name == "ReusableContainer"); Assert.Equal(1, ReusableContainer.Container1.Count(c => c.Name == "Assembly4")); var Assembly4 = ReusableContainer.Container1.First(c => c.Name == "Assembly4"); Assert.Equal(1, Assembly4.ComponentInstance.Count(ci => ci.Name == "CompA1")); Assert.Equal(1, Assembly4.ComponentInstance.Count(ci => ci.Name == "CompA2")); Assert.Equal(1, ReusableContainer.ComponentInstance.Count(ci => ci.Name == "CompA4")); Assert.Equal(1, root.ComponentInstance.Count(ci => ci.Name == "CompA")); Assert.Equal(1, root.ComponentInstance.Count(ci => ci.Name == "CompA")); } finally { proj.Close(); } }
protected void RunCyPhyMLSync(System.Action <MgaProject, CyPhyMetaLink.CyPhyMetaLinkAddon, CyPhyMetaLink.CyPhyMetalinkInterpreter> testAction) { try { if (debugMetalinkStartup) { metalink.WaitForExit(); string stderr = metalink.StandardError.ReadToEnd(); string stdout = metalink.StandardOutput.ReadToEnd(); } Exception exception = null; AutoResetEvent workEvent = new AutoResetEvent(false); Thread work = new Thread(new ThreadStart(delegate { try { // Import XME file to create an MGA String xmeFullPath = Path.Combine(TestModelDir, testXMEFilename); String mgaFullPath = TestModelDir + testInputFilename; MgaUtils.ImportXME(xmeFullPath, mgaFullPath); Assert.True(File.Exists(mgaFullPath), "MGA file not found. XME import may have failed."); MgaProject project = new MgaProject(); project.EnableAutoAddOns(true); project.OpenEx("MGA=" + mgaFullPath, "", true); CyPhyMetaLink.CyPhyMetaLinkAddon propagate = null; try { Assert.Contains("MGA.Addon.CyPhyMLPropagate", project.AddOnComponents.Cast <IMgaComponentEx>().Select(x => x.ComponentProgID)); propagate = (CyPhyMetaLink.CyPhyMetaLinkAddon)project.AddOnComponents.Cast <IMgaComponent>().Where(comp => comp is CyPhyMetaLink.CyPhyMetaLinkAddon).FirstOrDefault(); CyPhyMetaLink.CyPhyMetalinkInterpreter interpreter = new CyPhyMetaLink.CyPhyMetalinkInterpreter(); propagate.TestMode = true; propagate.TestMode_NoAutomaticCreoStart = true; propagate.TestMode_CreoJobObject = JobObjectPinvoke.CreateKillOnCloseJob(); interpreter.GMEConsole = GME.CSharp.GMEConsole.CreateFromProject(project); interpreter.MgaGateway = new MgaGateway(project); var task = Task.Run(async() => await interpreter.ConnectToMetaLinkBridge(project, 128)); task.Wait(); propagate.bridgeClient.SocketQueue.EditMessageReceived += msg => addonMessagesQueue.Add(msg); testAction(project, propagate, interpreter); try { Xunit.Assert.True(propagate.TestMode_LastException == null, propagate.TestMode_LastException); } finally { propagate.TestMode_LastException = null; } } finally { if (propagate != null) { JobObjectPinvoke.CloseHandle(propagate.TestMode_CreoJobObject); propagate.TestMode_CreoJobObject = IntPtr.Zero; } project.Save(project.ProjectConnStr + "_posttest.mga", true); project.Close(true); } } catch (Exception e) { exception = new Exception(e.StackTrace, e); KillMetaLink(); } finally { workEvent.Set(); } })); work.SetApartmentState(ApartmentState.STA); work.Start(); ManualResetEvent metalinkEvent = new ManualResetEvent(true); metalinkEvent.SafeWaitHandle = new SafeWaitHandle(metalink.Handle, false); int handle = WaitHandle.WaitAny(new WaitHandle[] { metalinkEvent, workEvent }); if (exception != null) { throw new Exception("Test failed", exception); } if (handle == 0) { work.Abort(); throw new Exception("metalink exited"); } } finally { KillMetaLink(); lock (metalinkLogStream) metalinkLogStream.Dispose(); } }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a transaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { InitializeLogger(project); MgaGateway = new MgaGateway(project); }
static int Main(string[] args) { bool errorInUsage = false; bool mgaIsGiven = true; bool generateTemplate = false; bool formattedOutput = false; string outputDirectory = Path.Combine(Environment.CurrentDirectory, "output"); string statFileName = "sample_stats.json"; string inputFilename = string.Empty; Directory.CreateDirectory(outputDirectory); // verify the input arguments for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("-")) { switch (args[i].Substring(1)) { case "p": case "-prettyPrint": formattedOutput = true; break; case "t": case "-template": generateTemplate = true; break; default: errorInUsage = true; break; } } else { inputFilename = args[i]; if (i < args.Length - 1) { Console.WriteLine("Arguments after filename are ignored."); } break; } } if (File.Exists(inputFilename)) { if (Path.GetExtension(inputFilename).ToLowerInvariant() == ".mga") { mgaIsGiven = true; } else if (Path.GetExtension(inputFilename).ToLowerInvariant() == ".xme") { mgaIsGiven = false; } else { errorInUsage = true; } } else { errorInUsage = true; } if (generateTemplate) { Statistics.Statistics stats = Process(null); SerializeStats(stats, Path.Combine(outputDirectory, statFileName), formattedOutput); return(0); } if (errorInUsage) { Console.WriteLine("Usage: {0} [arguments] inputfilename.[mga|xme]", Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location)); Console.WriteLine(""); Console.WriteLine("Arguments:"); Console.WriteLine(" -p --prettyPrint Indents the output json file."); Console.WriteLine(" -t --template Generates a sample json file with random numbers."); return(1); } // copy the file to a temp directory string tempXmeFile = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(inputFilename) + ".xme"); string tempMgaFile = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(inputFilename) + ".mga"); statFileName = Path.GetFileNameWithoutExtension(inputFilename) + "_stat.json"; MgaProject project = new MgaProject(); if (mgaIsGiven) { if (inputFilename != tempMgaFile) { Console.WriteLine("Copying MGA file to temp directory: {0}", tempMgaFile); File.Copy(inputFilename, tempMgaFile, true); } Console.WriteLine("Opening project"); int mgaversion; string paradigmName; string paradigmVersion; object paradigmGUID; bool ro_mode; project.QueryProjectInfo("MGA=" + tempMgaFile, out mgaversion, out paradigmName, out paradigmVersion, out paradigmGUID, out ro_mode); project.OpenEx("MGA=" + tempMgaFile, paradigmName, true); Console.WriteLine("Saving project as xme: {0}", tempXmeFile); // export to xme GME.MGA.Parser.MgaDumper dumper = new GME.MGA.Parser.MgaDumper(); dumper.DumpProject(project, tempXmeFile); } else { if (inputFilename != tempXmeFile) { Console.WriteLine("Copying XME file to temp directory: {0}", tempXmeFile); File.Copy(inputFilename, tempXmeFile, true); } GME.MGA.Parser.MgaParser parser = new GME.MGA.Parser.MgaParser(); string paradigmName; parser.GetXMLParadigm(tempXmeFile, out paradigmName); Console.WriteLine("Creating project"); project.CreateEx("MGA=" + tempMgaFile, paradigmName, null); // import xme file Console.WriteLine("Importing project"); parser.ParseProject(project, tempXmeFile); Console.WriteLine("Saving project as mga: {0}", tempMgaFile); project.Save("MGA=" + tempMgaFile); } if (project == null) { throw new Exception("Project is null."); } // process the project var statistics = Process(project); // read in file stats FileInfo mgaInfo = new FileInfo(tempMgaFile); FileInfo xmeInfo = new FileInfo(tempXmeFile); statistics.MgaSizeInBytes = mgaInfo.Length; statistics.XmeSizeInBytes = xmeInfo.Length; // serialize the object SerializeStats(statistics, Path.Combine(outputDirectory, statFileName), formattedOutput); return(0); }
public IMgaFCO ImportFileAndReplaceComponent(MgaProject project, string projroot, string FileName) { // this function can be called from python return(this.ImportFiles(project, projroot, new string[] { FileName }, alwaysReplace: true).Cast <IMgaFCO>().FirstOrDefault()); }
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; } } } }
public void merge(MgaFCO currentObject, string filename) { _currentMgaProject = currentObject.Project; MgaProject mgaProject = GetProject(filename, currentObject.Project.MetaName); if (mgaProject == null) { return; } try { _projectFilename = filename; MgaGateway mgaGateway = new MgaGateway(mgaProject); mgaGateway.PerformInTransaction(delegate { // "DO" LOOP IS ONLY TO ALLOW "break" TO TERMINATE THIS INTERPRETER do { int origPrefs = _currentMgaProject.Preferences; // Magic word allows us to remove ConnPoints _currentMgaProject.Preferences = origPrefs | (int)GME.MGA.preference_flags.MGAPREF_IGNORECONNCHECKS | (int)GME.MGA.preference_flags.MGAPREF_FREEINSTANCEREFS; try { // GET FCO TO BE MERGED FROM OTHER MGA FILE IMgaFCO otherCurrentObject = mgaProject.get_ObjectByPath(currentObject.AbsPath) as IMgaFCO; if (otherCurrentObject == null) { gmeConsole.Error.WriteLine("Could not perform merge: could not find object of path \"" + currentObject.AbsPath + "\" in file \"" + filename + "\""); _exitStatus |= Errors.PathError; break; } recordConnections(otherCurrentObject); // GET PARENT (IN CURRENT MODEL) OF THE FCO TO BE MERGED INTO THE CURRENT MODEL MgaObject currentParentMGAObject = null; GME.MGA.Meta.objtype_enum currentParentObjTypeEnum; currentObject.GetParent(out currentParentMGAObject, out currentParentObjTypeEnum); // THE ROOT OF THE MERGED FCO IMgaFCO newCurrentObject = null; IMgaFCO otherArchetype = otherCurrentObject.ArcheType; if (otherArchetype != null) { MgaFCO newArchetype = mgaProject.get_ObjectByPath(otherArchetype.AbsPath) as MgaFCO; if (newArchetype == null) { gmeConsole.Error.WriteLine("Could not find object of path \"" + otherArchetype.AbsPath + "\" (archetype of \"" + otherCurrentObject.AbsPath + "\" in file \"" + filename + "\") in current model."); _exitStatus |= Errors.PathError; break; } if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { newCurrentObject = (currentParentMGAObject as MgaFolder).DeriveRootObject(newArchetype, otherCurrentObject.IsInstance); } else if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL) { newCurrentObject = (currentParentMGAObject as MgaModel).DeriveChildObject(newArchetype, otherCurrentObject.MetaRole, otherCurrentObject.IsInstance); } else { gmeConsole.Error.WriteLine("Unable to merge \"" + otherCurrentObject.AbsPath + "\" of file \"" + filename + "\": prospective parent neither a folder nor a model."); _exitStatus |= Errors.GMEError; break; } attributesAndRegistryCopy(newCurrentObject, otherCurrentObject); connectionCopy(); } else { if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { newCurrentObject = (currentParentMGAObject as MgaFolder).CreateRootObject(currentObject.Meta); } else if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL) { newCurrentObject = (currentParentMGAObject as MgaModel).CreateChildObject(currentObject.MetaRole); } else { gmeConsole.Error.WriteLine("Unable to merge \"" + otherCurrentObject.AbsPath + "\" of file \"" + filename + "\": prospective parent neither a folder nor a model."); _exitStatus |= Errors.GMEError; break; } subTreeCopy(newCurrentObject, otherCurrentObject); instanceCopy(); attributesAndRegistryCopy(newCurrentObject, otherCurrentObject); referenceCopy(); connectionCopy(); //referenceConnectionCopy(); } } finally { _currentMgaProject.Preferences = origPrefs; } } while (false); }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false); currentObject.DestroyObject(); } finally { mgaProject.Close(true); } }
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"; // 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.WriteError("ConnectorUnroller failed. Check log for details."); this.Logger.WriteDebug(ex.ToString()); success = false; } sw.Stop(); this.Logger.WriteDebug("ConnectorUnroller runtime: {0}", sw.Elapsed.ToString("c")); } this.Logger.WriteInfo("CyPhyElaborate 2.0 finished."); PumpMessages(); return(success); }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // TODO: Add your initialization code here... }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName); if (currentobj == null) { this.Logger.WriteError("Invalid context. This interpreter can only be run if open in the correct context (E.g., test bench)."); return; } GMEConsole.Out.WriteLine(DateTime.Now.ToString() + " running CyPhyPrepIFab Interpreter"); //InitLogger(); // [1] CyPhy2CAD // [2] Export DDP, Manufacture XML, Manufacture Manifest // [3] Generate AppendArtifact.py - script to append artifacts to testbench_manifest.json files // [4] Generate DesignModel1BOM.py - script to generate .bom.json from ddp file // [5] Generate main run bat file //CallCAD(project, currentobj, selectedobjs, param); // CyPhy2CAD MgaGateway.PerformInTransaction(delegate { string kindName = string.Empty; if (currentobj != null) { kindName = currentobj.MetaBase.Name; } if (string.IsNullOrEmpty(kindName) == false && kindName != typeof(CyPhyClasses.TestBench).Name) { Logger.WriteFailed("CyPhyPrepIFAB must be called from a TestBench."); return; } ElaborateModel(project, currentobj, selectedobjs, param); // elaborate model CallCAD(project, currentobj, selectedobjs, param); // CyPhy2CAD ManufacturingGeneration(currentobj); // DDP, Manufacture XML, Manufacture Manifest }, transactiontype_enum.TRANSACTION_NON_NESTED); GenerateAppendArtifactScript(); // AppendArtifact.py GenerateBOMGenScript(); // DesignModel1BOM.py GenerateRunBatFile(); // main run bat file GMEConsole.Out.WriteLine("CyPhyPrepIFab Interpreter Finished!"); } catch (Exception) { Logger.WriteError("{0} has finished with critical errors. Please see above.", this.ComponentName); } finally { //Trace.Close(); MgaGateway = null; if (Logger != null) { Logger.Dispose(); } project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public bool RunInTransaction(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, string outputDirectory = null, bool commitTransaction = false) { bool success = false; bool shouldDisposeLogger = false; try { MgaGateway = new MgaGateway(project); // populate a test model /*MgaGateway.PerformInTransaction(delegate * { * currentobj = GenerateTestModel(project, currentobj); * }, transactiontype_enum.TRANSACTION_NON_NESTED);*/ if (this.Logger == null) { this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName); this.Logger.GMEConsoleLoggingLevel = this.Convert(param) == ComponentStartMode.GME_SILENT_MODE ? CyPhyGUIs.SmartLogger.MessageType_enum.Warning : CyPhyGUIs.SmartLogger.MessageType_enum.Info; this.Logger.LoggingLevel = SmartLogger.MessageType_enum.Info; shouldDisposeLogger = true; } HashSet <string> m_addonNames = new HashSet <string>() { "ConstraintManager".ToLowerInvariant(), "CyPhyAddOn".ToLowerInvariant(), "CyPhyDecoratorAddon".ToLowerInvariant(), "CyPhyMdaoAddOn".ToLowerInvariant(), "CyPhySignalBlocksAddOnAddon".ToLowerInvariant(), "ComponentLibraryManagerAddOn".ToLowerInvariant() }; // turn off all addons specified above var addons = project.AddOnComponents.Cast <IMgaComponentEx>(); foreach (var addon in addons) { if (addon.ComponentName.ToLowerInvariant() == "CyPhyAddOn".ToLowerInvariant()) { addon.ComponentParameter["DontAssignGuidsOnNextTransaction".ToLowerInvariant()] = true; } if (m_addonNames.Contains(addon.ComponentName.ToLowerInvariant())) { try { addon.Enable(false); } catch (Exception ex) { // if one fails keep trying the other ones. this.Logger.WriteError("Turing off addon failed: {0} --> {1}", addon.ComponentName, ex.ToString()); } } } try { MgaGateway.PerformInTransaction(delegate { success = this.Main(project, currentobj, selectedobjs, this.Convert(param)); if (String.IsNullOrEmpty(outputDirectory) == false) { UpdateMetricsInTestbenchManifest(currentobj, outputDirectory); } }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: !commitTransaction); // call old elaborator ////this.CallOldElaborator(project, currentobj); } catch (Exception ex) { this.Logger.WriteInfo(ex.ToString()); success = false; } finally { foreach (var addon in addons) { if (m_addonNames.Contains(addon.ComponentName.ToLowerInvariant())) { try { addon.Enable(true); } catch (Exception ex) { // if one fails keep trying the other ones. this.Logger.WriteError("Turing off addon failed: {0} --> {1}", addon.ComponentName, ex.ToString()); } } } } } finally { if (shouldDisposeLogger && this.Logger != null) { this.Logger.Dispose(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return(success); }
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(); } } }
/// <summary> /// Calls CyPhy2Modelica using early bindings /// </summary> /// <param name="outputdirname">xme folder from trunk/models/DynamicsTeam</param> /// <param name="projectPath">name of mga-file</param> /// <param name="absPath">Folder-path to test-bench</param> /// <returns>Boolean - True -> interpreter call was successful</returns> public static bool Run(string outputdirname, string projectPath, string absPath, CyPhy2Modelica_v2.CyPhy2Modelica_v2Settings config = null) { bool result = false; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + projectPath; //Type CyPhy2Modelica_v2Interpreter = Type.GetTypeFromProgID("MGA.Interpreter.CyPhy2Modelica_v2"); //Type MainParametersType = Type.GetTypeFromProgID("ISIS.CyPhyML.InterpreterConfiguration"); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); string OutputDir = Path.Combine(Path.GetDirectoryName(projectPath), outputdirname); if (Directory.Exists(OutputDir)) { Test.DeleteDirectory(OutputDir); } Directory.CreateDirectory(OutputDir); //dynamic interpreter = Activator.CreateInstance(CyPhy2Modelica_v2Interpreter); var interpreter = new CyPhy2Modelica_v2.CyPhy2Modelica_v2Interpreter(); interpreter.Initialize(project); //dynamic mainParameters = Activator.CreateInstance(MainParametersType); var mainParameters = new CyPhyGUIs.InterpreterMainParameters(); mainParameters.Project = project; mainParameters.CurrentFCO = testObj; mainParameters.SelectedFCOs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); mainParameters.StartModeParam = 128; mainParameters.ConsoleMessages = false; mainParameters.ProjectDirectory = Path.GetDirectoryName(projectPath); mainParameters.OutputDirectory = OutputDir; if (config != null) { mainParameters.config = config; } //dynamic results = interpreter.Main(mainParameters); var results = interpreter.MainThrows(mainParameters); Assert.True(File.Exists(ProjectConnStr.Substring("MGA=".Length))); result = results.Success; if (result == false) { Test.DeleteDirectory(OutputDir); } } finally { project.Close(true); } return(result); }
// Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); }
// Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); }
/// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // TODO: Add your initialization code here... GMEConsole = GMEConsole.CreateFromProject(project); }
public T GetGMEObjectFromIdentification <T>(MgaProject project, string identification) where T : IMgaObject { T result = default(T); // is project in transaction already? bool projectWasNotInTransaction = (project.ProjectStatus & 8) == 0; try { if (projectWasNotInTransaction) { // open a transaction if it is not in a transaction already. project.BeginTransactionInNewTerr(); } // regexp for GME ID - case insensitive string idPattern = @"(id-006[0-9a-f]{1}-[0-9a-f]{8})"; // hexadecimal char: [0-9a-f] System.Text.RegularExpressions.Regex regexId = new System.Text.RegularExpressions.Regex(idPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); bool isId = regexId.IsMatch(identification); // regexp for GUID - case insensitive string guidPattern = @"(\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\})"; System.Text.RegularExpressions.Regex regexGuid = new System.Text.RegularExpressions.Regex(guidPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); bool isGuid = regexGuid.IsMatch(identification); if (isId) { // assume it is an id identification = identification.ToLowerInvariant(); result = (T)project.GetObjectByID(identification); } else if (isGuid) { // FIXME: does not work for folders // assume it is a GUID identification = identification.ToLowerInvariant(); // this may take time, no better method on the GME API at this point. foreach (MgaFCO fco in project.AllFCOs(project.CreateFilter())) { if (fco.GetGuidDisp() == identification) { result = (T)fco; break; } } } else if (identification.StartsWith("/")) { // assume it is an AbsPath if (identification.StartsWith("/@") == false) { // inject @ signs for the user // FIXME: what if the name has / for any objects? identification = identification.Replace("/", "/@"); } result = (T)project.ObjectByPath[identification]; } else { throw new FormatException(string.Format("Identification must be a GME ID 'id-006X-YYYYYYYY' or a GUID '{{guid}}' or an AbsPath '/@...' : given value:'{0}'", identification)); } } finally { if (projectWasNotInTransaction) { project.AbortTransaction(); } } return(result); }
public T GetGMEObjectFromIdentification <T>(MgaProject project, Guid guid) where T : IMgaObject { return(this.GetGMEObjectFromIdentification <T>(project, guid.ToString("B"))); }