private avm.Component FindAndConvert(string compName, string compFolName) { avm.Component avmComp = null; proj.PerformInTransaction(delegate { CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components cf = rf.Children.ComponentsCollection.First(f => f.Name == compFolName); CyPhy.Component comp = cf.Children.ComponentCollection.First(c => c.Name == compName); avmComp = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(comp); }); string outPath = Path.Combine(testPath, "output"); if (!Directory.Exists(outPath)) { Directory.CreateDirectory(outPath); } CyPhyComponentExporter.CyPhyComponentExporterInterpreter.SerializeAvmComponent(avmComp, Path.Combine(outPath, String.Format("{0}-{1}.exported.acm", compFolName, compName))); return(avmComp); }
public void CADMetric() { string p_TestFolder = Path.Combine(InterchangeTestDirectory, "ComponentInterchangeTest", "SharedModels", "CompCadMetric"); string p_DesiredResultXME = Path.Combine(p_TestFolder, "DesiredResult.xme"); string p_DesiredResultMGA; GME.MGA.MgaUtils.ImportXMEForTest(p_DesiredResultXME, out p_DesiredResultMGA); p_DesiredResultMGA = p_DesiredResultMGA.Replace("MGA=", ""); Assert.True(File.Exists(p_DesiredResultMGA), "DesiredResult.mga not found. Import may have failed."); Assert.True(0 == Common.runCyPhyComponentExporterCL(p_DesiredResultMGA), "Component exporter failed."); String p_expectedACM = Path.Combine(p_TestFolder, "expected.component.acm"); String p_generatedACM = Path.Combine(p_TestFolder, "Components", "CompWithCADMetric", "CompWithCADMetric.component.acm"); Assert.True(File.Exists(p_generatedACM), "Exported ACM file not found."); avm.Component component = AvmXmlSerializer.Deserialize <avm.Component>(File.ReadAllText(p_generatedACM)); var parameterValue = component.Property.OfType <avm.PrimitiveProperty>().First().Value; var cadMetricValue = component.DomainModel.OfType <avm.cad.CADModel>().First().ModelMetric.First().Value; Assert.True(parameterValue.ValueExpression is avm.DerivedValue); Assert.True(cadMetricValue.ValueExpression is avm.FixedValue); // TODO: add regression test // Assert.True(0 == RunXmlComparator(p_generatedACM, p_expectedACM), "Generated ACM files doesn't match expected output."); }
public void CheckExportedACM() { avm.Component acm = null; using (var reader = new StreamReader(path_ExportedACM)) { acm = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(reader); } Assert.Equal(1, acm.Connector.Count); var connector = acm.Connector.FirstOrDefault(); Assert.Equal(8, connector.Role.Count); var datums = connector.Role.OfType <avm.cad.Datum>(); Assert.Equal(8, datums.Count()); var guideDatums = connector.ConnectorFeature.OfType <avm.cad.GuideDatum>(); Assert.Equal(4, guideDatums.Count()); foreach (var guideDatum in guideDatums) { var linkedDatum = datums.FirstOrDefault(x => x.ID == guideDatum.Datum); Assert.NotNull(linkedDatum); Assert.True(linkedDatum.Name.StartsWith("GD_")); } }
public void Import() { var pathACM = Path.Combine(fixture.testPath, "CompWithCyber.acm"); avm.Component avmComp = null; using (var tr = new StreamReader(pathACM)) { avmComp = CyPhyComponentImporter.CyPhyComponentImporterInterpreter .DeserializeAvmComponentXml(tr); } proj.PerformInTransaction(delegate { var rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(proj); var cf = rf.Children.ComponentsCollection.First(); var comp = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cf, avmComp); Assert.Equal(1, comp.Children.CyberModelCollection.Count()); var CyberModel = comp.Children.CyberModelCollection.First(); Assert.Equal("author", CyberModel.Attributes.Author); Assert.Equal("notes", CyberModel.Attributes.Notes); Assert.Equal("RootFolder.Components.excavator_control", CyberModel.Attributes.FilePathWithinResource); Assert.Equal("Simulink.excavator_control_type", CyberModel.Attributes.Class); Assert.Equal(ISIS.GME.Dsml.CyPhyML.Classes.CyberModel.AttributesClass.ModelType_enum.Simulink, CyberModel.Attributes.ModelType); #region fetch objects var ActualBoom_Connector = comp.Children.ConnectorCollection.FirstOrDefault(c => c.Name.Equals("ActualBoom_Connector")); Assert.NotNull(ActualBoom_Connector); var connector_ActualBoom_1 = ActualBoom_Connector.Children.ModelicaConnectorCollection.FirstOrDefault(); Assert.NotNull(connector_ActualBoom_1); var boomValve_Connector = comp.Children.ConnectorCollection.FirstOrDefault(c => c.Name.Equals("boomValve_Connector")); Assert.NotNull(boomValve_Connector); var connector_boomValve_1 = boomValve_Connector.Children.ModelicaConnectorCollection.FirstOrDefault(); Assert.NotNull(connector_boomValve_1); var ActualBoom_Port = comp.Children.ModelicaConnectorCollection.FirstOrDefault(mc => mc.Name.Equals("ActualBoom_Port")); Assert.NotNull(ActualBoom_Port); var boomValve_Port = comp.Children.ModelicaConnectorCollection.FirstOrDefault(mc => mc.Name.Equals("boomValve_Port")); Assert.NotNull(boomValve_Port); var ActualBoom_1 = CyberModel.Children.ModelicaConnectorCollection.FirstOrDefault(mc => mc.Name.Equals("ActualBoom_1")); Assert.NotNull(ActualBoom_1); var boomValve_1 = CyberModel.Children.ModelicaConnectorCollection.FirstOrDefault(mc => mc.Name.Equals("boomValve_1")); Assert.NotNull(boomValve_1); var sample_Period = comp.Children.ParameterCollection.FirstOrDefault(p => p.Name.Equals("sample_Period")); Assert.NotNull(sample_Period); var SamplePeriod = CyberModel.Children.ModelicaParameterCollection.FirstOrDefault(mp => mp.Name.Equals("SamplePeriod")); Assert.NotNull(SamplePeriod); #endregion AssertConnected(comp, connector_ActualBoom_1.Impl, ActualBoom_1.Impl); AssertConnected(comp, connector_boomValve_1.Impl, boomValve_1.Impl); AssertConnected(comp, ActualBoom_Port.Impl, ActualBoom_1.Impl); AssertConnected(comp, boomValve_Port.Impl, boomValve_1.Impl); Assert.Equal(1, comp.Children.ModelicaParameterPortMapCollection.Count()); Assert.Equal(1, comp.Children.ModelicaParameterPortMapCollection.Count(vf => (vf.SrcEnd.ID == sample_Period.ID && vf.DstEnd.ID == SamplePeriod.ID))); }); }
public void NoCategory() { String compName = GetCurrentMethodName(); avm.Component comp = new avm.Component() { Classifications = null, Name = compName }; String pathComp = Path.Combine(pathTest, comp.Name + ".acm"); comp.SaveToFile(pathComp); IMgaFCO cyphyComp = null; proj.PerformInTransaction(delegate { cyphyComp = importer.ImportFile(proj, pathTest, pathComp); }); String expectedPath = "RootFolder/Components/" + compName; proj.PerformInTransaction(delegate { Assert.NotNull(cyphyComp); String pathCyPhyComp = GetSimplePath(cyphyComp as MgaObject); Assert.Equal(expectedPath, pathCyPhyComp); }); }
public void Import_NewStyle_Dist() { string testNote = "STATEMENT C -- test note"; proj.PerformInTransaction(delegate { CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components cf = rf.Children.ComponentsCollection.First(f => f.Name == "Components"); avm.Component avmComp = new avm.Component() { Name = "Imported_NewStyle_Dist" }; avmComp.DistributionRestriction.Add(new avm.DoDDistributionStatement() { Type = avm.DoDDistributionStatementEnum.StatementC, Notes = testNote }); var cyphyComp = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cf, avmComp); Assert.False(cyphyComp.Children.ITARCollection.Any()); var distCollection = cyphyComp.Children.DoDDistributionStatementCollection; Assert.True(distCollection.Count() == 1); Assert.True(distCollection.First().Attributes.DoDDistributionStatementEnum == CyPhyClasses.DoDDistributionStatement.AttributesClass.DoDDistributionStatementEnum_enum.StatementC); Assert.Equal(testNote, distCollection.First().Attributes.Notes); }); }
private CyPhy.Component ExportThenImport(CyPhyML.Component comp, out CyPhy.Components importedcomponents, String testName) { // export the component avm.Component exportee = CyPhyML2AVM.AVMComponentBuilder.CyPhyML2AVM(comp); CyPhyComponentExporter.CyPhyComponentExporterInterpreter.SerializeAvmComponent(exportee, Path.Combine(testPath, testName + ".acm")); // import the component back in CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(fixture.proj); importedcomponents = CyPhyClasses.Components.Create(rf); return(AVM2CyPhyML.CyPhyMLComponentBuilder.AVM2CyPhyML(importedcomponents, exportee)); }
public void Import_NewStyle_NotITAR() { proj.PerformInTransaction(delegate { CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components cf = rf.Children.ComponentsCollection.First(f => f.Name == "Components"); avm.Component avmComp = new avm.Component() { Name = "Imported_NewStyle_NotITAR" }; var cyphyComp = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cf, avmComp); Assert.False(cyphyComp.Children.DistributionRestrictionCollection.Any()); }); }
public void CategoryIsBlankString() { var category = new List <String> { "" }; String compName = GetCurrentMethodName(); // Create the test component and export it to disk. avm.Component comp = new avm.Component() { Classifications = new List <String>() { "" }, Name = compName }; String pathComp = Path.Combine(pathTest, comp.Name + ".acm"); comp.SaveToFile(pathComp); // Import the component IMgaFCO cyphyComp = null; proj.PerformInTransaction(delegate { cyphyComp = importer.ImportFile(proj, pathTest, pathComp); }); // Check that its path is what we expected var expectedPath = String.Join("/", new List <String>() { "RootFolder", "Components", compName }); proj.PerformInTransaction(delegate { Assert.NotNull(cyphyComp); String pathCyPhyComp = GetSimplePath(cyphyComp as MgaObject); Assert.Equal(expectedPath, pathCyPhyComp); }); }
private void CreateComponent_ImportComponent_CheckPath(List <string> category, String compName) { // Create the test component and export it to disk. avm.Component comp = new avm.Component() { Classifications = new List <String>() { String.Join(".", category) }, Name = compName }; String pathComp = Path.Combine(pathTest, comp.Name + ".acm"); comp.SaveToFile(pathComp); // Import the component IMgaFCO cyphyComp = null; proj.PerformInTransaction(delegate { cyphyComp = importer.ImportFile(proj, pathTest, pathComp); }); // Check that its path is what we expected var expectedPath = String.Join("/", new List <String>() { "RootFolder", "Components", String.Join("/", category), compName }); proj.PerformInTransaction(delegate { Assert.NotNull(cyphyComp); String pathCyPhyComp = GetSimplePath(cyphyComp as MgaObject); Assert.Equal(expectedPath, pathCyPhyComp); }); }
public void Import_NewStyle_ITAR() { proj.PerformInTransaction(delegate { CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components cf = rf.Children.ComponentsCollection.First(f => f.Name == "Components"); avm.Component avmComp = new avm.Component() { Name = "Imported_NewStyle_ITAR" }; avmComp.DistributionRestriction.Add(new avm.ITAR()); var cyphyComp = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cf, avmComp); var itarCollection = cyphyComp.Children.ITARCollection; Assert.True(itarCollection.Count() == 1); Assert.True(itarCollection.First().Attributes.RestrictionLevel == CyPhyClasses.ITAR.AttributesClass.RestrictionLevel_enum.ITAR); Assert.False(cyphyComp.Children.DoDDistributionStatementCollection.Any()); }); }
public void ImportCADModel(string CADpath = null) { string cadFilename = ""; this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name); using (this.Logger) { //The CAT module will perform these steps, in this order: // - Check that the user has Creo (so that the extraction will be successful) // - Implementation Suggestion: The extraction utility may have special flag to have it indicates if all the dependencies are met // - Display a dialog box to let the user choose their Creo model file bool cad_file_chosen = false; bool test_copy_and_path_only = false; if (string.IsNullOrWhiteSpace(CADpath)) { cad_file_chosen = get_cad_file(out cadFilename); } else { test_copy_and_path_only = true; cadFilename = CADpath; if (File.Exists(cadFilename)) { cad_file_chosen = true; } else { this.Logger.WriteError("Invalid CAD file path passed in: " + CADpath); } } // - Run the extractor on the Creo model file #region Run the Extractor bool extractor_ran_success = test_copy_and_path_only; string tempXMLfile = Path.GetTempFileName(); this.Logger.WriteDebug("Temporary XML file created: " + tempXMLfile); if (cad_file_chosen && !test_copy_and_path_only) { try { // assemble the arg string // first the input CAD file // include quotation marks to handle paths with white spaces string argstring = "ExtractACM-XMLfromCreoModels -c \""; argstring += cadFilename; argstring += "\""; // add the XML output file name argstring += " -x \""; argstring += tempXMLfile; argstring += "\""; // Debug only: pause before exit, graphics mode. //argstring += " -p -g"; Process firstProc = new Process(); string path = Path.Combine(META.VersionInfo.MetaPath, "bin\\CAD\\Creo\\bin\\CADCreoParametricCreateAssembly.exe"); if (!File.Exists(path)) { this.Logger.WriteError(String.Format("Cannot find '{0}'", path)); throw new Exception("CADCreoParametricCreateAssembly.exe not found."); } firstProc.StartInfo.FileName = path; firstProc.StartInfo.Arguments = argstring; firstProc.StartInfo.CreateNoWindow = true; firstProc.StartInfo.UseShellExecute = false; firstProc.StartInfo.RedirectStandardOutput = true; firstProc.StartInfo.RedirectStandardError = true; firstProc.StartInfo.RedirectStandardInput = true; int streamsClosed = 0; StringBuilder exeConsoleOutput = new StringBuilder(); DataReceivedEventHandler handler = (sender, e) => { lock (Logger) { if (e.Data == null) { streamsClosed += 1; if (streamsClosed == 2) { } return; } Logger.WriteDebug(e.Data); exeConsoleOutput.AppendLine(e.Data); } }; firstProc.OutputDataReceived += handler; firstProc.ErrorDataReceived += handler; firstProc.EnableRaisingEvents = true; bool showProgressBar = sender != null && sender is IWin32Window; bool done = false; Object doneSyncObject = new object(); GUIs.CADProgress progress = null; EventHandler closeDialogWithSuccess = (e, o) => { lock (doneSyncObject) { if (done == false) { progress.BeginInvoke((Action)(() => { done = true; progress.DialogResult = DialogResult.OK; progress.Close(); })); } } }; if (showProgressBar) { progress = new GUIs.CADProgress(); firstProc.Exited += closeDialogWithSuccess; } IntPtr job = JobObjectPinvoke.CreateKillOnCloseJob(); firstProc.Exited += (s, o) => { if (job != JobObjectPinvoke.INVALID_HANDLE_VALUE) { JobObjectPinvoke.CloseHandle(job); } if (progress != null && progress.DialogResult == DialogResult.Cancel) { File.Delete(tempXMLfile); } }; this.Logger.WriteDebug("Calling CADCreoParametricCreateAssembly.exe with argument string: " + argstring); firstProc.Start(); JobObjectPinvoke.AssignProcessToJobObject(firstProc, job); firstProc.StandardInput.Close(); firstProc.BeginOutputReadLine(); firstProc.BeginErrorReadLine(); if (showProgressBar) { progress.FormClosing += (e, o) => { lock (doneSyncObject) { firstProc.Exited -= closeDialogWithSuccess; done = true; } }; var result = progress.ShowDialog((IWin32Window)sender); if (result == DialogResult.Cancel) { cleanup(null, true); return; } } else { firstProc.WaitForExit(); } this.Logger.WriteDebug("CADCreoParametricCreateAssembly.exe ExtractACM-XMLfromCreoModels has completed."); if (firstProc.ExitCode == 0) { extractor_ran_success = true; } else { this.Logger.WriteDebug("CADCreoParametricCreateAssembly.exe ExtractACM-XMLfromCreoModels returned error code " + firstProc.ExitCode.ToString()); // Warn with last non-empty line, it should contain a useful error message Regex lastLine = new Regex("[\\n^]([^\\n]+)(\\n|\\s)*$", RegexOptions.Singleline); var match = lastLine.Match(exeConsoleOutput.ToString()); if (match != null && match.Success) { this.Logger.WriteWarning(match.Groups[1].Value); } throw new Exception("Extract executable returned error code " + firstProc.ExitCode.ToString() + ". Detailed log at " + this.Logger.LogFilenames.FirstOrDefault()); } } catch (Exception ex) { this.Logger.WriteError("An error occurred running Creo parametric: " + ex.Message + " - Extraction Failed. Insure you can access the Creo license server"); cleanup(tempXMLfile, true); return; } } #endregion // - Use a function from CyPhy2ComponentModel to convert the extractor's XML format into a CyPhy model fragment #region Convert_to_XML // used in creating the resource object below CyPhy.CADModel ProcessedCADModel = null; if (extractor_ran_success && !test_copy_and_path_only) { this.Logger.WriteDebug("About to call DeserializeAvmComponentXml..."); StreamReader streamReader = new StreamReader(tempXMLfile); avm.Component ac_import = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(streamReader); streamReader.Close(); this.Logger.WriteDebug("... finished DeserializeAvmComponentXml call."); foreach (var cadmodel in ac_import.DomainModel.Where(dm => dm is avm.cad.CADModel) .Cast <avm.cad.CADModel>()) { var rf = CyPhyClasses.RootFolder.GetRootFolder(CurrentProj); AVM2CyPhyML.CyPhyMLComponentBuilder newComponent = new AVM2CyPhyML.CyPhyMLComponentBuilder(rf); ProcessedCADModel = newComponent.process(cadmodel, (CyPhy.Component)GetCurrentDesignElement()); ProcessedCADModel.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFilename)); } // find the largest current Y value so our new elements are added below the existing design elements foreach (var child in GetCurrentDesignElement().AllChildren) { foreach (MgaPart item in (child.Impl as MgaFCO).Parts) { int read_x, read_y; string read_str; item.GetGmeAttrs(out read_str, out read_x, out read_y); greatest_current_y = (read_y > greatest_current_y) ? read_y : greatest_current_y; } } // layout CAD model to the "south" of existing elements foreach (MgaPart item in (ProcessedCADModel.Impl as MgaFCO).Parts) { item.SetGmeAttrs(null, CAD_MODEL_START_X, greatest_current_y + CAD_MODEL_START_Y); } // Extend it's properties out to the component level. this.CADModuleImportExtension(ProcessedCADModel); } else if (test_copy_and_path_only) { ProcessedCADModel = CyPhyClasses.CADModel.Create((CyPhy.Component)GetCurrentDesignElement()); ProcessedCADModel.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(CADpath)); } #endregion // - Copy the Creo Model files into the component's backend folder // - Note: The solution includes a function that can find this folder using the project.manifest.json file. // - For nice organization, create them in a subfolder called "CAD" // create avmproj #region Copy files to backend folder // used in creating the resource object below string PathforComp = null; var importedCADFiles = new List <String>(); if (extractor_ran_success) { try { // create the destination path PathforComp = META.ComponentLibraryManager.EnsureComponentFolder((CyPhy.Component)GetCurrentDesignElement()); PathforComp = ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE); string finalPathName = Path.Combine(PathforComp, "CAD"); Directory.CreateDirectory(finalPathName); // determine if one part file or all part and assembly files need to be copied string cpsrcfile = System.IO.Path.GetFileName(cadFilename); // copy the selected file string cadFileCopyPath = System.IO.Path.Combine(finalPathName, cpsrcfile); if (Path.GetFullPath(cadFilename) != Path.GetFullPath(cadFileCopyPath)) { System.IO.File.Copy(cadFilename, cadFileCopyPath, true); } // Set "primary" file as the first in the list. importedCADFiles.Add(Path.Combine("CAD", Path.GetFileName(cadFileCopyPath))); if (fileISasm(cpsrcfile) && !test_copy_and_path_only) { // get a string of the XML contents this.Logger.WriteDebug("About to read contents of XML file using class XmlDocument: " + tempXMLfile); XmlDocument doc = new XmlDocument(); doc.Load(tempXMLfile); string xmlcontents = doc.InnerXml; // mine down to the Resource dependencies using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents))) { // iterate through each file listed in the resourcedependency section while (reader.ReadToFollowing("ResourceDependency") == true) { string res_path = reader.GetAttribute("Path"); this.Logger.WriteDebug("Copying this file: " + res_path); // CAD files end in .1 .2 etc. Pick the latest ones var allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*prt." /*n.b. literal dot*/ + "*") .Concat(Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*asm.*")) .Select(Path.GetFileName) .Select(filename => new { basename = filename.Substring(0, filename.LastIndexOf('.')), version = filename.Substring(filename.LastIndexOf('.') + 1) }) .Where(p => { int val; return(Int32.TryParse(p.version, out val)); }) .OrderByDescending(p => Int32.Parse(p.version)) .ToArray(); foreach (var basename in allFiles.Select(p => p.basename).Distinct()) { var latest = allFiles.Where(p => p.basename == basename).FirstOrDefault(); if (latest != null) { string latestFilename = latest.basename + "." + latest.version; // Need to limit this down to just the filename in question // The XML file changes the name to all caps, so compare apples to apples if (latestFilename.ToUpperInvariant().StartsWith(Path.GetFileName(res_path).ToUpperInvariant())) { string destpathandname = Path.Combine(finalPathName, latestFilename); if (!importedCADFiles.Contains(Path.Combine("CAD", Path.GetFileName(destpathandname)))) { importedCADFiles.Add(Path.Combine("CAD", Path.GetFileName(destpathandname))); } var sourcepathandname = Path.Combine(Path.GetDirectoryName(res_path), latestFilename); if (Path.GetFullPath(sourcepathandname) != Path.GetFullPath(destpathandname)) { File.Copy(sourcepathandname, destpathandname, true); } break; } } } } } } } catch (Exception err_create_proj) { this.Logger.WriteError("Error creating AVM project: " + err_create_proj.Message, " - Extraction Failed. Possible ComponentManagement issue."); cleanup(tempXMLfile, true); return; } } #endregion // - Create Resource objects in the CyPhy Component model that point to these Creo Model files // - Note: The "paths" of these should be the relative path from that component's root folder if (extractor_ran_success) { foreach (var cadFile in importedCADFiles) { CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create((CyPhy.Component)GetCurrentDesignElement()); ResourceObj.Attributes.ID = Guid.NewGuid().ToString("B"); ResourceObj.Attributes.Path = AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFile); ResourceObj.Attributes.Notes = "CAD Model Import tool added this resource object for the imported CAD file"; ResourceObj.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFile)); // layout Resource just to the side of the CAD model foreach (MgaPart item in (ResourceObj.Impl as MgaFCO).Parts) { item.SetGmeAttrs(null, RESOURCE_START_X, greatest_current_y + RESOURCE_START_Y); } // The "primary" CAD model is the first one -- associate it with the CyPhy CADModel object if (importedCADFiles.IndexOf(cadFile) == 0) { // - Create a UsesResource association between the CyPhy CADModel object and the Resource object that represents the top-level Creo Model file. CyPhyClasses.UsesResource.Connect(ResourceObj, ProcessedCADModel, null, null, (CyPhy.Component)GetCurrentDesignElement()); } } } // throw in an ACM file for the current state of the component. if (extractor_ran_success && !test_copy_and_path_only) { var exporter = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter(); String acmPath = Path.Combine(PathforComp, GetCurrentDesignElement().Name + ".component.acm"); CyPhyComponentExporterInterpreter.ExportToDirectory((CyPhy.Component)GetCurrentDesignElement(), Path.GetDirectoryName(acmPath)); } // Clean up cleanup(tempXMLfile, (extractor_ran_success && !test_copy_and_path_only)); } }
private static void ImportAndTestCADMetric(String cadMetricName, Double expectedVal, String testModelName) { var testPath = Path.Combine(META.VersionInfo.MetaPath, "test", "InterchangeTest", "ComponentInterchangeTest", "ImportTestModels", "CADMetric"); var testModel = Path.Combine(testPath, testModelName); var testACM = Path.Combine(testPath, "InputModel.acm"); GME.MGA.MgaProject proj = new GME.MGA.MgaProjectClass(); String connString = "MGA=" + testModel; proj.Create(connString, "CyPhyML"); proj.PerformInTransaction(delegate { var rf = CyPhyClasses.RootFolder.GetRootFolder(proj); var cf = CyPhyClasses.Components.Create(rf); cf.Name = "Components"; avm.Component acm = null; using (var reader = new StreamReader(testACM)) { acm = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(reader); } var comp = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cf, acm); var cm_param = comp.Children .CADModelCollection .FirstOrDefault() .Children .CADMetricCollection .Where(cm => cm.Name == cadMetricName) .FirstOrDefault(); Assert.True(cm_param != null, String.Format("Could not find CAD Metric: {0}", cadMetricName)); Assert.False(String.IsNullOrWhiteSpace(cm_param.Attributes.Value), String.Format("CAD Metric \"{0}\" has a null or whitespace value", cadMetricName)); var cm_paramVal = Double.Parse(cm_param.Attributes.Value); Assert.True(cm_paramVal == expectedVal, String.Format("CAD Metric \"{0}\" has wrong value ({1} expected, {2} found)", cadMetricName, expectedVal, cm_param.Attributes.Value)); var dstProp = cm_param.DstConnections .CADMetricPortMapCollection .FirstOrDefault() .DstEnds .Property; var dstPropVal = Double.Parse(dstProp.Attributes.Value); Assert.True(dstPropVal == cm_paramVal, "CADMetric value didn't propagate."); }); proj.Save(); proj.Close(); }
public void ImportCyberModel(string Cyberpath = null) { string CyberFilename = ""; this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name); // - Display a dialog box to let the user choose their Cyber model file bool Cyber_file_chosen = false; //bool test_copy_and_path_only = false; if (string.IsNullOrWhiteSpace(Cyberpath)) { Cyber_file_chosen = get_Cyber_file(out CyberFilename); } else { //test_copy_and_path_only = true; CyberFilename = Cyberpath; if (File.Exists(CyberFilename)) { Cyber_file_chosen = true; } else { this.Logger.WriteError("Invalid Cyber file path passed in: " + Cyberpath); } } // - Run the extractor on the Creo model file #region Run the Extractor List <string> componentList = new List <string>(); IMgaProject project = (IMgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); string compName; project.OpenEx("MGA=" + CyberFilename, "CyberComposition", null); try { project.BeginTransactionInNewTerr(); IMgaFCO currentObj; try { IMgaFolder currentFolder = (IMgaFolder)project.RootFolder; IMgaFolders cFolders = currentFolder.ChildFolders; foreach (IMgaFolder f in cFolders) { if (f.MetaFolder.Name == "Components") { IMgaFCOs objects = f.ChildFCOs; foreach (IMgaFCO o in objects) { componentList.Add("/" + f.Name + "/" + o.Name); } } } } finally { project.CommitTransaction(); } // Adapted from ModelicaImporter.cs string result = ""; using (CyberComponentPicker cyberpicker = new CyberComponentPicker(componentList)) { var dialogResult = cyberpicker.ShowDialog(); if (dialogResult != System.Windows.Forms.DialogResult.OK) { this.Logger.WriteInfo("Modelica import was cancelled by the user."); return; } result = cyberpicker.compResult; } var halves = result.Split('/'); compName = halves[1]; project.BeginTransactionInNewTerr(); try { currentObj = (IMgaFCO)project.RootFolder.ObjectByPath[result]; } finally { project.CommitTransaction(); } IMgaComponentEx comp = (IMgaComponentEx)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Interpreter.CyberComponentExporter")); comp.Initialize((MgaProject)project); comp.InvokeEx((MgaProject)project, (MgaFCO)currentObj, null, 128); project.Save(); } finally { project.Close(true); } #endregion // - Use a function from CyPhy2ComponentModel to convert the extractor's XML format into a CyPhy model fragment #region Convert_to_XML // used in creating the resource object below CyPhy.CyberModel ProcessedCyberModel = null; if (true) { this.Logger.WriteDebug("About to call DeserializeAvmComponentXml..."); StreamReader streamReader = new StreamReader(compName + ".component.acm"); avm.Component ac_import = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(streamReader); streamReader.Close(); this.Logger.WriteDebug("... finished DeserializeAvmComponentXml call."); foreach (avm.cyber.CyberModel Cybermodel in ac_import.DomainModel.Where(dm => dm is avm.cyber.CyberModel) .Cast <avm.cyber.CyberModel>()) { var rf = CyPhyClasses.RootFolder.GetRootFolder(CurrentProj); Dictionary <string, CyPhy.Component> avmidComponentMap = new Dictionary <string, CyPhy.Component>(); AVM2CyPhyML.CyPhyMLComponentBuilder newComponent = new AVM2CyPhyML.CyPhyMLComponentBuilder(rf); ProcessedCyberModel = newComponent.process(Cybermodel, GetCurrentComp()); ProcessedCyberModel.Name = Path.GetFileNameWithoutExtension(CyberFilename); } // find the largest current Y value so our new elements are added below the existing design elements foreach (var child in GetCurrentComp().AllChildren) { foreach (MgaPart item in (child.Impl as MgaFCO).Parts) { int read_x, read_y; string read_str; item.GetGmeAttrs(out read_str, out read_x, out read_y); greatest_current_y = (read_y > greatest_current_y) ? read_y : greatest_current_y; } } // layout Cyber model to the "south" of existing elements foreach (MgaPart item in (ProcessedCyberModel.Impl as MgaFCO).Parts) { item.SetGmeAttrs(null, Cyber_MODEL_START_X, greatest_current_y + Cyber_MODEL_START_Y); } // Extend it's properties out to the component level. this.CyberModuleImportExtension(ProcessedCyberModel); } #endregion // - Copy the Cyber Model files into the component's backend folder // - Note: The solution includes a function that can find this folder using the project.manifest.json file. // - For nice organization, create them in a subfolder called "Cyber" // create avmproj #region Copy files to backend folder // used in creating the resource object below string PathforComp = null; var importedCyberFiles = new List <String>(); if (true) { try { // create the destination path PathforComp = GetCurrentComp().GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE); string finalPathName = Path.Combine(PathforComp, "Cyber"); Directory.CreateDirectory(finalPathName); // determine if one part file or all part and assembly files need to be copied string cpsrcfile = System.IO.Path.GetFileName(CyberFilename); // copy the selected file string CyberFileCopyPath = System.IO.Path.Combine(finalPathName, cpsrcfile); System.IO.File.Copy(CyberFilename, CyberFileCopyPath, true); // Set "primary" file as the first in the list. importedCyberFiles.Add(Path.Combine("Cyber", Path.GetFileName(CyberFileCopyPath))); if (true) { // get a string of the XML contents this.Logger.WriteDebug("About to read contents of XML file using class XmlDocument: " + compName + ".component.acm"); XmlDocument doc = new XmlDocument(); doc.Load(compName + ".component.acm"); string xmlcontents = doc.InnerXml; // mine down to the Resource dependencies using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents))) { // iterate through each file listed in the resourcedependency section while (reader.ReadToFollowing("ResourceDependency") == true) { string res_name = reader.GetAttribute("Name"); string res_path = reader.GetAttribute("Path"); this.Logger.WriteDebug("Copying this file: " + res_path + "\\" + res_name); // Cyber files end in .1 .2 etc. Pick the latest ones var allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*mga." /*n.b. literal dot*/ + "*") .Select(Path.GetFileName) .Select(filename => new { basename = filename.Substring(0, filename.LastIndexOf('.')), version = filename.Substring(filename.LastIndexOf('.') + 1) }) .Where(p => { int val; return(Int32.TryParse(p.version, out val)); }) .OrderByDescending(p => Int32.Parse(p.version)) .ToArray(); foreach (var basename in allFiles.Select(p => p.basename).Distinct()) { var latest = allFiles.Where(p => p.basename == basename).FirstOrDefault(); if (latest != null) { string latestFilename = latest.basename + "." + latest.version; // Need to limit this down to just the filename in question // The XML file changes the name to all caps, so compare apples to apples if (latestFilename.ToUpper().StartsWith(res_name.ToUpper())) { string destpathandname = Path.Combine(finalPathName, latestFilename); if (!importedCyberFiles.Contains(Path.Combine("Cyber", Path.GetFileName(destpathandname)))) { importedCyberFiles.Add(Path.Combine("Cyber", Path.GetFileName(destpathandname))); } File.Copy(Path.Combine(Path.GetDirectoryName(res_path), latestFilename), destpathandname, true); break; } } } } } } } catch (Exception err_create_proj) { this.Logger.WriteError("Error creating AVM project: " + err_create_proj.Message, " - Extraction Failed. Possible ComponentManagement issue."); //cleanup(tempXMLfile, true); return; } } #endregion // - Create Resource objects in the CyPhy Component model that point to these Cyber Model files // - Note: The "paths" of these should be the relative path from that component's root folder if (true) { foreach (var CyberFile in importedCyberFiles) { CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create(GetCurrentComp()); ResourceObj.Attributes.ID = Guid.NewGuid().ToString("B"); ResourceObj.Attributes.Path = CyberFile; ResourceObj.Attributes.Notes = "Cyber Model Import tool added this resource object for the imported Cyber file"; ResourceObj.Name = Path.GetFileName(CyberFile); // layout Resource just to the side of the Cyber model foreach (MgaPart item in (ResourceObj.Impl as MgaFCO).Parts) { item.SetGmeAttrs(null, RESOURCE_START_X, greatest_current_y + RESOURCE_START_Y); } // The "primary" Cyber model is the first one -- associate it with the CyPhy CyberModel object if (importedCyberFiles.IndexOf(CyberFile) == 0) { // - Create a UsesResource association between the CyPhy CyberModel object and the Resource object that represents the top-level Creo Model file. CyPhyClasses.UsesResource.Connect(ResourceObj, ProcessedCyberModel, null, null, GetCurrentComp()); } } } // throw in an ACM file for the current state of the component. if (true) { var exporter = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter(); String acmPath = Path.Combine(PathforComp, GetCurrentComp().Name + ".component.acm"); CyPhyComponentExporterInterpreter.ExportToFile(GetCurrentComp(), Path.GetDirectoryName(acmPath)); } // Clean up //cleanup(tempXMLfile, true); }
public void Export() { avm.Component comp = null; proj.PerformInTransaction(delegate { var cyphyComp = proj.GetComponentsByName("Excavator_controller").First(); comp = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(cyphyComp); }); String testName = GetCurrentMethod(); CyPhyComponentExporter.CyPhyComponentExporterInterpreter .SerializeAvmComponent(comp, Path.Combine(fixture.testPath, testName + ".acm")); #region check basics Assert.NotNull(comp); Assert.Equal(2, comp.Connector.Count); Assert.Equal(2, comp.Port.Count); Assert.Equal(1, comp.DomainModel.Count); #endregion #region fetch objects var cyberModel = comp.DomainModel.OfType <avm.cyber.CyberModel>().FirstOrDefault(); Assert.NotNull(cyberModel); Assert.Equal(2, cyberModel.Connector.Count); var ActualBoom_Connector = comp.Connector.FirstOrDefault(c => c.Name.Equals("ActualBoom_Connector")); Assert.NotNull(ActualBoom_Connector); var connector_ActualBoom_Connector = ActualBoom_Connector.Role.OfType <avm.modelica.Connector>().First(); Assert.NotNull(connector_ActualBoom_Connector); var ActualBoom_Port = comp.Port.OfType <avm.modelica.Connector>().FirstOrDefault(mc => mc.Name.Equals("ActualBoom_Port")); Assert.NotNull(ActualBoom_Port); var boomValve_Connector = comp.Connector.FirstOrDefault(c => c.Name.Equals("boomValve_Connector")); Assert.NotNull(boomValve_Connector); var connector_boomValve_Connector = boomValve_Connector.Role.OfType <avm.modelica.Connector>().First(); Assert.NotNull(connector_boomValve_Connector); var boomValve_Port = comp.Port.OfType <avm.modelica.Connector>().FirstOrDefault(mc => mc.Name.Equals("boomValve_Port")); Assert.NotNull(boomValve_Port); var sample_Period = comp.Property.OfType <avm.PrimitiveProperty>().FirstOrDefault(p => p.Name.Equals("sample_Period")); Assert.NotNull(sample_Period); var ActualBoom_1 = cyberModel.Connector.FirstOrDefault(mc => mc.Name.Equals("ActualBoom_1")); Assert.NotNull(ActualBoom_1); var boomValve_1 = cyberModel.Connector.FirstOrDefault(mc => mc.Name.Equals("boomValve_1")); Assert.NotNull(boomValve_1); var SamplePeriod = cyberModel.Parameter.FirstOrDefault(p => p.Locator.Equals("SamplePeriod")); Assert.NotNull(SamplePeriod); #endregion AssertConnection(ActualBoom_1, ActualBoom_Port); AssertConnection(ActualBoom_1, connector_ActualBoom_Connector); AssertConnection(boomValve_1, boomValve_Port); AssertConnection(boomValve_1, connector_boomValve_Connector); Assert.IsType <avm.DerivedValue>(SamplePeriod.Value.ValueExpression); var vex = SamplePeriod.Value.ValueExpression as avm.DerivedValue; Assert.Equal(sample_Period.Value.ID, vex.ValueSource); #region check cyber model attributes Assert.Equal("RootFolder.Components.excavator_control", cyberModel.Locator); Assert.Equal("Simulink.excavator_control_type", cyberModel.Class); Assert.Equal("author", cyberModel.Author); Assert.Equal("notes", cyberModel.Notes); Assert.Equal(avm.cyber.ModelType.Simulink, cyberModel.Type); #endregion }
public static CyPhyML.Component AVMComponent2CyPhyML(CyPhyML.Components cyPhyMLComponentParent, avm.Component avmComponent, bool resetUnitLib = true, object messageConsole = null) { CyPhyML.Component c_rtn = AVM2CyPhyML.CyPhyMLComponentBuilder.AVM2CyPhyML(cyPhyMLComponentParent, avmComponent, resetUnitLib, messageConsole); // CyPhyComponentAutoLayout.LayoutComponent(c_rtn); return(c_rtn); }
public void ExportComponentAsZip() { var path_ZipExpected = Path.Combine(ExportZipFixture.path_Test, "Spring_Tungsten.expected.zip"); var path_ZipGenerated = Path.Combine(ExportZipFixture.path_Test, "Spring_Tungsten.zip"); if (File.Exists(path_ZipGenerated)) { File.Delete(path_ZipGenerated); } Assert.False(File.Exists(path_ZipGenerated), String.Format("{0} couldn't be deleted; Test won't be valid unless it can be newly created by the test.", path_ZipGenerated)); // Export ZIP package fixture.proj.PerformInTransaction(delegate { CyPhy.Component comp = fixture.proj.GetComponentsByName("Spring_Tungsten").First(); CyPhyComponentExporter.CyPhyComponentExporterInterpreter.ExportComponentPackage(comp, ExportZipFixture.path_Test); }); Assert.True(File.Exists(path_ZipGenerated), String.Format("{0} couldn't be found; Export may have failed.", path_ZipGenerated)); avm.Component component = null; // Check that ZIP matches expected. // Assemble a list of files that didn't match. List <String> missing = new List <String>(); using (ZipFile zip_Expected = ZipFile.Read(path_ZipExpected)) { using (ZipFile zip_Generated = ZipFile.Read(path_ZipGenerated)) { foreach (var entry in zip_Expected) { var generatedFile = zip_Generated.Where(e => e.FileName == entry.FileName); // If no entry with matching FileName, add it to the mising list. if (false == generatedFile.Any()) { missing.Add(entry.FileName); } else { if (generatedFile.FirstOrDefault().FileName == "Spring_Tungsten.acm") { MemoryStream stream = new MemoryStream(); generatedFile.FirstOrDefault().Extract(stream); component = OpenMETA.Interchange.AvmXmlSerializer.Deserialize <avm.Component>(Encoding.UTF8.GetString(stream.ToArray())); } } } } } if (missing.Any()) { String msg = String.Format("{0} was missing these expected files: ", path_ZipGenerated); foreach (var filename in missing) { msg += filename + " "; } Assert.True(false, msg); } Assert.NotNull(component); var path = component.ResourceDependency.Where(x => x.Name == "TUNGSTEN_SPRING.PRT").FirstOrDefault().Path; Assert.Equal("CAD\\TUNGSTEN_SPRING.PRT.3", path); }