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; } }
public static void RunFormulaEvaluate(string projectPath, string absPath, bool automation) { Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + Path.GetFullPath(projectPath); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; project.AbortTransaction(); MgaFCOs fcos = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); Type tFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator"); var formulaEval = Activator.CreateInstance(tFormulaEval) as GME.MGA.IMgaComponentEx; formulaEval.ComponentParameter["automation"] = automation ? "true" : "false"; formulaEval.ComponentParameter["console_messages"] = "on"; formulaEval.ComponentParameter["expanded"] = "true"; //formulaEval.Initialize(project); formulaEval.InvokeEx(project, testObj, fcos, 16); } finally { project.Close(true); } }
public void 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 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 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 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 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 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 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 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 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); }
/// <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 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 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); }
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 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); } }
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); } }
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); }
//[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); } }
// Generator Entry Point public static string main(string projectPathFull, string targetPath, string namespaceName) { Clear(); Generator.Path = targetPath; IMgaProject project = new MgaProject(); IMgaTerritory territory = null; try { bool ro_mode = true; project.Open("MGA=" + projectPathFull, out ro_mode); territory = project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_READ_ONLY); GME.MGA.IMgaFolder root = project.RootFolder as GME.MGA.IMgaFolder; Generator.ClassName = root.Name; Generator.NamespaceName = namespaceName; foreach (GME.MGA.IMgaFCO fco in root.ChildFCOs) { ProcessParadigmSheet(fco); } foreach (GME.MGA.IMgaFolder fol in root.ChildFolders) { foreach (GME.MGA.IMgaFCO fco in fol.ChildFCOs) { ProcessParadigmSheet(fco); } } RootFolder rootFolder = new RootFolder(); rootFolder.Save(); foreach (DSM.Generators.Object elem in DSM.Generators.Object.ElementsByName.Values) { elem.Save(); } DSM.Generators.Enum.Save(); DSM.Generators.Generator.Save(); if (Errors.Count > 0) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Errors during generation process:"); foreach (string item in Errors) { sb.AppendLine(item); } } return(Generator.ClassName); } catch (Exception e) { MessageBox.Show("Error generationg domain-specific interface: " + e.Message); return(null); } finally { if (territory != null) { territory.Destroy(); project.AbortTransaction(); } project.Close(true); } }
private void AttachLibrary(LibraryInfo libraryInfo) { string mgaPath = metaPath + "\\" + libraryInfo.MgaName + ".mga"; if ((project.ProjectStatus & PROJECT_STATUS_OPEN) == PROJECT_STATUS_OPEN) { if (!File.Exists(mgaPath)) { GMEConsole.Error.WriteLine("Path '" + mgaPath + "' does not exist. Cannot attach " + libraryInfo.MgaName); return; } project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_BEGIN); try { project.BeginTransaction(project.ActiveTerritory); IMgaFolder oldLibFolder = project.RootFolder.ChildFolders.Cast <IMgaFolder>() .Where(x => string.IsNullOrWhiteSpace(x.LibraryName) == false && (x.Name.Contains(libraryInfo.DisplayName) || x.Name.Contains(libraryInfo.DisplayName))).FirstOrDefault(); bool needAttach; if (oldLibFolder == null) { needAttach = true; if (libraryPaths.Contains(Path.GetFullPath(project.ProjectConnStr.Substring("MGA=".Length)))) { // Don't attach libraries to themselves needAttach = false; } } else { DateTime oldModTime; long loldModTime; if (long.TryParse(oldLibFolder.RegistryValue["modtime"], out loldModTime)) { oldModTime = DateTime.FromFileTimeUtc(loldModTime); } else { oldModTime = DateTime.MinValue; } needAttach = File.GetLastWriteTimeUtc(mgaPath).CompareTo(oldModTime) > 0; if (!needAttach) { GMEConsole.Info.WriteLine("Library is up-to-date: embedded library modified " + oldModTime.ToString() + ", " + libraryInfo.MgaName + " modified " + File.GetLastWriteTimeUtc(mgaPath).ToString()); } } if (needAttach) { MgaProject proj = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); int mgaVersion; string paradigmName; string paradigmVersion; object paradigmGuid; bool readOnly; proj.QueryProjectInfo("MGA=" + mgaPath, out mgaVersion, out paradigmName, out paradigmVersion, out paradigmGuid, out readOnly); Guid guidP1 = ConvertToGUID(paradigmGuid); Guid guidP2 = ConvertToGUID(project.RootMeta.GUID); bool guidsEqual = guidP1.Equals(guidP2); if (paradigmName != project.MetaName || !guidsEqual) { GMEConsole.Info.WriteLine("Skipping refresh of " + libraryInfo.DisplayName + " because it uses a different metamodel version than the current project."); project.AbortTransaction(); // not true, but don't try again libraryInfo.attachedLibrary = true; return; } // GMEConsole.Info.WriteLine("Attaching library " + mgaPath); RootFolder newLibFolder = Common.Classes.RootFolder.GetRootFolder(project).AttachLibrary("MGA=" + mgaPath); DateTime modtime = File.GetLastWriteTimeUtc(mgaPath); ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).RegistryValue["modtime"] = modtime.ToFileTimeUtc().ToString(); if (oldLibFolder != null) { ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(oldLibFolder, newLibFolder.Impl, null); sw.UpdateSublibrary(); oldLibFolder.DestroyObject(); } ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).LibraryName = libraryInfo.DisplayName; GMEConsole.Info.WriteLine((oldLibFolder == null ? "Attached " : "Refreshed ") + libraryInfo.MgaName + ".mga library."); } project.CommitTransaction(); } catch (Exception e) { GMEConsole.Error.WriteLine("Error refreshing library: " + SecurityElement.Escape(e.Message)); project.AbortTransaction(); } finally { project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_END); } libraryInfo.attachedLibrary = 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; }
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 void CleanUpTempMgaProject(string outputFile) { var newProject = new MgaProject(); bool ro_mode; // open the copied temporary mga file newProject.Open("MGA=" + outputFile, out ro_mode); IMgaTerritory terr = null; try { // create a new transaction terr = newProject.BeginTransactionInNewTerr(); // get the sot object on which the job manager will operate var sot = newProject.GetObjectByID(sotConfig.SoTID); if (sot != null) { // if the sot object exists in the project GME.MGA.Meta.objtype_enum objtype; MgaObject parent; // get the parent folder of which this SoT belongs to. sot.GetParent(out parent, out objtype); if (objtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { // if it is really a folder cast it var parentSoTFolder = parent as MgaFolder; // get all SoT objects in the folder except the one we operate on // mark them for deletion var sotsToDelete = parentSoTFolder .ChildFCOs .Cast <MgaFCO>() .Where(x => x.ID != sotConfig.SoTID) .ToList(); try { // destroy all SoTs that are not used by this sot run sotsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } // get all not null test bench objects that this sot run uses. var referredTBsInSot = sot .ChildObjects .OfType <MgaReference>() .Where(x => x.Meta.Name == typeof(CyPhy.TestBenchRef).Name && x.Referred != null) .Select(x => x.Referred) .Cast <MgaModel>() .ToList(); foreach (var tb in referredTBsInSot) { GME.MGA.Meta.objtype_enum tbParentObjtype; MgaObject tbParent; // get the parent folder where the referenced test bench located tb.GetParent(out tbParent, out tbParentObjtype); if (tbParentObjtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { var parentTBFolder = tbParent as MgaFolder; // get all test benches that are not used by the sot // WARNING: sometimes COM object comparison can fail this code is not the safest. var tbsToDelete = parentTBFolder .ChildFCOs .OfType <MgaModel>() .Where(x => referredTBsInSot.Contains(x) == false) .ToList(); try { // delete test benches that sot does not use tbsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } } } } } // commit changes if everything is successful newProject.CommitTransaction(); } catch { // abort all changes if exception occured newProject.AbortTransaction(); } finally { if (terr != null) { // destroy the territory we were working in if it is not null terr.Destroy(); } } // close the project AND save all changes newProject.Close(); }
//[Fact] public void 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); } }
private bool CallCyberInterpreter(CyPhy.CyberModel cyberModel) { bool success = true; string cyberModelPath = string.Empty; // checks if (string.IsNullOrWhiteSpace(cyberModel.Attributes.FileRef)) { this.Logger.WriteError("[Cyber] Model filename attribute is empty: {0}", cyberModel.ToHyperLink()); return false; } if (Path.IsPathRooted(cyberModel.Attributes.FileRef)) { cyberModelPath = cyberModel.Attributes.FileRef; } else { cyberModelPath = Path.Combine(this.mainParameters.ProjectDirectory, cyberModel.Attributes.FileRef); } string cyberModelMgaPath = string.Empty; string cyberModelXmePath = string.Empty; bool requiresImport = false; cyberModelMgaPath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".mga"; cyberModelXmePath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".xme"; if (Path.GetExtension(cyberModelPath) == ".mga") { if (File.Exists(cyberModelMgaPath) == false) { requiresImport = true; if (File.Exists(cyberModelXmePath) == false) { this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath); return false; } } } else if (Path.GetExtension(cyberModelPath) == ".xme") { requiresImport = true; if (File.Exists(cyberModelXmePath) == false) { this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath); return false; } } else { this.Logger.WriteError("[Cyber] Model filename attribute has unknown extension (valid: [mga|xme]): {0} {1}", cyberModel.ToHyperLink(), Path.GetExtension(cyberModelPath)); return false; } MgaProject cyberProject = new MgaProject(); if (requiresImport) { // FIXME: this will throw an exception if xme is referenced mga exists and it is being used. MgaUtils.ImportXME(cyberModelXmePath, cyberModelMgaPath); } try { bool ro_mode; // FIXME: any race conditions here??? // FIXME: for SoT we need to copy the referenced xme/mgas cyberProject.Open("MGA=" + cyberModelMgaPath, out ro_mode); string cyberComponentPath = ""; if (cyberModel.Attributes.FilePathWithinResource.Contains('.')) { cyberComponentPath = cyberModel.Attributes.FilePathWithinResource.Substring(cyberModel.Attributes.FilePathWithinResource.IndexOf('.')).Replace(".", "/@"); } this.Logger.WriteInfo("[Cyber] {0} --> {1}", cyberModel.Attributes.FilePathWithinResource, cyberComponentPath); var terr = cyberProject.BeginTransactionInNewTerr(); MgaFCO currentObj = cyberProject.ObjectByPath[cyberComponentPath] as MgaFCO; cyberProject.AbortTransaction(); terr.Destroy(); if (currentObj == null) { this.Logger.WriteError("[Cyber] Referenced cyber object was not found in model: {0} {1} {2}", cyberModel.ToHyperLink(), cyberModelPath, cyberModel.Attributes.FilePathWithinResource); return false; } // Cyber model type and interpreter progid map. Each cyber model type has a different interpreter. Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string> interpreterMap = new Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string>() { //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.ESMoL, ""}, //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.SignalFlow, ""}, { CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.Simulink, "MGA.Interpreter.Cyber2SLC_CodeGen" } }; // call appropriate Cyber interpreter Type tCyber = Type.GetTypeFromProgID(interpreterMap[cyberModel.Attributes.ModelType]); if (tCyber == null) { this.Logger.WriteError("[Cyber] Cannot instantiate Cyber interpreter: {0} {1}", cyberModel.ToHyperLink(), interpreterMap[cyberModel.Attributes.ModelType]); } IMgaComponentEx cyberCodeGenerator = Activator.CreateInstance(tCyber) as IMgaComponentEx; cyberCodeGenerator.Initialize(cyberProject); var cyberOutputDir = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage); Directory.CreateDirectory(cyberOutputDir); cyberCodeGenerator.ComponentParameter["output_dir"] = cyberOutputDir; cyberCodeGenerator.ComponentParameter["automation"] = "true"; cyberCodeGenerator.ComponentParameter["console_messages"] = "off"; this.Logger.WriteInfo("Generating code for Cyber [{0}] elements...", cyberModel.Attributes.ModelType); System.Windows.Forms.Application.DoEvents(); MgaFCOs selectedobjs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); cyberCodeGenerator.InvokeEx(cyberProject, currentObj, selectedobjs, 128); this.Logger.WriteInfo("Cyber [{0}] code generation is done.", cyberModel.Attributes.ModelType); System.Windows.Forms.Application.DoEvents(); } catch (Exception ex) { this.Logger.WriteError("Cyber exception occured: {0}", ex); success = false; } return success; }
//[Fact] public void TestCodeSample() { string ProjectConnStr; MgaUtils.ImportXMEForTest(Path.GetFullPath(@"..\..\..\..\models\DynamicsTeam\MasterInterpreter\MasterInterpreter.xme"), out ProjectConnStr); MgaProject project = new MgaProject(); bool ro_mode; project.Open(ProjectConnStr, out ro_mode); MgaHelper.CheckParadigmVersionUpgrade(project); try { List<IMgaFCO> 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); } }
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 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); } }
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; }
//[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 CyPhyMasterInterpreter.MasterInterpreterResult Test(string tbpath, string configPath, int jobRunTimeout) { string tbId; string configId; project.BeginTransactionInNewTerr(); try { var tb = project.RootFolder.ObjectByPath[tbpath]; if (tb == null) { throw new ApplicationException("Could not find " + tbpath); } tbId = tb.ID; var config = project.RootFolder.ObjectByPath[configPath]; if (config == null) { throw new ApplicationException("Could not find " + configPath); } configId = config.ID; } finally { project.AbortTransaction(); } var configurationSelection = new CyPhyMasterInterpreter.ConfigurationSelectionLight() { PostToJobManager = true, ContextId = tbId, SelectedConfigurationIds = new string[] { configId } }; if (masterApi != null) { masterApi.Dispose(); } masterApi = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(); masterApi.Initialize(project); var results = masterApi.RunInTransactionWithConfigLight(configurationSelection); if (results.First().Success == false) { throw new ApplicationException("MasterInterpreter run failed"); } while (true) { Job job; if (jobUpdates.TryTake(out job, jobRunTimeout)) { if (Job.IsFailedStatus(job.Status)) { // TODO dump logs, stdout.txt, stderr.txt throw new ApplicationException("Remote run failed: " + job.Status); } else if (job.Status == Job.StatusEnum.Succeeded) { break; } } else { throw new TimeoutException(); } } return(results[0]); }
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 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")); }
//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; }
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; } }
public static Tuple <CyPhyGUIs.InterpreterMainParameters, CyPhyGUIs.IInterpreterResult> RunReturnFull(string outputdirname, string projectPath, string absPath, CyPhyGUIs.SmartLogger logger = null, Action <MgaProject> preProcess = null) { var mainParameters = new CyPhyGUIs.InterpreterMainParameters(); CyPhyGUIs.IInterpreterResult results = null; Assert.True(File.Exists(projectPath), "Project file does not exist."); string ProjectConnStr = "MGA=" + projectPath; //Type CyPhyPETInterpreter = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyPET"); //Type MainParametersType = Type.GetTypeFromProgID("ISIS.CyPhyML.InterpreterConfiguration"); MgaProject project = new MgaProject(); project.OpenEx(ProjectConnStr, "CyPhyML", null); try { if (preProcess != null) { preProcess(project); } var terr = project.BeginTransactionInNewTerr(); var testObj = project.ObjectByPath[absPath] as MgaFCO; Assert.True(testObj != null, String.Format("Could not find FCO by path '{0}'", absPath)); mainParameters.OriginalCurrentFCOName = testObj.Name; project.AbortTransaction(); string OutputDir = Path.Combine(Path.GetDirectoryName(projectPath), outputdirname); OutputDir = Path.GetFullPath(OutputDir); if (Directory.Exists(OutputDir)) { CyPhyGUIs.CyPhyDirectory.EnsureEmptyDirectory(OutputDir); } Directory.CreateDirectory(OutputDir); //dynamic interpreter = Activator.CreateInstance(CyPhyPETInterpreter); var interpreter = new CyPhyPET.CyPhyPETInterpreter(); interpreter.Initialize(project); //dynamic mainParameters = Activator.CreateInstance(MainParametersType); 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); interpreter.Logger = logger; results = interpreter.MainThrows(mainParameters); Assert.True(File.Exists(ProjectConnStr.Substring("MGA=".Length))); if (results.Success == false) { Test.DeleteDirectory(OutputDir); } } finally { project.Close(true); } return(new Tuple <CyPhyGUIs.InterpreterMainParameters, CyPhyGUIs.IInterpreterResult>(mainParameters, results)); }