public void OpenProject(string mgaFile) { if (project != null) { project.Close(true); } project = new MgaProjectClass(); project.OpenEx("MGA=" + mgaFile, "CyPhyML", null); }
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; }
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 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 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 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 InvokeExShouldNotThrowIfCurrentObjNull() { Assert.True(File.Exists(this.mgaFile), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(this.mgaFile); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath["/@TestBenches|kind=Testing|relpos=0/@DesignSpace|kind=Testing|relpos=0/@Dynamics|kind=Testing|relpos=0/@MSD_om_DS|kind=TestBench|relpos=0"] as MgaFCO; project.AbortTransaction(); MgaFCOs fcos = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); IMgaComponentEx interpreter = GetInterpreterByProgID(ProgID); Assert.DoesNotThrow(() => { interpreter.Initialize(project); }); Assert.DoesNotThrow(() => { interpreter.InvokeEx(project, null, fcos, 128); }); } finally { project.Close(true); } }
public void CopyMgaAndRunImporter(string tbName) { //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + tbName + ".mga").Substring("MGA=".Length), true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx(proj.ProjectConnStr + tbName + ".mga", "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO oldTestBench = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + tbName + "|kind=TestBench"); Assert.NotNull(oldTestBench); oldTestBench.DestroyObject(); CyPhyML.TestBenchType testBench; using (StreamReader streamReader = new StreamReader(Path.Combine(AtmPath, tbName + ".atm"))) { avm.TestBench avmTestBench = OpenMETA.Interchange.AvmXmlSerializer.Deserialize <avm.TestBench>(streamReader); testBench = CyPhy2TestBenchInterchange.TestBenchInterchange2CyPhy.Convert(avmTestBench, proj2); } } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } }
public void LibraryAttach() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.EnableAutoAddOns(true); project.OpenEx(mgaReference, "CyPhyML", null); try { Assert.Contains("MGA.Addon.CyPhyDecoratorAddon", project.AddOnComponents.Cast <IMgaComponentEx>().Select(addon => addon.ComponentProgID)); MgaFolder lib; project.BeginTransactionInNewTerr(); try { project.RootFolder.AttachLibrary(project.ProjectConnStr, out lib); } finally { project.CommitTransaction(); } } finally { project.Close(true); } Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); }
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; }
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); }
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); }
// This tests that the interpreters would not fail on null object public void CAD_CurrentObjectNull() { var XmePath = Path.GetFullPath(@"..\..\..\..\models\CADTeam\MSD_CAD.xme"); UnpackXmes(XmePath); var mgaFile = XmePath.Replace(".xme", ".mga"); string ProjectConnStr = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var PrepIFABInt = new CyPhyPrepareIFab.CyPhyPrepareIFabInterpreter(); var CADAnalysisInt = new CyPhyCADAnalysis.CyPhyCADAnalysisInterpreter(); var CyPhy2CAD = new CyPhy2CAD_CSharp.CyPhy2CAD_CSharpInterpreter(); PrepIFABInt.Initialize(project); CADAnalysisInt.Initialize(project); CyPhy2CAD.Initialize(project); Assert.DoesNotThrow(() => PrepIFABInt.InvokeEx(project, null, null, 16)); Assert.DoesNotThrow(() => CyPhy2CAD.InvokeEx(project, null, null, 16)); Assert.DoesNotThrow(() => CADAnalysisInt.InvokeEx(project, null, null, 16)); } finally { project.Close(true); } }
public void ShouldThrowExceptions() { // null context Assert.Throws <ArgumentNullException>(() => { AnalysisModelProcessor.GetAnalysisModelProcessor(null); }); Assert.True(File.Exists(this.mgaFile), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(this.mgaFile); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var componentAssembly = project.RootFolder.GetDescendantFCOs(project.CreateFilter()).OfType <MgaModel>().FirstOrDefault(x => x.MetaBase.Name == "ComponentAssembly"); Assert.True(componentAssembly != null, string.Format("{0} project must contain one component assembly.", Path.GetFullPath(this.mgaFile))); // invalid context Assert.Throws <AnalysisModelContextNotSupportedException>(() => { AnalysisModelProcessor.GetAnalysisModelProcessor(componentAssembly); }); } finally { project.AbortTransaction(); project.Close(true); } }
public void CopyMgaAndRunDesignImporter(string asmName) { //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + asmName + ".mga").Substring("MGA=".Length), true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx(proj.ProjectConnStr + asmName + ".mga", "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO componentAssembly = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + asmName); Assert.NotNull(componentAssembly); componentAssembly.DestroyObject(); var importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj2); avm.Design design; using (StreamReader streamReader = new StreamReader(Path.Combine(AdmPath, asmName + ".adm"))) design = CyPhyDesignImporter.CyPhyDesignImporterInterpreter.DeserializeAvmDesignXml(streamReader); var ret = (ISIS.GME.Dsml.CyPhyML.Interfaces.DesignEntity)importer.ImportDesign(design, "ComponentAssemblies" == FolderName ? CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_CAS : CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS); } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } }
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 List<IMgaFCO> InsertComponents( // IMgaFCO designContainer, // IMgaFCO componentRef, // List<IMgaFCO> components, // List<KeyValuePair<IMgaFCO, string>> messages) /// <summary> /// Calls CLM_LIght without showing any GUI. /// </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 projectPath, string absPathDesignContainer, List <string> absPathComponentsToAdd) { bool result = false; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + projectPath; //Type CLM_light_interpreter = Type.GetTypeFromProgID("MGA.Interpreter.CLM_light"); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { //dynamic interpreter = Activator.CreateInstance(CLM_light_interpreter); var interpreter = new CLM_light.CLM_lightInterpreter(); interpreter.Initialize(project); var terr = project.BeginTransactionInNewTerr(); var designContainer = project.ObjectByPath[absPathDesignContainer] as MgaFCO; List <IMgaFCO> componentsToAdd = new List <IMgaFCO>(); var defaultComponentRef = designContainer.ChildObjects.Cast <MgaFCO>().FirstOrDefault(x => x.Meta.Name == "ComponentRef"); var compRefCountBeforeInsert = designContainer.ChildObjects.Cast <MgaFCO>().Count(x => x.Meta.Name == "ComponentRef"); Assert.False(defaultComponentRef == null, string.Format("Design Container has no Component References: {0}", absPathDesignContainer)); foreach (string path in absPathComponentsToAdd) { var component = project.ObjectByPath[path] as MgaFCO; Assert.False(component == null, string.Format("Component was not found in the project: {0}", path)); componentsToAdd.Add(component); } List <KeyValuePair <IMgaFCO, string> > messages = new List <KeyValuePair <IMgaFCO, string> >(); if (interpreter.CheckForValidContext(designContainer)) { List <IMgaFCO> results = interpreter.InsertComponents(designContainer, defaultComponentRef, componentsToAdd, messages); var compRefCountAfterInsert = designContainer.ChildObjects.Cast <MgaFCO>().Count(x => x.Meta.Name == "ComponentRef"); result = compRefCountBeforeInsert + absPathComponentsToAdd.Count == compRefCountAfterInsert; project.AbortTransaction(); Assert.True(File.Exists(ProjectConnStr.Substring("MGA=".Length))); } } finally { project.Close(true); } return(result); }
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; }
/// <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 RunMain(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.Main(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 void TestAddCustomIconTool() { string TestName = System.Reflection.MethodBase.GetCurrentMethod().Name; string path_Test = Path.Combine(testcreatepath, TestName); string path_Mga = Path.Combine(path_Test, TestName + ".mga"); // delete any previous test results if (Directory.Exists(path_Test)) { Directory.Delete(path_Test, true); } // create a new blank project MgaProject proj = new MgaProject(); proj.Create("MGA=" + path_Mga, "CyPhyML"); // these are the actual steps of the test proj.PerformInTransaction(delegate { // create the environment for the Component authoring class CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components components = CyPhyClasses.Components.Create(rf); CyPhy.Component testcomp = CyPhyClasses.Component.Create(components); // new instance of the class to test CyPhyComponentAuthoring.Modules.CustomIconAdd CATModule = new CyPhyComponentAuthoring.Modules.CustomIconAdd(); //// these class variables need to be set to avoid NULL references CATModule.SetCurrentDesignElement(testcomp); CATModule.CurrentObj = testcomp.Impl as MgaFCO; // call the primary function directly CATModule.AddCustomIcon(testiconpath); // verify results // 1. insure the icon file was copied to the back-end folder correctly string iconAbsolutePath = Path.Combine(testcomp.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE), "Icon.png"); Assert.True(File.Exists(iconAbsolutePath), String.Format("Could not find the source file for the created resource, got {0}", iconAbsolutePath)); // 2. insure the resource path was created correctly var iconResource = testcomp.Children.ResourceCollection.Where(p => p.Name == "Icon.png").First(); Assert.True(iconResource.Attributes.Path == "Icon.png", String.Format("{0} Resource should have had value {1}; instead found {2}", iconResource.Name, "Icon.png", iconResource.Attributes.Path) ); // 3. Verify the registry entry exists string expected_registry_entry = Path.Combine(testcomp.GetDirectoryPath(ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT), "Icon.png"); string registry_entry = (testcomp.Impl as GME.MGA.IMgaFCO).get_RegistryValue("icon"); Assert.True(registry_entry.Equals(expected_registry_entry), String.Format("Registry should have had value {0}; instead found {1}", expected_registry_entry, registry_entry) ); }); proj.Save(); proj.Close(); Directory.Delete(testcreatepath, true); }
/// <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 void ProjectMgaOpen() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.OpenEx(mgaReference, "CyPhyML", null); project.Close(true); Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); }
public void TestAddMfgModelTool() { string TestName = System.Reflection.MethodBase.GetCurrentMethod().Name; string path_Test = Path.Combine(testcreatepath, TestName); string path_Mga = Path.Combine(path_Test, TestName + ".mga"); // delete any previous test results if (Directory.Exists(path_Test)) { Directory.Delete(path_Test, true); } // create a new blank project MgaProject proj = new MgaProject(); proj.Create("MGA=" + path_Mga, "CyPhyML"); // these are the actual steps of the test proj.PerformInTransaction(delegate { // create the environment for the Component authoring class CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components components = CyPhyClasses.Components.Create(rf); CyPhy.Component testcomp = CyPhyClasses.Component.Create(components); // new instance of the class to test CyPhyComponentAuthoring.Modules.MfgModelImport CATModule = new CyPhyComponentAuthoring.Modules.MfgModelImport(); //// these class variables need to be set to avoid NULL references CATModule.SetCurrentDesignElement(testcomp); CATModule.CurrentObj = testcomp.Impl as MgaFCO; // call the primary function directly CATModule.import_manufacturing_model(testmfgmdlpath); // verify results // 1. insure the mfg file was copied to the backend folder correctly // insure the part file was copied to the backend folder correctly var getmfgmdl = testcomp.Children.ManufacturingModelCollection.First(); string returnedpath; getmfgmdl.TryGetResourcePath(out returnedpath, ComponentLibraryManager.PathConvention.ABSOLUTE); string demanglepathpath = returnedpath.Replace("\\", "/"); Assert.True(File.Exists(demanglepathpath), String.Format("Could not find the source file for the created resource, got {0}", demanglepathpath)); // 2. insure the resource path was created correctly var mfgResource = testcomp.Children.ResourceCollection.Where(p => p.Name == "generic_cots_mfg.xml").First(); Assert.True(mfgResource.Attributes.Path == Path.Combine("Manufacturing", "generic_cots_mfg.xml"), String.Format("{0} Resource should have had value {1}; instead found {2}", mfgResource.Name, "generic_cots_mfg.xml", mfgResource.Attributes.Path) ); }); proj.Save(); proj.Close(); }
public void ProjectMgaOpen() { var mgaReference = "MGA=" + this.mgaFile; MgaProject project = new MgaProject(); project.OpenEx(mgaReference, "CyPhyML", null); MgaHelper.CheckParadigmVersionUpgrade(project); project.Close(true); Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); }
public bool Execute() { Exception excep = null; bool success = false; Thread t = new Thread(() => { try { MgaProject project = new MgaProject(); project.OpenEx("MGA=" + InputFile, "MetaGME", null); try { string rootName; project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { rootName = project.RootFolder.Name; } finally { project.AbortTransaction(); } if (Path.GetFileNameWithoutExtension(InputFile) != rootName) { // TODO: warn } IMgaComponentEx metaInterpreter = (IMgaComponentEx)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Interpreter.MetaInterpreter")); metaInterpreter.InvokeEx(project, null, null, (int)component_startmode_enum.GME_SILENT_MODE); success = File.ReadAllText(Path.Combine(Path.GetDirectoryName(InputFile), rootName + ".xmp.log")).Contains("Successfully generated"); } finally { project.Close(); } } catch (Exception e) { excep = e; } } ); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); if (excep != null) { throw new Exception("Error running MetaInterpreter", excep); } return(success); }
public static CyPhyMasterInterpreter.MasterInterpreterResult RunMasterInterpreterAndReturnResults( string projectPath, string absPath, string configPath, bool postToJobManager = false, bool keepTempModels = false, [System.Runtime.CompilerServices.CallerMemberName] string functionName = "") { 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(); MgaFCO testObj; MgaFCO configObj; try { testObj = project.ObjectByPath[absPath] as MgaFCO; configObj = project.ObjectByPath[configPath] as MgaFCO; } finally { project.AbortTransaction(); } using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { masterInterpreter.Logger.GMEConsoleLoggingLevel = CyPhyGUIs.SmartLogger.MessageType_enum.Debug; if (String.IsNullOrWhiteSpace(functionName) == false) { masterInterpreter.ResultsSubdirectoryName = functionName; var resultsDirPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(projectPath)), "results", masterInterpreter.ResultsSubdirectoryName); if (Directory.Exists(resultsDirPath)) { Directory.Delete(resultsDirPath, true); } } var miResults = masterInterpreter.RunInTransactionOnOneConfig(testObj as MgaModel, configObj, postToJobManager, keepTempModels); Assert.True(miResults.Length == 1, "MasterInterpreter.RunInTransactionOnOneConfig should always return one result."); return(miResults[0]); } } finally { project.Close(true); } }
public void CreatedObjectWithDefaultNamesShouldNotHaveSpaces() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.EnableAutoAddOns(true); project.OpenEx(mgaReference, "CyPhyML", null); List <IMgaObject> createdObjects = new List <IMgaObject>(); try { var terr = project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); // turn off CyPhySignalBlocksAddOn var addons = project.AddOnComponents.Cast <IMgaComponentEx>().Where(x => x.ComponentName == "CyPhySignalBlocksAddOnAddon"); foreach (var addon in addons) { try { addon.Enable(false); } catch (Exception ex) { // if one fails keep trying the other ones. } } // Use default names empty suffix createdObjects = this.CreateObjectHierarchy(project, ""); project.CommitTransaction(); project.BeginTransaction(terr, transactiontype_enum.TRANSACTION_NON_NESTED); // check renames foreach (var obj in createdObjects) { // this will fail on the first one // FIXME: should we collect everything and print a detailed message about failures? Assert.False(obj.Name.Contains(' '), string.Format("Name contains space, but it should not contain any spaces. {0} [{1}]", obj.Name, obj.MetaBase.DisplayedName)); } project.AbortTransaction(); } finally { project.Close(false); } Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); }
public void TestCADImportResourceNaming() { string TestName = System.Reflection.MethodBase.GetCurrentMethod().Name; string path_Test = Path.Combine(testcreatepath, TestName); string path_Mga = Path.Combine(path_Test, TestName + ".mga"); // delete any previous test results if (Directory.Exists(path_Test)) { Directory.Delete(path_Test, true); } // create a new blank project MgaProject proj = new MgaProject(); proj.Create("MGA=" + path_Mga, "CyPhyML"); // these are the actual steps of the test proj.PerformInTransaction(delegate { // create the environment for the Component authoring class CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components components = CyPhyClasses.Components.Create(rf); CyPhy.Component testcomp = CyPhyClasses.Component.Create(components); // new instance of the class to test CyPhyComponentAuthoring.Modules.CADModelImport testcam = new CyPhyComponentAuthoring.Modules.CADModelImport(); // these class variables need to be set to avoid NULL references testcam.SetCurrentDesignElement(testcomp); testcam.CurrentObj = testcomp.Impl as MgaFCO; // call the module with a part file to skip the CREO steps testcam.ImportCADModel(testpartpath); // verify results // insure the resource path was created correctly var correct_name = testcomp.Children.ResourceCollection.Where(p => p.Name == "damper.prt").First(); Assert.True(correct_name.Attributes.Path == "CAD\\damper.prt", String.Format("{0} should have had value {1}; instead found {2}", correct_name.Name, "CAD\\damper.prt", correct_name.Attributes.Path) ); // insure the part file was copied to the back-end folder correctly var getcadmdl = testcomp.Children.CADModelCollection.First(); string returnedpath; getcadmdl.TryGetResourcePath(out returnedpath, ComponentLibraryManager.PathConvention.ABSOLUTE); Assert.True(File.Exists(returnedpath + ".36"), String.Format("Could not find the source file for the created resource, got {0}", returnedpath)); }); proj.Save(); proj.Close(); }
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); } }
protected string CopyMgaAndRunDesignImporter(string asmName, Action <ISIS.GME.Dsml.CyPhyML.Interfaces.ComponentAssembly> caTest) { string testrunDir = Path.Combine(Path.GetDirectoryName(proj.ProjectConnStr.Substring("MGA=".Length)), "testrun"); try { Directory.Delete(testrunDir, true); } catch (DirectoryNotFoundException) { } Directory.CreateDirectory(testrunDir); string importMgaPath = Path.Combine(testrunDir, Path.GetFileNameWithoutExtension(proj.ProjectConnStr.Substring("MGA=".Length)) + asmName + ".mga"); //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), importMgaPath, true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx("MGA=" + importMgaPath, "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO componentAssembly = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + asmName); Assert.NotNull(componentAssembly); componentAssembly.DestroyObject(); var importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj2); avm.Design design; var adpPath = Path.Combine(fixture.AdmPath, asmName + ("ComponentAssemblies" == FolderName ? ".adp" : ".adm")); var ret = importer.ImportFile(adpPath, "ComponentAssemblies" == FolderName ? CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_CAS : CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS); if (caTest != null) { caTest((ISIS.GME.Dsml.CyPhyML.Interfaces.ComponentAssembly)ret); } } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } return(importMgaPath); }
public void TestExcelImport() { var excelType = Type.GetTypeFromProgID("Excel.Application"); if (excelType == null) { Console.Out.WriteLine("Skipping " + GetCurrentMethod() + " because Excel is not installed"); return; } MgaProject project = new MgaProject(); project.OpenEx("MGA=" + this.mgaFile, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var excel = (IMgaModel)project.ObjectByPath["/@Testing/@ParametricExploration/@TestExcel/@ExcelWrapper"]; foreach (var fco in excel.ChildFCOs.Cast <IMgaFCO>().ToList()) { fco.DestroyObject(); } var excelDS = ISIS.GME.Dsml.CyPhyML.Classes.ExcelWrapper.Cast(excel); string mgaDir = Path.GetDirectoryName(Path.GetFullPath(excel.Project.ProjectConnStr.Substring("MGA=".Length))); CyPhyPET.CyPhyPETInterpreter.CreateParametersAndMetricsForExcel(excelDS, Path.Combine(mgaDir, excelDS.Attributes.ExcelFilename)); Dictionary <string, ISIS.GME.Dsml.CyPhyML.Interfaces.Parameter> params_ = excelDS.Children.ParameterCollection.ToDictionary(p => p.Name, p => p); Assert.Contains("x", params_.Keys); Assert.Contains("b", params_.Keys); Assert.Contains("s", params_.Keys); Assert.Equal("12", params_["x"].Attributes.Value); Dictionary <string, ISIS.GME.Dsml.CyPhyML.Interfaces.Metric> metrics = excelDS.Children.MetricCollection.ToDictionary(m => m.Name, m => m); Assert.Contains("y", metrics.Keys); Assert.Contains("bout", metrics.Keys); Assert.Contains("sout", metrics.Keys); } finally { project.AbortTransaction(); project.Close(); } }
public static CyPhyMasterInterpreter.MasterInterpreterResult RunMasterInterpreterAndReturnResults( string projectPath, string absPath, string configPath, bool postToJobManager = false, bool keepTempModels = 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(); MgaFCO testObj; MgaFCO configObj; try { testObj = project.ObjectByPath[absPath] as MgaFCO; configObj = project.ObjectByPath[configPath] as MgaFCO; } finally { project.AbortTransaction(); } using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { masterInterpreter.Logger.GMEConsoleLoggingLevel = CyPhyGUIs.SmartLogger.MessageType_enum.Debug; var miResults = masterInterpreter.RunInTransactionOnOneConfig(testObj as MgaModel, configObj, postToJobManager, keepTempModels); Assert.True(miResults.Length == 1, "MasterInterpreter.RunInTransactionOnOneConfig should always return one result."); return(miResults[0]); } } finally { project.Close(true); } }
public void Import(IEnumerable <string> lbrFiles) { project.Create("MGA=" + Path.GetFullPath(Path.Combine(".", "ComponentCreator", "Components")) + ".mga", "CyPhyML"); IMgaComponent signalBlocksAddon = (IMgaComponent)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Addon.CyPhySignalBlocksAddOn")); signalBlocksAddon.Initialize(project); project.Notify(globalevent_enum.GLOBALEVENT_OPEN_PROJECT_FINISHED); System.Windows.Forms.Application.DoEvents(); // let CyPhySignalBlocksAddOn create libs project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { MgaMetaFolder componentsMeta = (MgaMetaFolder)project.RootMeta.RootFolder.DefinedFolderByName["Components", false]; var components = project.RootFolder.CreateFolder(componentsMeta); components.Name = componentsMeta.Name; } finally { project.CommitTransaction(); } foreach (string eagleFilePath in lbrFiles) { //Console.WriteLine(eagleFilePath); //Console.WriteLine(string.Join(" ", CyPhyComponentAuthoring.Modules.EDAModelImport.GetDevicesInEagleModel(eagleFilePath).ToArray())); foreach (string deviceName in CyPhyComponentAuthoring.Modules.EDAModelImport.GetDevicesInEagleModel(eagleFilePath)) { try { CreateNewComponentMga(eagleFilePath, deviceName); Console.WriteLine("Imported {0} {1}", eagleFilePath, deviceName); } catch (Exception e) { MessageBox.Show("Import failed: " + e.ToString()); } } } project.Save("", true); project.Close(true); }
public void CyPhyMultiJobRun_CurrentObjectNull() { Assert.True(File.Exists(mgaFile), "Failed to generate the mga."); string ProjectConnStr = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var interpreter = new CyPhyMultiJobRun.CyPhyMultiJobRunInterpreter(); interpreter.Initialize(project); Assert.DoesNotThrow(() => interpreter.InvokeEx(project, null, null, 16)); } finally { project.Close(true); } }
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 bool Run(string originalProjectDir, MgaProject project, MgaFCO testObj, bool copycomponents) { bool status = true; try { var outputdirname = GetProjectDir(project); if (copycomponents) { CopyDirectory(Path.Combine(originalProjectDir, "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 bool AnalysisModelSupported(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(); CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; project.BeginTransactionInNewTerr(); try { Assert.ThrowsDelegate d = () => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(testObj as MgaModel); }; Assert.DoesNotThrow(d); Assert.True(analysisModelProcessor != null, string.Format("Analysis model processor was not able to create the model processor for {0} {1}.", testObj.Name, testObj.Meta.Name)); } finally { project.AbortTransaction(); } } finally { project.Close(true); } return(result); }
public void DesignPackageImport() { // Clean the test directory var pathTest = Path.Combine(META.VersionInfo.MetaPath, "test", "InterchangeTest", "DesignInterchangeTest", "ImportTestUnits", "Package"); foreach (var path in Directory.EnumerateDirectories(pathTest)) { Directory.Delete(path, true); } foreach (var path in Directory.EnumerateFiles(pathTest, "*.*")) { if (!path.Contains("NestedFolders.adp")) { File.Delete(path); } } // Create a test project var proj = new MgaProject(); proj.Create("MGA=" + Path.Combine(pathTest,"testmodel.mga"), "CyPhyML"); try { String pathCA = null; proj.PerformInTransaction(() => { // Instantiate the importer and import the package var importer = new AVMDesignImporter(GMEConsole.CreateFromProject(proj), proj); var mdlCA = importer.ImportFile(Path.Combine(pathTest, "NestedFolders.adp"), AVMDesignImporter.DesignImportMode.CREATE_CAS); var ca = CyPhyClasses.ComponentAssembly.Cast(mdlCA.Impl); pathCA = ca.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE); }); // Check the design's backend folder for all files except for the ADM. var filesExpected = new List<String> { "testObject.txt", "dir1/testObject.txt", "dir1/dir1a/testObject.txt", "dir2/testObject.txt" }; var filesInDir = Directory.GetFiles(pathCA, "*.*", SearchOption.AllDirectories); Assert.Equal(filesExpected.Count(), filesInDir.Count()); foreach (var file in filesExpected) { String fullPath = Path.Combine(pathCA, file); Assert.True(File.Exists(fullPath)); } } finally { proj.Save(); 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("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 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(); } }
private static void ConvertAllSchematicsToCyPhy(string path) { var schematics = ConvertAllDevices(path); // Create MGA project on the spot. var proj = new MgaProject(); String connectionString = String.Format("MGA={0}", Path.GetTempFileName()); proj.Create(connectionString, "CyPhyML"); proj.EnableAutoAddOns(true); var mgaGateway = new MgaGateway(proj); proj.CreateTerritoryWithoutSink(out mgaGateway.territory); var module = new CyPhyComponentAuthoring.Modules .EDAModelImport() { CurrentProj = proj }; Dictionary<String, String> d_failures = new Dictionary<string, string>(); mgaGateway.PerformInTransaction(delegate { var rf = CyPhyClasses.RootFolder.GetRootFolder(proj); var cf = CyPhyClasses.Components.Create(rf); foreach (var t in schematics) { var identifier = t.Item1; var schematic = t.Item2; CyPhy.Component component = CyPhyClasses.Component.Create(cf); component.Name = identifier; module.SetCurrentComp(component); try { var cyphySchematicModel = module.BuildCyPhyEDAModel(schematic, component); Assert.Equal(component.Children.SchematicModelCollection.Count(), 1); } catch (Exception e) { d_failures[identifier] = e.ToString(); } } }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: true); proj.Save(); proj.Close(); if (d_failures.Any()) { String msg = String.Format("Failures in converting {0} component(s):" + Environment.NewLine, d_failures.Count); foreach (var kvp in d_failures) { msg += String.Format("{0}: {1}" + Environment.NewLine + Environment.NewLine, kvp.Key, kvp.Value); } Assert.True(false, msg); } }
//public List<IMgaFCO> InsertComponents( // IMgaFCO designContainer, // IMgaFCO componentRef, // List<IMgaFCO> components, // List<KeyValuePair<IMgaFCO, string>> messages) /// <summary> /// Calls CLM_LIght without showing any GUI. /// </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 projectPath, string absPathDesignContainer, List<string> absPathComponentsToAdd) { bool result = false; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + projectPath; //Type CLM_light_interpreter = Type.GetTypeFromProgID("MGA.Interpreter.CLM_light"); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { //dynamic interpreter = Activator.CreateInstance(CLM_light_interpreter); var interpreter = new CLM_light.CLM_lightInterpreter(); interpreter.Initialize(project); var terr = project.BeginTransactionInNewTerr(); var designContainer = project.ObjectByPath[absPathDesignContainer] as MgaFCO; List<IMgaFCO> componentsToAdd = new List<IMgaFCO>(); var defaultComponentRef = designContainer.ChildObjects.Cast<MgaFCO>().FirstOrDefault(x => x.Meta.Name == "ComponentRef"); var compRefCountBeforeInsert = designContainer.ChildObjects.Cast<MgaFCO>().Count(x => x.Meta.Name == "ComponentRef"); Assert.False(defaultComponentRef == null, string.Format("Design Container has no Component References: {0}", absPathDesignContainer)); foreach (string path in absPathComponentsToAdd) { var component = project.ObjectByPath[path] as MgaFCO; Assert.False(component == null, string.Format("Component was not found in the project: {0}", path)); componentsToAdd.Add(component); } List<KeyValuePair<IMgaFCO, string>> messages = new List<KeyValuePair<IMgaFCO, string>>(); if (interpreter.CheckForValidContext(designContainer)) { List<IMgaFCO> results = interpreter.InsertComponents(designContainer, defaultComponentRef, componentsToAdd, messages); var compRefCountAfterInsert = designContainer.ChildObjects.Cast<MgaFCO>().Count(x => x.Meta.Name == "ComponentRef"); result = compRefCountBeforeInsert + absPathComponentsToAdd.Count == compRefCountAfterInsert; project.AbortTransaction(); Assert.True(File.Exists(ProjectConnStr.Substring("MGA=".Length))); } } finally { project.Close(true); } return result; }
public static bool RunMasterInterpreter( string projectPath, string absPath, string configPath, bool postToJobManager = false, bool keepTempModels = false) { 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; var configObj = project.ObjectByPath[configPath] as MgaFCO; project.AbortTransaction(); using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project)) { masterInterpreter.Logger.GMEConsoleLoggingLevel = CyPhyGUIs.SmartLogger.MessageType_enum.Debug; var miResults = masterInterpreter.RunInTransactionOnOneConfig(testObj as MgaModel, configObj, postToJobManager, keepTempModels); result = miResults.Any(x => x.Success == false) ? false: true; } } finally { project.Close(true); } return result; }
public static bool AnalysisModelSupported(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(); CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null; project.BeginTransactionInNewTerr(); try { Assert.ThrowsDelegate d = () => { analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(testObj as MgaModel); }; Assert.DoesNotThrow(d); Assert.True(analysisModelProcessor != null, string.Format("Analysis model processor was not able to create the model processor for {0} {1}.", testObj.Name, testObj.Meta.Name)); } finally { project.AbortTransaction(); } } finally { project.Close(true); } return result; }
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); try { Assert.Contains("MGA.Addon.CyPhyMLPropagate", project.AddOnComponents.Cast<IMgaComponentEx>().Select(x => x.ComponentProgID)); CyPhyMetaLink.CyPhyMetaLinkAddon propagate = (CyPhyMetaLink.CyPhyMetaLinkAddon)project.AddOnComponents.Cast<IMgaComponent>().Where(comp => comp is CyPhyMetaLink.CyPhyMetaLinkAddon).FirstOrDefault(); CyPhyMetaLink.CyPhyMetalinkInterpreter interpreter = new CyPhyMetaLink.CyPhyMetalinkInterpreter(); propagate.TestMode = true; interpreter.GMEConsole = GME.CSharp.GMEConsole.CreateFromProject(project); interpreter.MgaGateway = new MgaGateway(project); interpreter.ConnectToMetaLinkBridge(project, 128); propagate.bridgeClient.SocketQueue.EditMessageReceived += msg => addonMessagesQueue.Add(msg); testAction(project, propagate, interpreter); } finally { project.Save(project.ProjectConnStr + "_posttest.mga", true); project.Close(true); } } catch (Exception e) { exception = 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(); } }
//[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 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> 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); } }