//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; }
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 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); }
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 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 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 void CallCyPhy2CADWithTransaction(MgaProject project, MgaFCO toplevelAssembly, int param) { if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(project); } Dictionary <MgaFCO, MgaFCO> objectMap = new Dictionary <MgaFCO, MgaFCO>(); try { project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); handleEvents = false; GenerateCADAssemblyXml(project, toplevelAssembly, param); try { HighlightInTree(toplevelAssembly, 1); } catch (Exception e) { GMEConsole.Error.Write("Error during processing the model: " + e.Message); // Don't do anything, there won't be highlight } } finally { project.AbortTransaction(); handleEvents = 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 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 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 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 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 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); } }
private void RunInTransaction(Action <MgaProject> action) { MgaProject project = m_Input.designContainer.Impl.Project; project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { action(project); project.CommitTransaction(); } catch (Exception) { try { project.AbortTransaction(); } catch { } throw; } }
/// <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); }
/// <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 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 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 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 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 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 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 ConfigurationSelection GetConfigurationSelection(MgaProject project) { ConfigurationSelection config = new ConfigurationSelection() { PostToJobManager = this.PostToJobManager, KeepTemporaryModels = this.KeepTemporaryModels }; try { project.BeginTransactionInNewTerr(); using (CyPhyGUIs.GMELogger logger = new CyPhyGUIs.GMELogger(project)) { config.Context = this.GetGMEObjectFromIdentification <MgaModel>(project, this.ContextId); if (config.Context == null) { logger.WriteError("Context was not found based on this id '{0}'", this.ContextId); } config.SelectedConfigurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); foreach (var selectedId in this.SelectedConfigurationIds) { var selectedElement = this.GetGMEObjectFromIdentification <MgaFCO>(project, selectedId); if (selectedElement != null) { // should be CWC or Component assembly config.SelectedConfigurations.Append(selectedElement); } else { logger.WriteError("Configuration was not found based on this id '{0}'", selectedId); } } } } finally { project.AbortTransaction(); } return(config); }
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 Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { string OutputBaseDir = (string)componentParameters["output_dir"]; SotConfig sotConfig = new SotConfig(); sotConfig.MultiJobRun = true; sotConfig.OriginalProjectFileName = project.ProjectConnStr.Substring("MGA=".Length); sotConfig.ProjectFileName = Path.Combine(OutputBaseDir, Path.GetFileName(sotConfig.OriginalProjectFileName)); // can't be in a tx and save the project project.AbortTransaction(); project.Save("MGA=" + sotConfig.ProjectFileName, true); project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); MgaGateway.PerformInTransaction(delegate { sotConfig.SoTID = currentobj.ID; }, transactiontype_enum.TRANSACTION_READ_ONLY); using (StreamWriter writer = new StreamWriter(Path.Combine(OutputBaseDir, "manifest.sot.json"))) { writer.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(sotConfig, Newtonsoft.Json.Formatting.Indented)); } string configsDir = Path.Combine(Path.GetDirectoryName((string)componentParameters["original_project_file"]), "config"); if (Directory.Exists(configsDir)) { var configs = Directory.EnumerateFiles(configsDir, "*xml").ToList(); string sotConfigDir = Path.Combine(OutputBaseDir, "config"); Directory.CreateDirectory(sotConfigDir); foreach (var config in configs) { File.Copy(config, Path.Combine(sotConfigDir, Path.GetFileName(config))); } } //componentParameters["labels"] = ""; //componentParameters["runCommand"] = ; //componentParameters["results_zip_py"] as string; // result.LogFileDirectory = Path.Combine(MainParameters.ProjectDirectory, "log"); // componentParameters["build_query"] as string; }
public static void CheckParadigmVersionUpgrade(MgaProject project) { GME.Util.MgaRegistrar registar = new GME.Util.MgaRegistrar(); string MetaConnStr; object MetaGuid = null; object ProjectMetaGuid; project.BeginTransactionInNewTerr(); try { registar.QueryParadigm(project.MetaName, out MetaConnStr, ref MetaGuid, GME.Util.regaccessmode_enum.REGACCESS_BOTH); ProjectMetaGuid = project.MetaGUID; } finally { project.AbortTransaction(); } if (((Array)ProjectMetaGuid).Cast<byte>().SequenceEqual(((Array)MetaGuid).Cast<byte>()) == false) { Xunit.Assert.True(false, string.Format("Please upgrade {0} to the latest registered {1} paradigm", project.ProjectConnStr, project.MetaName)); } }
public static void CheckParadigmVersionUpgrade(MgaProject project) { GME.Util.MgaRegistrar registar = new GME.Util.MgaRegistrar(); string MetaConnStr; object MetaGuid = null; object ProjectMetaGuid; project.BeginTransactionInNewTerr(); try { registar.QueryParadigm(project.MetaName, out MetaConnStr, ref MetaGuid, GME.Util.regaccessmode_enum.REGACCESS_BOTH); ProjectMetaGuid = project.MetaGUID; } finally { project.AbortTransaction(); } if (((Array)ProjectMetaGuid).Cast <byte>().SequenceEqual(((Array)MetaGuid).Cast <byte>()) == false) { Xunit.Assert.True(false, string.Format("Please upgrade {0} to the latest registered {1} paradigm", project.ProjectConnStr, project.MetaName)); } }
public void ComponentLibraryManagerAddonRelativeProjectPathURI() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.EnableAutoAddOns(true); project.OpenEx(mgaReference, "CyPhyML", null); 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. } } var components = project.RootFolder.CreateFolder(project.RootMeta.RootFolder.LegalChildFolderByName["Components"]); components.Name = "ComponentLibraryManagerAddonProjectPathURITest"; var component = components.CreateRootObject(project.RootMeta.RootFolder.DefinedFCOByName["Component", false]); component.Name = "ComponentLibraryManagerAddonProjectPathURITest"; project.CommitTransaction(); } finally { project.Close(false); } }
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); }
public void TestInitArguments() { MgaProject project = new MgaProject(); project.OpenEx("MGA=" + mgaFile, "CyPhyML", null); try { project.BeginTransactionInNewTerr(); try { string petExperimentPath = "/@Testing/@ParametricExploration/@TestAnalysis"; string assemblyDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); string pyFile = Path.Combine(assemblyDir, "..\\..\\..\\..\\models\\PET_simple_proof-of-concept\\sample_analysis.py"); MgaModel model = (MgaModel)project.ObjectByPath[petExperimentPath]; var params_ = CyPhyPET.CyPhyPETInterpreter.GetPythonComponentInitializerParameters(pyFile, (MgaFCO)model); Assert.Equal(new string[] { "self", "config1", "config2", "opt1", "opt2" }, params_.args); Assert.Equal(new string[] { "self", "config1", "config2" }, params_.requiredArgs); Assert.Equal(new object[] { null, 0.0 }, params_.defaults); var analysisBlock = ISIS.GME.Dsml.CyPhyML.Classes.AnalysisBlock.Cast(model.ObjectByPath["/@AnalysisBlock"]); CyPhyPET.CyPhyPETInterpreter.EditConfigurationParameters(params_, analysisBlock, showGui: false); var kwargs = CyPhyPET.CyPhyPETInterpreter.GetConfigurationParameters(analysisBlock); CyPhyPET.CyPhyPETInterpreter.GetParamsAndUnknownsForPythonOpenMDAO(pyFile, analysisBlock, kwargs); } finally { project.AbortTransaction(); } } finally { project.Close(true); } }
public void Test_CyPhyPET_unit_matcher() { var project = new MgaProject(); project.OpenEx("MGA=" + this.mgaFile, "CyPhyML", null); try { project.BeginTransactionInNewTerr(); try { var wrapper = project.RootFolder.ObjectByPath["/@Testing/@ParametricExploration/@TestPython/@PythonWrapper"]; var pythonBlock = ISIS.GME.Dsml.CyPhyML.Classes.PythonWrapper.Cast(wrapper); var binDir = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Workflow_PET_Test)).CodeBase.Substring("file:///".Length)); var path = Path.GetFullPath(binDir + "/../../paraboloid.py"); var pet = CyPhyPET.CyPhyPETInterpreter.GetParamsAndUnknownsForPythonOpenMDAO(path, pythonBlock); // "{\"unknowns\": {\"f_xy\": {\"units\": \"m**3\", \"gme_unit_id\": \"id-0065-00000179\", \"shape\": 1, \"val\": 0.0, \"size\": 1}}, \"params\": {\"x\": {\"units\": \"m\", \"gme_unit_id\": \"id-0066-00000014\", \"shape\": 1, \"val\": 0.0, \"size\": 1}, \"y\": {\"units\": \"m**3\", \"gme_unit_id\": \"id-0065-00000179\", \"shape\": 1, \"val\": 0.0, \"size\": 1}}}" var unknowns = pet["unknowns"]; var params_ = pet["params"]; var x = params_["x"]; var y = params_["y"]; var f_xy = unknowns["f_xy"]; Assert.Equal("Meter", project.GetFCOByID((string)x["gme_unit_id"]).Name); Assert.Equal("Cubic Meter", project.GetFCOByID((string)y["gme_unit_id"]).Name); Assert.Equal("Cubic Meter", project.GetFCOByID((string)f_xy["gme_unit_id"]).Name); } finally { project.CommitTransaction(); } } finally { project.Close(abort: true); } }
private void ExecuteInTransaction(MgaProject project, Action doWork) { if (project == null || doWork == null) { throw new ArgumentNullException(); } var terr = project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { doWork(); project.CommitTransaction(); project.FlushUndoQueue(); } catch (Exception) { try { project.AbortTransaction(); } catch { } throw; } }
//[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 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")); }
//[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; }
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; }
//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; }
private void ExecuteInTransaction(MgaProject project, Action doWork, bool abort = false, transactiontype_enum type = transactiontype_enum.TRANSACTION_NON_NESTED) { if (project == null || doWork == null) { throw new ArgumentNullException(); } bool inTx = (project.ProjectStatus & 8) != 0; if (inTx) { doWork(); return; } project.BeginTransactionInNewTerr(type); try { doWork(); if (abort) { project.AbortTransaction(); } else { project.CommitTransaction(); } project.FlushUndoQueue(); } catch (Exception) { try { project.AbortTransaction(); } catch { } throw; } }
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; }
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 CallCyPhy2CADWithTransaction(MgaProject project, MgaFCO toplevelAssembly, int param) { if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(project); } Dictionary<MgaFCO, MgaFCO> objectMap = new Dictionary<MgaFCO, MgaFCO>(); try { project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); handleEvents = false; GenerateCADAssemblyXml(project, toplevelAssembly, param); try { HighlightInTree(toplevelAssembly, 1); } catch (Exception e) { GMEConsole.Error.Write("Error during processing the model: " + e.Message); // Don't do anything, there won't be highlight } } finally { project.AbortTransaction(); handleEvents = 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> 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); } }