/* 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 static MgaProject GetProject(String filename) { MgaProject result = null; if (filename != null && filename != "") { if (Path.GetExtension(filename) == ".mga") { result = new MgaProject(); if (System.IO.File.Exists(filename)) { Console.Out.Write("Opening {0} ... ", filename); bool ro_mode; result.Open("MGA=" + Path.GetFullPath(filename), out ro_mode); } else { Console.Out.Write("Creating {0} ... ", filename); result.Create("MGA=" + filename, "CyPhyML"); } Console.Out.WriteLine("Done."); } else { Console.Error.WriteLine("{0} file must be an mga project.", filename); } } else { Console.Error.WriteLine("Please specify an Mga project."); } return(result); }
public static bool Run(string outputdirname, string xmePath, string absPath, bool copycomponents = true) { xmePath = Path.GetFullPath(xmePath); outputdirname = Path.GetFullPath(outputdirname); bool status = true; string ProjectConnStr; CyPhyGUIs.CyPhyDirectory.EnsureEmptyDirectory(outputdirname); MgaUtils.ImportXMEForTest(xmePath, Path.Combine(outputdirname, Path.GetFileNameWithoutExtension(xmePath) + "_CADtest.mga"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); return(Run(Path.GetDirectoryName(xmePath), project, testObj, copycomponents)); } catch (Exception) { status = false; } finally { project.Close(); } return(status); }
public ValueFlowTestFixture() { String connectionString; GME.MGA.MgaUtils.ImportXMEForTest(path_XME, out connectionString); Boolean ro_mode; Project = new MgaProject(); Project.Open(connectionString, out ro_mode); Project.EnableAutoAddOns(true); MgaFilter filter = Project.CreateFilter(); filter.Kind = "Component"; filter.Name = "ValueFlow"; var mgaGateway = new MgaGateway(Project); mgaGateway.PerformInTransaction(delegate { ValueFlow = Project.AllFCOs(filter) .Cast <MgaFCO>() .Select(x => CyPhyC.Component.Cast(x)) .First(); RunFormulaEvaluator(ValueFlow.Impl as MgaFCO); }, transactiontype_enum.TRANSACTION_GENERAL, abort: false); }
public AddOnTestFixture() { var path_XME = Path.Combine(path_Test, "model.xme"); var path_MGA = Path.Combine(path_Test, "model_test.mga"); var path_Manifest = Path.Combine(path_Test, "manifest.project.json"); var path_Manifest_Original = Path.Combine(path_Test, "manifest.project.org"); // Copy to create a new test folder if (Directory.Exists(path_Test)) { Directory.Delete(path_Test, true); } Utils.DirectoryCopy(AddOnTest.path_OriginalFiles, path_Test); File.WriteAllText(Path.Combine(path_Test, "_THIS_DIR_IS_A_COPY"), ""); // Delete any MGA and import from scratch File.Delete(path_MGA); GME.MGA.MgaUtils.ImportXME(path_XME, path_MGA, enableAutoAddons: true); Assert.True(File.Exists(path_MGA)); File.Copy(path_Manifest_Original, path_Manifest, true); proj = new MgaProject(); bool ro_mode; proj.Open("MGA=" + Path.GetFullPath(path_MGA), out ro_mode); }
public InterpreterFixture() { Assert.True(File.Exists(testXme), "Test GME model '" + testXme + "' not found."); Assert.True(File.Exists(testAntenna), "Test antenna model '" + testAntenna + "' not found."); Assert.True(File.Exists(openEmsExecutableName), "Simulator executable '" + openEmsExecutableName + "' not found."); Assert.True(File.Exists(nf2ffExecutable), "Simulator executable '" + nf2ffExecutable + "' not found."); string mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(testXme, 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)); if (Directory.Exists(Path.Combine(testPath, "output"))) { Directory.Delete(Path.Combine(testPath, "output"), true); } project = new MgaProject(); Assert.True(project != null, "MgaProject is null"); bool ro_mode; project.Open(mgaConnectionString, out ro_mode); }
private static MgaProject GetProject(String filename) { MgaProject result = null; if (!string.IsNullOrEmpty(filename)) { if (Path.GetExtension(filename) == ".mga") { result = new MgaProject(); if (File.Exists(filename)) { Console.Out.Write("Opening {0} ... ", filename); var roMode = true; result.Open("MGA=" + filename, out roMode); Console.Out.WriteLine("Done."); } else { Console.Error.WriteLine("{0} file must be an existing mga project.", filename); } } else { Console.Error.WriteLine("{0} file must be an mga project.", filename); } } else { Console.Error.WriteLine("Please specify an Mga project."); } return(result); }
public InterpreterFixtureBaseClass() { String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(path_XME, out mgaConnectionString); path_MGA = mgaConnectionString.Substring("MGA=".Length); Assert.True(File.Exists(Path.GetFullPath(path_MGA)), String.Format("{0} not found. Model import may have failed.", path_MGA)); foreach (string dirname in new string[] { Path.Combine(path_Test, "output"), Path.Combine(path_Test, "results") }) { if (Directory.Exists(dirname)) { foreach (string filename in Directory.GetFiles(dirname, "*", SearchOption.AllDirectories)) { File.Delete(Path.Combine(dirname, filename)); } } } proj = new MgaProject(); bool ro_mode; proj.Open("MGA=" + Path.GetFullPath(path_MGA), out ro_mode); proj.EnableAutoAddOns(true); // Ensure "~/Documents/eagle" exists var pathDocEagle = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "eagle"); Directory.CreateDirectory(pathDocEagle); }
public OrganizeByCategoryFixture() { #region Set up test model and folder if (!Directory.Exists(PathTest)) { Directory.CreateDirectory(PathTest); } if (File.Exists(PathTestXME)) { File.Delete(PathTestXME); } File.Copy(PathOriginalXME, PathTestXME); #endregion String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(PathTestXME, out mgaConnectionString); proj = new MgaProject(); bool ro_mode; proj.Open(mgaConnectionString, out ro_mode); proj.EnableAutoAddOns(true); importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter(); importer.Initialize(proj); }
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); }
public DesignImporterTestFixtureBase() { String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(Path.Combine(PathTest, pathXME), out mgaConnectionString); proj = new MgaProject(); bool ro_mode; proj.Open(mgaConnectionString, out ro_mode); proj.EnableAutoAddOns(true); }
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 ExportZipFixture() { String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(path_XME, out mgaConnectionString); path_MGA = mgaConnectionString.Substring("MGA=".Length); Assert.True(File.Exists(Path.GetFullPath(path_MGA)), String.Format("{0} not found. Model import may have failed.", path_MGA)); proj = new MgaProject(); bool ro_mode; proj.Open(mgaConnectionString, out ro_mode); proj.EnableAutoAddOns(true); }
public FormulaEvaluatorFixture() { String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(FormulaEvaluator.xmePath, out mgaConnectionString); 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 InterpreterFixture() { String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(path_XME, out mgaConnectionString); var path_MGA = mgaConnectionString.Substring("MGA=".Length); Assert.True(File.Exists(Path.GetFullPath(path_MGA)), String.Format("{0} not found. Model import may have failed.", path_MGA)); if (Directory.Exists(Path.Combine(path_Test, "output"))) { Directory.Delete(Path.Combine(path_Test, "output"), true); } proj = new MgaProject(); bool ro_mode; proj.Open(mgaConnectionString, out ro_mode); proj.EnableAutoAddOns(true); }
public DesignPackageFixture() { // Delete files from past runs var adm = Directory.EnumerateFiles(PathTest, "*.adm", SearchOption.AllDirectories); var adp = Directory.EnumerateFiles(PathTest, "*.adp", SearchOption.AllDirectories); foreach (var file in adm.Union(adp)) { File.Delete(file); } String mgaConnectionString; GME.MGA.MgaUtils.ImportXMEForTest(pathXME, out mgaConnectionString); proj = new MgaProject(); bool ro_mode; proj.Open(mgaConnectionString, out ro_mode); proj.EnableAutoAddOns(true); }
public TestFixture() { String mgaConnectionString; // n.b. another test uses Schematic_test.mga, so use a different name GME.MGA.MgaUtils.ImportXMEForTest(path_XME, Path.Combine(Path.GetDirectoryName(path_XME), Path.GetFileNameWithoutExtension(path_XME) + "_CyPhy2CADPCB_test.mga"), out mgaConnectionString); path_MGA = mgaConnectionString.Substring("MGA=".Length); Assert.True(File.Exists(Path.GetFullPath(path_MGA)), String.Format("{0} not found. Model import may have failed.", path_MGA)); if (Directory.Exists(Path.Combine(path_Test, "output"))) { Directory.Delete(Path.Combine(path_Test, "output"), true); } if (Directory.Exists(Path.Combine(path_Test, "results"))) { Directory.Delete(Path.Combine(path_Test, "results"), true); } proj = new MgaProject(); bool ro_mode; proj.Open("MGA=" + Path.GetFullPath(path_MGA), out ro_mode); proj.EnableAutoAddOns(true); // Ensure "~/Documents/eagle" exists var pathDocEagle = Path.Combine(Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%"), "Documents", "eagle"); if (!Directory.Exists(pathDocEagle)) { Directory.CreateDirectory(pathDocEagle); } }
public VFTestFixture() { 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)); // Copy the python scripts referenced in the Python Math Block System.IO.Directory.CreateDirectory("scripts"); File.Copy(Path.Combine("..", "..", "..", "..", "scripts", "optimizeContainer.py"), Path.Combine("scripts", "optimizeContainer.py"), true); //Overwrite = true proj = new MgaProject(); bool ro_mode; proj.Open("MGA=" + Path.GetFullPath(mgaPath), out ro_mode); proj.EnableAutoAddOns(true); }
public void Connectors_Invalid() { string XmePath = Path.GetFullPath(@"..\..\..\..\models\CADTeam\MSD_CAD.xme"); string OutputDir = Path.Combine(Path.GetDirectoryName(XmePath), "Connectors_Invalid"); var generatedAsmPath = Path.Combine(OutputDir, generatedAsmFile); CyPhyGUIs.CyPhyDirectory.EnsureEmptyDirectory(OutputDir); string ProjectConnStr; MgaUtils.ImportXMEForTest(XmePath, Path.Combine(OutputDir, Path.GetFileNameWithoutExtension(XmePath) + "_CADtest.mga"), out ProjectConnStr); CyPhy2CADRun.CopyDirectory(Path.Combine(Path.GetDirectoryName(XmePath), "components"), Path.Combine(Path.Combine(OutputDir, "components"))); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); try { // testbenchpath doesn't work:( var terr = project.BeginTransactionInNewTerr(); var testObj = project.RootFolder.GetObjectByPathDisp("/@Generated_configurations/MyMassSpringDamper/Config1/MyMassSpringDamper_cfg_broken"); project.AbortTransaction(); bool status = CyPhy2CADRun.Run(Path.GetDirectoryName(XmePath), project, (MgaFCO)testObj, false); string logfilename = Path.Combine(OutputDir, "log", CyPhy2CAD_CSharp.Logger.LogFileName); StreamReader r = new StreamReader(logfilename); string logcontent = r.ReadToEnd(); Assert.True(logcontent.Contains("badname")); } finally { project.Close(abort: true); } }
static int Main(string[] args) { try { MgaProject project = new MgaProject(); bool ro_mode; project.Open(args[0], out ro_mode); project.BeginTransactionInNewTerr(); try { RootFolder rf = ISIS.GME.Dsml.BidirConnection.Classes.RootFolder.GetRootFolder(project); var children = rf.Children.ModelCollection.GetEnumerator(); children.MoveNext(); Model model = children.Current; AssertEqual(model.Children.ModelCollection, new string[] { "Child1", "Child2" }); foreach (Model child in model.Children.ModelCollection) { var conns = new string[] { "C1_C2", "C2_C1" }; AssertEqual(child.SrcConnections.ConnectionCollection, conns); AssertEqual(child.DstConnections.ConnectionCollection, conns); AssertEqual(child.AllDstConnections, conns); AssertEqual(child.AllSrcConnections, conns); } } finally { project.AbortTransaction(); project.Close(); } } catch (Exception e) { Console.Error.WriteLine(e.ToString()); return(11); } return(0); }
private static MgaProject GetProject( String filename ) { MgaProject result = null; if( filename != null && filename != "" ) { if( Path.GetExtension( filename ) == ".mga" ) { result = new MgaProject(); if( System.IO.File.Exists( filename ) ) { Console.Out.Write( "Opening {0} ... ", filename ); bool ro_mode; result.Open( "MGA=" + Path.GetFullPath(filename), out ro_mode ); } else { Console.Out.Write( "Creating {0} ... ", filename ); result.Create( "MGA=" + filename, "CyPhyML" ); } Console.Out.WriteLine( "Done." ); } else { Console.Error.WriteLine( "{0} file must be an mga project.", filename ); } } else { Console.Error.WriteLine( "Please specify an Mga project." ); } return result; }
public void Connectors_Invalid() { string XmePath = Path.GetFullPath(@"..\..\..\..\models\CADTeam\MSD_CAD.xme"); string OutputDir = Path.Combine(Path.GetDirectoryName(XmePath), "Connectors_Invalid"); var generatedAsmPath = Path.Combine(OutputDir, generatedAsmFile); if (Directory.Exists(OutputDir)) { Directory.Delete(OutputDir, true); } Directory.CreateDirectory(OutputDir); string ProjectConnStr; MgaUtils.ImportXMEForTest(XmePath, Path.Combine(OutputDir, Path.GetFileNameWithoutExtension(XmePath) + "_CADtest.mga"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); // testbenchpath doesn't work:( var terr = project.BeginTransactionInNewTerr(); var testObj = project.RootFolder.GetObjectByPathDisp("/@Generated_configurations/MyMassSpringDamper/Config1/MyMassSpringDamper_cfg_broken"); project.AbortTransaction(); bool status = CyPhy2CADRun.Run(OutputDir, project, (MgaFCO)testObj, false); string logfilename = Path.Combine(OutputDir, "log", CyPhy2CAD_CSharp.Logger.LogFileName); StreamReader r = new StreamReader(logfilename); string logcontent = r.ReadToEnd(); Assert.True(logcontent.Contains("badname")); }
private void CleanUpTempMgaProject(string outputFile) { var newProject = new MgaProject(); bool ro_mode; // open the copied temporary mga file newProject.Open("MGA=" + outputFile, out ro_mode); IMgaTerritory terr = null; try { // create a new transaction terr = newProject.BeginTransactionInNewTerr(); // get the sot object on which the job manager will operate var sot = newProject.GetObjectByID(sotConfig.SoTID); if (sot != null) { // if the sot object exists in the project GME.MGA.Meta.objtype_enum objtype; MgaObject parent; // get the parent folder of which this SoT belongs to. sot.GetParent(out parent, out objtype); if (objtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { // if it is really a folder cast it var parentSoTFolder = parent as MgaFolder; // get all SoT objects in the folder except the one we operate on // mark them for deletion var sotsToDelete = parentSoTFolder .ChildFCOs .Cast <MgaFCO>() .Where(x => x.ID != sotConfig.SoTID) .ToList(); try { // destroy all SoTs that are not used by this sot run sotsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } // get all not null test bench objects that this sot run uses. var referredTBsInSot = sot .ChildObjects .OfType <MgaReference>() .Where(x => x.Meta.Name == typeof(CyPhy.TestBenchRef).Name && x.Referred != null) .Select(x => x.Referred) .Cast <MgaModel>() .ToList(); foreach (var tb in referredTBsInSot) { GME.MGA.Meta.objtype_enum tbParentObjtype; MgaObject tbParent; // get the parent folder where the referenced test bench located tb.GetParent(out tbParent, out tbParentObjtype); if (tbParentObjtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { var parentTBFolder = tbParent as MgaFolder; // get all test benches that are not used by the sot // WARNING: sometimes COM object comparison can fail this code is not the safest. var tbsToDelete = parentTBFolder .ChildFCOs .OfType <MgaModel>() .Where(x => referredTBsInSot.Contains(x) == false) .ToList(); try { // delete test benches that sot does not use tbsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } } } } } // commit changes if everything is successful newProject.CommitTransaction(); } catch { // abort all changes if exception occured newProject.AbortTransaction(); } finally { if (terr != null) { // destroy the territory we were working in if it is not null terr.Destroy(); } } // close the project AND save all changes newProject.Close(); }
//[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(); } }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List <IMgaFCO> objectsToCheck = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast <MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck = allObjects.Where(x => x.AbsPath.Contains("TestingContextChecker") && x.Name.Contains("ReadOnly") == false).ToList(); 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)); }); } finally { project.AbortTransaction(); } Assert.True(objectsToCheck != null, "There are no object in the project that has to be checked."); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToCheck) { // single test using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { 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)); }); project.BeginTransactionInNewTerr(); try { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var successExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; if (successExpected == checkerSuccess) { numSuccess++; //GMEConsole.Info.WriteLine("OK"); } else { success = false; foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[Passed]"); tw = Console.Out; } else { sb.Append("[Failed]"); tw = Console.Error; } sb.AppendFormat(" {0} - {1} ", result.Subject.Name, result.Subject.AbsPath); sb.Append(result.Message); tw.WriteLine(sb); } numFailures++; Console.Error.WriteLine("========= FAILED =========="); Console.Error.WriteLine("= {0}", subject.Name); Console.Error.WriteLine("= {0}", subject.AbsPath); Console.Error.WriteLine("==========================="); } } finally { project.AbortTransaction(); } } } if (success) { Console.Out.WriteLine("[OK] Checked contexts: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Checked contexts: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one context was failed to check against the expected results."); } finally { project.Close(true); } }
private bool CallCyberInterpreter(CyPhy.CyberModel cyberModel) { bool success = true; string cyberModelPath = string.Empty; // get the path to the cyber model file // first, the right way (using resources) CyPhy.UsesResource uses_conn = null; CyPhy.Resource res = null; CyPhy.Component parent_comp = cyberModel.ParentContainer as CyPhy.Component; if (cyberModel.SrcConnections.UsesResourceCollection != null && cyberModel.SrcConnections.UsesResourceCollection.Count() != 0) { uses_conn = cyberModel.SrcConnections.UsesResourceCollection.First(); res = uses_conn.SrcEnd as CyPhy.Resource; } else if (cyberModel.DstConnections.UsesResourceCollection != null && cyberModel.DstConnections.UsesResourceCollection.Count() != 0) { uses_conn = cyberModel.DstConnections.UsesResourceCollection.First(); res = uses_conn.DstEnd as CyPhy.Resource; } if (res != null) { cyberModelPath = Path.Combine(parent_comp.Attributes.Path, res.Attributes.Path); } else { uses_conn = null; } if (uses_conn == null) { // failing that, do it the wrong way by getting the fileref attribute value // checks if (string.IsNullOrWhiteSpace(cyberModel.Attributes.FileRef)) { this.Logger.WriteError("[Cyber] Model filename attribute is empty: {0}", cyberModel.ToHyperLink()); return false; } if (Path.IsPathRooted(cyberModel.Attributes.FileRef)) { cyberModelPath = cyberModel.Attributes.FileRef; } else { cyberModelPath = Path.Combine(this.mainParameters.ProjectDirectory, cyberModel.Attributes.FileRef); } } string cyberModelMgaPath = string.Empty; string cyberModelXmePath = string.Empty; bool requiresImport = false; cyberModelMgaPath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".mga"; cyberModelXmePath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".xme"; if (Path.GetExtension(cyberModelPath) == ".mga") { if (File.Exists(cyberModelMgaPath) == false) { requiresImport = true; if (File.Exists(cyberModelXmePath) == false) { this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath); return false; } } } else if (Path.GetExtension(cyberModelPath) == ".xme") { requiresImport = true; if (File.Exists(cyberModelXmePath) == false) { this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath); return false; } } else { this.Logger.WriteError("[Cyber] Model filename attribute has unknown extension (valid: [mga|xme]): {0} {1}", cyberModel.ToHyperLink(), Path.GetExtension(cyberModelPath)); return false; } MgaProject cyberProject = new MgaProject(); if (requiresImport) { // FIXME: this will throw an exception if xme-referenced mga exists and it is being used. MgaUtils.ImportXME(cyberModelXmePath, cyberModelMgaPath); } try { bool ro_mode; // FIXME: any race conditions here??? // FIXME: for SoT we need to copy the referenced xme/mgas cyberProject.Open("MGA=" + cyberModelMgaPath, out ro_mode); string cyberComponentPath = ""; if (cyberModel.Attributes.FilePathWithinResource.Contains('.')) { cyberComponentPath = cyberModel.Attributes.FilePathWithinResource.Substring(cyberModel.Attributes.FilePathWithinResource.IndexOf('.')).Replace(".", "/@"); } this.Logger.WriteInfo("[Cyber] {0} --> {1}", cyberModel.Attributes.FilePathWithinResource, cyberComponentPath); var terr = cyberProject.BeginTransactionInNewTerr(); MgaFCO currentObj = cyberProject.ObjectByPath[cyberComponentPath] as MgaFCO; cyberProject.AbortTransaction(); terr.Destroy(); if (currentObj == null) { this.Logger.WriteError("[Cyber] Referenced cyber object was not found in model: {0} {1} {2}", cyberModel.ToHyperLink(), cyberModelPath, cyberModel.Attributes.FilePathWithinResource); return false; } // Cyber model type and interpreter progid map. Each cyber model type has a different interpreter. Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string> interpreterMap = new Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string>() { //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.ESMoL, ""}, //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.SignalFlow, ""}, { CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.Simulink, "MGA.Interpreter.Cyber2SLC_CodeGen" } }; // call appropriate Cyber interpreter Type tCyber = Type.GetTypeFromProgID(interpreterMap[cyberModel.Attributes.ModelType]); if (tCyber == null) { this.Logger.WriteError("[Cyber] Cannot instantiate Cyber interpreter: {0} {1}", cyberModel.ToHyperLink(), interpreterMap[cyberModel.Attributes.ModelType]); } IMgaComponentEx cyberCodeGenerator = Activator.CreateInstance(tCyber) as IMgaComponentEx; cyberCodeGenerator.Initialize(cyberProject); string cyberOutputDir = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage); Directory.CreateDirectory(cyberOutputDir); cyberCodeGenerator.ComponentParameter["output_dir"] = cyberOutputDir; cyberCodeGenerator.ComponentParameter["automation"] = "true"; cyberCodeGenerator.ComponentParameter["console_messages"] = "off"; this.Logger.WriteInfo("Generating code for Cyber [{0}] elements... to directory {1}", cyberModel.Attributes.ModelType, cyberOutputDir); System.Windows.Forms.Application.DoEvents(); MgaFCOs selectedobjs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); cyberCodeGenerator.InvokeEx(cyberProject, currentObj, selectedobjs, 128); this.Logger.WriteInfo("Cyber [{0}] code generation is done.", cyberModel.Attributes.ModelType); System.Windows.Forms.Application.DoEvents(); // Copy files referred by resource objects string cyber_manifest_filename = parent_comp.Name + ".cyber.json"; Dictionary<string, string> comp_resources = new Dictionary<string, string>(); foreach (CyPhy.Resource resource in parent_comp.Children.ResourceCollection) { FileInfo resource_path = new FileInfo(Path.Combine(parent_comp.Attributes.Path, resource.Attributes.Path)); string final_path; if (resource_path.DirectoryName == null || resource_path.DirectoryName == string.Empty) { final_path = "Cyber"; } else { final_path = resource_path.DirectoryName.Split(Path.DirectorySeparatorChar).Last(); } //DirectoryInfo resource_directory = resource_path.Directory; //string res_path = Path.Combine(cyberModel.Path, resource.Attributes.Path); //string[] path_parts = res_path.Split('\\'); //string[] path_only = path_parts.Take(path_parts.Length - 1).ToArray(); string new_path = Path.Combine( cyberOutputDir, final_path ); Logger.WriteInfo("[Cyber] resource_path.DirectoryName == string.Empty, new_path is {0}", new_path); System.IO.Directory.CreateDirectory(new_path); string dest_filename = Path.Combine(new_path, resource_path.Name); Logger.WriteInfo("[Cyber] dest_filename is {0}", dest_filename); // TODO: Little bit hacky hard-coding the wait time //int counter = 0; //while ((IsFileReady(resource_path.FullName) != true)) && (counter < 10)) //{ // System.Threading.Thread.Sleep(2000); // counter++; //} if (IsFileReady(resource_path.FullName) == true) { Logger.WriteInfo("[Cyber] copying file {0} to file {1}", resource_path.FullName, dest_filename); System.IO.File.Copy(resource_path.FullName, dest_filename, true); comp_resources[resource.Attributes.ID] = Path.Combine(final_path, resource_path.Name ); } else { Logger.WriteError("[Cyber] Cannot access file for copying: {0}", dest_filename); } } string json_resources = Newtonsoft.Json.JsonConvert.SerializeObject(comp_resources); System.IO.File.WriteAllText(Path.Combine(cyberOutputDir, cyber_manifest_filename), json_resources); } catch (Exception ex) { this.Logger.WriteError("Cyber exception occured: {0}", ex); success = false; } return success; }
// Generator Entry Point public static string main(string projectPathFull, string targetPath, string namespaceName) { Clear(); Generator.Path = targetPath; IMgaProject project = new MgaProject(); IMgaTerritory territory = null; try { bool ro_mode = true; project.Open("MGA=" + projectPathFull, out ro_mode); territory = project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_READ_ONLY); GME.MGA.IMgaFolder root = project.RootFolder as GME.MGA.IMgaFolder; Generator.ClassName = root.Name; Generator.NamespaceName = namespaceName; foreach (GME.MGA.IMgaFCO fco in root.ChildFCOs) { ProcessParadigmSheet(fco); } foreach (GME.MGA.IMgaFolder fol in root.ChildFolders) { foreach (GME.MGA.IMgaFCO fco in fol.ChildFCOs) { ProcessParadigmSheet(fco); } } RootFolder rootFolder = new RootFolder(); rootFolder.Save(); foreach (DSM.Generators.Object elem in DSM.Generators.Object.ElementsByName.Values) { elem.Save(); } DSM.Generators.Enum.Save(); DSM.Generators.Generator.Save(); if (Errors.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Errors during generation process:"); foreach (string item in Errors) { sb.AppendLine(item); } } return(Generator.ClassName); } catch (Exception e) { MessageBox.Show("Error generationg domain-specific interface: " + e.Message); return(null); } finally { if (territory != null) { territory.Destroy(); project.AbortTransaction(); } project.Close(true); } }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List <IMgaFCO> objectsToCheck = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast <MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck = allObjects.Where(x => x.AbsPath.Contains("ProcessorTypesForContexts")).ToList(); 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)); }); } finally { project.AbortTransaction(); } Assert.True(objectsToCheck != null, "There are no object in the project that has to be checked."); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToCheck) { // single test CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; project.BeginTransactionInNewTerr(); try { Assert.ThrowsDelegate d = () => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel); }; MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var contextSupportExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; if (contextSupportExpected) { Assert.DoesNotThrow(d); Assert.True(analysisModelProcessor != null, string.Format("Analysis model processor was not able to create the model processor for {0} {1}.", subject.Name, subject.Meta.Name)); if (subject.Name.Contains(analysisModelProcessor.GetType().Name)) { numSuccess++; Console.Out.WriteLine("[Passed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name); } else { success = false; numFailures++; Console.Out.WriteLine("[Failed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name); } } else { Assert.Throws <CyPhyMasterInterpreter.AnalysisModelContextNotSupportedException>(d); numSuccess++; Console.Out.WriteLine("[Passed] Context not supported {0} [{1}]", subject.Name, subject.Meta.Name); } } finally { project.AbortTransaction(); } } if (success) { Console.Out.WriteLine("[OK] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one analysis model processor was not instantiated as expected."); } finally { project.Close(true); } }
public static bool Run(string outputdirname, string xmePath, string absPath, bool copycomponents = false, bool deletedir = true) { bool status = true; string ProjectConnStr; if (deletedir && Directory.Exists(outputdirname)) { Directory.Delete(outputdirname, true); } Directory.CreateDirectory(outputdirname); MgaUtils.ImportXMEForTest(xmePath, Path.Combine(outputdirname, Path.GetFileNameWithoutExtension(xmePath) + "_CADtest.mga"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); return Run(outputdirname, project, testObj, copycomponents); } catch(Exception) { status = false; } finally { project.Close(); } return status; }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List<IMgaFCO> objectsToGetConfigurations = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast<MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToGetConfigurations = allObjects.Where(x => x.AbsPath.Contains("TestingGetConfigurations")).ToList(); objectsToGetConfigurations.Sort((x, y) => { return x.Meta.Name.CompareTo(y.Meta.Name) != 0 ? x.Meta.Name.CompareTo(y.Meta.Name) : x.AbsPath.CompareTo(y.AbsPath); }); } finally { project.AbortTransaction(); } Assert.True(objectsToGetConfigurations != null, "There are no object in the project that has to be checked."); int numContexts = objectsToGetConfigurations.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToGetConfigurations) { // single test using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { IMgaFCOs configurations = null; Assert.ThrowsDelegate d = () => { configurations = masterInterpreter.GetConfigurations(subject as MgaModel); }; Assert.DoesNotThrow(d); //Assert.True(configurations != null, "GetConfiguration returned with null."); if (configurations == null) { numFailures++; } else { numSuccess++; } // print out nicely in the GME console project.BeginTransactionInNewTerr(); try { Console.Out.WriteLine("{0} [{1}] has {2} configurations.", subject.Name, subject.Meta.Name, configurations.Count); foreach (IMgaFCO configuration in configurations) { Console.Out.WriteLine(" > {0} - {1}", configuration.Name, configuration.ID); } } finally { project.AbortTransaction(); } } } if (success) { Console.Out.WriteLine("[OK] Got configurations for: {0} test benches. Success: {1}, Failed {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Tried to get configurations for: {0} test benches. Success: {1}, Failed {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one context was failed to check against the expected results."); } finally { project.Close(true); } }
public static void Main(string[] args) { try { bool noJobCollectionDone = false; // parse command line arguments string jobCollectionId = new Guid().ToString("D"); while (true) { if (args[0] == "--job-collection-id") { jobCollectionId = args[1]; args = args.Skip(2).ToArray(); } else if (args[0] == "--no-job-collection-done") { noJobCollectionDone = true; args = args.Skip(1).ToArray(); } else { break; } } if (args[0] == "--send-job-collection-done") { var dispatch = new JobManagerDispatch(jobCollectionId); dispatch.StartJobManager(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); dispatch.Done(); return; } 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)) { master.SetJobCollectionID(jobCollectionId); if (noJobCollectionDone == true) { master.SetSendJobCollectionDone(false); } // 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); System.Environment.Exit(results.Where(r => r.Success == false).Count()); } } finally { project.Close(true); } } catch (Exception e) { System.Console.Error.WriteLine(e.ToString()); System.Environment.Exit(5); } }
private static MgaProject GetProject(String filename) { MgaProject result = null; if (!string.IsNullOrEmpty(filename)) { if (Path.GetExtension(filename) == ".mga") { result = new MgaProject(); if (File.Exists(filename)) { Console.Out.Write("Opening {0} ... ", filename); var roMode = true; result.Open("MGA=" + filename, out roMode); Console.Out.WriteLine("Done."); } else { Console.Error.WriteLine("{0} file must be an existing mga project.", filename); } } else { Console.Error.WriteLine("{0} file must be an mga project.", filename); } } else { Console.Error.WriteLine("Please specify an Mga project."); } return result; }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List<IMgaFCO> objectsToCheck = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast<MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck = allObjects.Where(x => x.AbsPath.Contains("ProcessorTypesForContexts")).ToList(); 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); }); } finally { project.AbortTransaction(); } Assert.True(objectsToCheck != null, "There are no object in the project that has to be checked."); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToCheck) { // single test CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; project.BeginTransactionInNewTerr(); try { Assert.ThrowsDelegate d = () => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel); }; MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var contextSupportExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; if (contextSupportExpected) { Assert.DoesNotThrow(d); Assert.True(analysisModelProcessor != null, string.Format("Analysis model processor was not able to create the model processor for {0} {1}.", subject.Name, subject.Meta.Name)); if (subject.Name.Contains(analysisModelProcessor.GetType().Name)) { numSuccess++; Console.Out.WriteLine("[Passed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name); } else { success = false; numFailures++; Console.Out.WriteLine("[Failed] {0} was created for test bench {1} [{2}]", analysisModelProcessor.GetType().Name, subject.Name, subject.Meta.Name); } } else { Assert.Throws<CyPhyMasterInterpreter.AnalysisModelContextNotSupportedException>(d); numSuccess++; Console.Out.WriteLine("[Passed] Context not supported {0} [{1}]", subject.Name, subject.Meta.Name); } } finally { project.AbortTransaction(); } } if (success) { Console.Out.WriteLine("[OK] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Analysis model processor creation was checked for: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one analysis model processor was not instantiated as expected."); } finally { project.Close(true); } }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List<IMgaFCO> objectsToCheck = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast<MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToCheck = allObjects.Where(x => x.AbsPath.Contains("TestingContextChecker") && x.Name.Contains("ReadOnly") == false).ToList(); 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); }); } finally { project.AbortTransaction(); } Assert.True(objectsToCheck != null, "There are no object in the project that has to be checked."); int numContexts = objectsToCheck.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToCheck) { // single test using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { 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); }); project.BeginTransactionInNewTerr(); try { MgaObject parent = null; GME.MGA.Meta.objtype_enum type; subject.GetParent(out parent, out type); var successExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true; if (successExpected == checkerSuccess) { numSuccess++; //GMEConsole.Info.WriteLine("OK"); } else { success = false; foreach (var result in sortedResults) { TextWriter tw = null; StringBuilder sb = new StringBuilder(); if (result.Success) { sb.Append("[Passed]"); tw = Console.Out; } else { sb.Append("[Failed]"); tw = Console.Error; } sb.AppendFormat(" {0} - {1} ", result.Subject.Name, result.Subject.AbsPath); sb.Append(result.Message); tw.WriteLine(sb); } numFailures++; Console.Error.WriteLine("========= FAILED =========="); Console.Error.WriteLine("= {0}", subject.Name); Console.Error.WriteLine("= {0}", subject.AbsPath); Console.Error.WriteLine("==========================="); } } finally { project.AbortTransaction(); } } } if (success) { Console.Out.WriteLine("[OK] Checked contexts: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Checked contexts: {0}, Success: {1}, Failed: {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one context was failed to check against the expected results."); } finally { project.Close(true); } }
private bool CallCyberInterpreter(CyPhy.CyberModel cyberModel) { bool success = true; string cyberModelPath = string.Empty; // checks if (string.IsNullOrWhiteSpace(cyberModel.Attributes.FileRef)) { this.Logger.WriteError("[Cyber] Model filename attribute is empty: {0}", cyberModel.ToHyperLink()); return false; } if (Path.IsPathRooted(cyberModel.Attributes.FileRef)) { cyberModelPath = cyberModel.Attributes.FileRef; } else { cyberModelPath = Path.Combine(this.mainParameters.ProjectDirectory, cyberModel.Attributes.FileRef); } string cyberModelMgaPath = string.Empty; string cyberModelXmePath = string.Empty; bool requiresImport = false; cyberModelMgaPath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".mga"; cyberModelXmePath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".xme"; if (Path.GetExtension(cyberModelPath) == ".mga") { if (File.Exists(cyberModelMgaPath) == false) { requiresImport = true; if (File.Exists(cyberModelXmePath) == false) { this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath); return false; } } } else if (Path.GetExtension(cyberModelPath) == ".xme") { requiresImport = true; if (File.Exists(cyberModelXmePath) == false) { this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath); return false; } } else { this.Logger.WriteError("[Cyber] Model filename attribute has unknown extension (valid: [mga|xme]): {0} {1}", cyberModel.ToHyperLink(), Path.GetExtension(cyberModelPath)); return false; } MgaProject cyberProject = new MgaProject(); if (requiresImport) { // FIXME: this will throw an exception if xme is referenced mga exists and it is being used. MgaUtils.ImportXME(cyberModelXmePath, cyberModelMgaPath); } try { bool ro_mode; // FIXME: any race conditions here??? // FIXME: for SoT we need to copy the referenced xme/mgas cyberProject.Open("MGA=" + cyberModelMgaPath, out ro_mode); string cyberComponentPath = ""; if (cyberModel.Attributes.FilePathWithinResource.Contains('.')) { cyberComponentPath = cyberModel.Attributes.FilePathWithinResource.Substring(cyberModel.Attributes.FilePathWithinResource.IndexOf('.')).Replace(".", "/@"); } this.Logger.WriteInfo("[Cyber] {0} --> {1}", cyberModel.Attributes.FilePathWithinResource, cyberComponentPath); var terr = cyberProject.BeginTransactionInNewTerr(); MgaFCO currentObj = cyberProject.ObjectByPath[cyberComponentPath] as MgaFCO; cyberProject.AbortTransaction(); terr.Destroy(); if (currentObj == null) { this.Logger.WriteError("[Cyber] Referenced cyber object was not found in model: {0} {1} {2}", cyberModel.ToHyperLink(), cyberModelPath, cyberModel.Attributes.FilePathWithinResource); return false; } // Cyber model type and interpreter progid map. Each cyber model type has a different interpreter. Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string> interpreterMap = new Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string>() { //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.ESMoL, ""}, //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.SignalFlow, ""}, { CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.Simulink, "MGA.Interpreter.Cyber2SLC_CodeGen" } }; // call appropriate Cyber interpreter Type tCyber = Type.GetTypeFromProgID(interpreterMap[cyberModel.Attributes.ModelType]); if (tCyber == null) { this.Logger.WriteError("[Cyber] Cannot instantiate Cyber interpreter: {0} {1}", cyberModel.ToHyperLink(), interpreterMap[cyberModel.Attributes.ModelType]); } IMgaComponentEx cyberCodeGenerator = Activator.CreateInstance(tCyber) as IMgaComponentEx; cyberCodeGenerator.Initialize(cyberProject); var cyberOutputDir = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage); Directory.CreateDirectory(cyberOutputDir); cyberCodeGenerator.ComponentParameter["output_dir"] = cyberOutputDir; cyberCodeGenerator.ComponentParameter["automation"] = "true"; cyberCodeGenerator.ComponentParameter["console_messages"] = "off"; this.Logger.WriteInfo("Generating code for Cyber [{0}] elements...", cyberModel.Attributes.ModelType); System.Windows.Forms.Application.DoEvents(); MgaFCOs selectedobjs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); cyberCodeGenerator.InvokeEx(cyberProject, currentObj, selectedobjs, 128); this.Logger.WriteInfo("Cyber [{0}] code generation is done.", cyberModel.Attributes.ModelType); System.Windows.Forms.Application.DoEvents(); } catch (Exception ex) { this.Logger.WriteError("Cyber exception occured: {0}", ex); success = false; } return success; }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List <IMgaFCO> objectsToGetConfigurations = null; project.BeginTransactionInNewTerr(); try { // discover objects var allObjects = project .RootFolder .ChildFolders .Cast <MgaFolder>() .Where(x => x.Name.StartsWith("0")) .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast <IMgaFCO>()) .Where(x => x.RootFCO == x); // get all objects from folders starts with 0 within the root folder. objectsToGetConfigurations = allObjects.Where(x => x.AbsPath.Contains("TestingGetConfigurations")).ToList(); objectsToGetConfigurations.Sort((x, y) => { return(x.Meta.Name.CompareTo(y.Meta.Name) != 0 ? x.Meta.Name.CompareTo(y.Meta.Name) : x.AbsPath.CompareTo(y.AbsPath)); }); } finally { project.AbortTransaction(); } Assert.True(objectsToGetConfigurations != null, "There are no object in the project that has to be checked."); int numContexts = objectsToGetConfigurations.Count; int numSuccess = 0; int numFailures = 0; bool success = true; foreach (var subject in objectsToGetConfigurations) { // single test using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { IMgaFCOs configurations = null; Assert.ThrowsDelegate d = () => { configurations = masterInterpreter.GetConfigurations(subject as MgaModel); }; Assert.DoesNotThrow(d); //Assert.True(configurations != null, "GetConfiguration returned with null."); if (configurations == null) { numFailures++; } else { numSuccess++; } // print out nicely in the GME console project.BeginTransactionInNewTerr(); try { Console.Out.WriteLine("{0} [{1}] has {2} configurations.", subject.Name, subject.Meta.Name, configurations.Count); foreach (IMgaFCO configuration in configurations) { Console.Out.WriteLine(" > {0} - {1}", configuration.Name, configuration.ID); } } finally { project.AbortTransaction(); } } } if (success) { Console.Out.WriteLine("[OK] Got configurations for: {0} test benches. Success: {1}, Failed {2}", numContexts, numSuccess, numFailures); } else { Console.Error.WriteLine("[FAILED] Tried to get configurations for: {0} test benches. Success: {1}, Failed {2}", numContexts, numSuccess, numFailures); } Assert.True(success, "At least one context was failed to check against the expected results."); } finally { project.Close(true); } }