public void BrandNewComponent() { // Create a branch new component and submit the transaction. // This should trigger the add-on. // Next, go and check that the Component has a Path, and that that Path exists on disk. var project = fixture.GetProject(); project.EnableAutoAddOns(true); project.PerformInTransaction(delegate { CyPhy.RootFolder rf = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject); CyPhy.Components cf = rf.Children.ComponentsCollection.First(); CyPhy.Component comp = CyPhyClasses.Component.Create(cf); comp.Name = "BrandNewComponent"; }); project.PerformInTransaction(delegate { var matchingComponents = project.GetComponentsByName("BrandNewComponent"); Assert.Equal(1, matchingComponents.Count()); var comp_Retrieved = matchingComponents.First(); Assert.True(!String.IsNullOrWhiteSpace(comp_Retrieved.Attributes.AVMID), "Retrieved component is missing AVMID."); Assert.True(!String.IsNullOrWhiteSpace(comp_Retrieved.Attributes.Path), "Retrieved component is missing Path."); Assert.True(Directory.Exists(comp_Retrieved.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE)), "Component path doesn't exist."); }); project.Save(); }
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 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); }); }
public void TestAddCustomIconTool() { string TestName = System.Reflection.MethodBase.GetCurrentMethod().Name; string path_Test = Path.Combine(testcreatepath, TestName); string path_Mga = Path.Combine(path_Test, TestName + ".mga"); // delete any previous test results if (Directory.Exists(path_Test)) { Directory.Delete(path_Test, true); } // create a new blank project MgaProject proj = new MgaProject(); proj.Create("MGA=" + path_Mga, "CyPhyML"); // these are the actual steps of the test proj.PerformInTransaction(delegate { // create the environment for the Component authoring class CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components components = CyPhyClasses.Components.Create(rf); CyPhy.Component testcomp = CyPhyClasses.Component.Create(components); // new instance of the class to test CyPhyComponentAuthoring.Modules.CustomIconAdd CATModule = new CyPhyComponentAuthoring.Modules.CustomIconAdd(); //// these class variables need to be set to avoid NULL references CATModule.SetCurrentDesignElement(testcomp); CATModule.CurrentObj = testcomp.Impl as MgaFCO; // call the primary function directly CATModule.AddCustomIcon(testiconpath); // verify results // 1. insure the icon file was copied to the back-end folder correctly string iconAbsolutePath = Path.Combine(testcomp.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE), "Icon.png"); Assert.True(File.Exists(iconAbsolutePath), String.Format("Could not find the source file for the created resource, got {0}", iconAbsolutePath)); // 2. insure the resource path was created correctly var iconResource = testcomp.Children.ResourceCollection.Where(p => p.Name == "Icon.png").First(); Assert.True(iconResource.Attributes.Path == "Icon.png", String.Format("{0} Resource should have had value {1}; instead found {2}", iconResource.Name, "Icon.png", iconResource.Attributes.Path) ); // 3. Verify the registry entry exists string expected_registry_entry = Path.Combine(testcomp.GetDirectoryPath(ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT), "Icon.png"); string registry_entry = (testcomp.Impl as GME.MGA.IMgaFCO).get_RegistryValue("icon"); Assert.True(registry_entry.Equals(expected_registry_entry), String.Format("Registry should have had value {0}; instead found {1}", expected_registry_entry, registry_entry) ); }); proj.Save(); proj.Close(); Directory.Delete(testcreatepath, true); }
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 TestAddMfgModelTool() { string TestName = System.Reflection.MethodBase.GetCurrentMethod().Name; string path_Test = Path.Combine(testcreatepath, TestName); string path_Mga = Path.Combine(path_Test, TestName + ".mga"); // delete any previous test results if (Directory.Exists(path_Test)) { Directory.Delete(path_Test, true); } // create a new blank project MgaProject proj = new MgaProject(); proj.Create("MGA=" + path_Mga, "CyPhyML"); // these are the actual steps of the test proj.PerformInTransaction(delegate { // create the environment for the Component authoring class CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components components = CyPhyClasses.Components.Create(rf); CyPhy.Component testcomp = CyPhyClasses.Component.Create(components); // new instance of the class to test CyPhyComponentAuthoring.Modules.MfgModelImport CATModule = new CyPhyComponentAuthoring.Modules.MfgModelImport(); //// these class variables need to be set to avoid NULL references CATModule.SetCurrentDesignElement(testcomp); CATModule.CurrentObj = testcomp.Impl as MgaFCO; // call the primary function directly CATModule.import_manufacturing_model(testmfgmdlpath); // verify results // 1. insure the mfg file was copied to the backend folder correctly // insure the part file was copied to the backend folder correctly var getmfgmdl = testcomp.Children.ManufacturingModelCollection.First(); string returnedpath; getmfgmdl.TryGetResourcePath(out returnedpath, ComponentLibraryManager.PathConvention.ABSOLUTE); string demanglepathpath = returnedpath.Replace("\\", "/"); Assert.True(File.Exists(demanglepathpath), String.Format("Could not find the source file for the created resource, got {0}", demanglepathpath)); // 2. insure the resource path was created correctly var mfgResource = testcomp.Children.ResourceCollection.Where(p => p.Name == "generic_cots_mfg.xml").First(); Assert.True(mfgResource.Attributes.Path == Path.Combine("Manufacturing", "generic_cots_mfg.xml"), String.Format("{0} Resource should have had value {1}; instead found {2}", mfgResource.Name, "generic_cots_mfg.xml", mfgResource.Attributes.Path) ); }); proj.Save(); proj.Close(); }
public void OutsideCopy_SameProjDir_MissingAVMID() { // Simulate copying a component from another MGA in the same project folder. // It will have a Path unique to this project, and the path will already exist. // However, it will be missing an AVMID. // WHAT DO WE EXPECT THE ADDON TO DO? // We expect it to assign a new AVMID, but change nothing else. var compName = Utils.GetCurrentMethod(); // First, let's create such a path. var path_ToCopy = Path.Combine(fixture.path_Test, "components", "z672jsd8"); var path_NewCopy = Path.Combine(fixture.path_Test, "components", compName); Utils.DirectoryCopy(path_ToCopy, path_NewCopy); // Now let's simulate copying a component from another project. // It should have a Path, AVMID, and a Resource. String org_AVMID = ""; String org_Path = ""; var project = fixture.GetProject(); project.EnableAutoAddOns(true); project.PerformInTransaction(delegate { CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project); CyPhy.Components cf = rf.Children.ComponentsCollection.First(); CyPhy.Component c = CyPhyClasses.Component.Create(cf); c.Name = compName; c.Attributes.AVMID = org_AVMID; org_Path = c.Attributes.Path = Path.Combine("components", compName); CyPhy.Resource res = CyPhyClasses.Resource.Create(c); res.Attributes.Path = "generic_cots_mfg.xml"; res.Name = res.Attributes.Path; }); project.PerformInTransaction(delegate { var c = project.GetComponentsByName(compName).FirstOrDefault(); Assert.True(org_AVMID != c.Attributes.AVMID, "A new AVMID should have been assigned."); Assert.True(org_Path == c.Attributes.Path, "The path should not have been changed."); }); project.Save(); }
public void OutsideCopy_SameProjDir() { // Create a new component. // Its AVMID and Path will be unique to this project, and that path will exist already on disk. // We expect that the Add-on isn't going to change anything. var compName = Utils.GetCurrentMethod(); // First, let's create such a path. var path_ToCopy = Path.Combine(fixture.path_Test, "components", "z672jsd8"); var path_NewCopy = Path.Combine(fixture.path_Test, "components", compName); Utils.DirectoryCopy(path_ToCopy, path_NewCopy); // Now let's simulate copying a component from another project. // It should have a Path, AVMID, and a Resource. String org_AVMID = ""; String org_Path = ""; var project = fixture.GetProject(); project.EnableAutoAddOns(true); Assert.Contains("MGA.Addon.ComponentLibraryManagerAddOn", project.AddOnComponents.Cast <IMgaComponentEx>().Select(x => x.ComponentProgID)); project.PerformInTransaction(delegate { CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project); CyPhy.Components cf = rf.Children.ComponentsCollection.First(); CyPhy.Component c = CyPhyClasses.Component.Create(cf); c.Name = compName; org_AVMID = c.Attributes.AVMID = Guid.NewGuid().ToString("D"); org_Path = c.Attributes.Path = Path.Combine("components", compName); CyPhy.Resource res = CyPhyClasses.Resource.Create(c); res.Attributes.Path = "generic_cots_mfg.xml"; res.Name = res.Attributes.Path; }); project.PerformInTransaction(delegate { var c = project.GetComponentsByName(compName).FirstOrDefault(); Assert.True(org_AVMID == c.Attributes.AVMID, "AVMID was changed."); Assert.True(org_Path == c.Attributes.Path, "Path was changed."); }); project.Save(); }
public void TestCADImportResourceNaming() { string TestName = System.Reflection.MethodBase.GetCurrentMethod().Name; string path_Test = Path.Combine(testcreatepath, TestName); string path_Mga = Path.Combine(path_Test, TestName + ".mga"); // delete any previous test results if (Directory.Exists(path_Test)) { Directory.Delete(path_Test, true); } // create a new blank project MgaProject proj = new MgaProject(); proj.Create("MGA=" + path_Mga, "CyPhyML"); // these are the actual steps of the test proj.PerformInTransaction(delegate { // create the environment for the Component authoring class CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components components = CyPhyClasses.Components.Create(rf); CyPhy.Component testcomp = CyPhyClasses.Component.Create(components); // new instance of the class to test CyPhyComponentAuthoring.Modules.CADModelImport testcam = new CyPhyComponentAuthoring.Modules.CADModelImport(); // these class variables need to be set to avoid NULL references testcam.SetCurrentDesignElement(testcomp); testcam.CurrentObj = testcomp.Impl as MgaFCO; // call the module with a part file to skip the CREO steps testcam.ImportCADModel(testpartpath); // verify results // insure the resource path was created correctly var correct_name = testcomp.Children.ResourceCollection.Where(p => p.Name == "damper.prt").First(); Assert.True(correct_name.Attributes.Path == "CAD\\damper.prt", String.Format("{0} should have had value {1}; instead found {2}", correct_name.Name, "CAD\\damper.prt", correct_name.Attributes.Path) ); // insure the part file was copied to the back-end folder correctly var getcadmdl = testcomp.Children.CADModelCollection.First(); string returnedpath; getcadmdl.TryGetResourcePath(out returnedpath, ComponentLibraryManager.PathConvention.ABSOLUTE); Assert.True(File.Exists(returnedpath + ".36"), String.Format("Could not find the source file for the created resource, got {0}", returnedpath)); }); proj.Save(); proj.Close(); }
public void OutsideCopy_DifferentProjDir_AVMIDCollision() { // Create a new component. // Its AVMID will NOT be unique to this project, and thus a new (unique) AVMID must be assigned. // Its Path will be unique to this project, and that path will NOT exist already on disk, // because we expect in this case that the component was copied from another project somewhere else. // WHAT DO WE EXPECT THE ADD-ON TO DO? // 1. Assign a new AVMID. // 2. Because the folder does not exist on disk, a new path and backing folder will be created for this guy. var compName = Utils.GetCurrentMethod(); // First, let's create a fake path. var path_NewCopy = Path.Combine(fixture.path_Test, "components", compName); // Now let's simulate copying a component from another project. // It should have a Path, AVMID, and a Resource. String org_AVMID = ""; String org_Path = ""; var project = fixture.GetProject(); project.EnableAutoAddOns(true); project.PerformInTransaction(delegate { CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project); CyPhy.Components cf = rf.Children.ComponentsCollection.First(); CyPhy.Component c = CyPhyClasses.Component.Create(cf); c.Name = compName; org_AVMID = c.Attributes.AVMID = "101b"; // This AVMID should collide org_Path = c.Attributes.Path = Path.Combine("components", compName); CyPhy.Resource res = CyPhyClasses.Resource.Create(c); res.Attributes.Path = "generic_cots_mfg.xml"; res.Name = res.Attributes.Path; }); project.PerformInTransaction(delegate { var c = project.GetComponentsByName(compName).FirstOrDefault(); Assert.True(org_AVMID != c.Attributes.AVMID, "A new AVMID should have been assigned."); Assert.True(org_Path != c.Attributes.Path, "Component should have been assigned a new path."); Assert.True(Directory.Exists(c.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE)), "New component folder doesn't exist on disk."); }); project.Save(); }
List <CyPhy.Component> GetAllComponents(CyPhy.Components componentsFolder) { List <CyPhy.Component> componentList = new List <CyPhy.Component>(); foreach (CyPhy.Components childComponentsFolder in componentsFolder.Children.ComponentsCollection) { componentList.AddRange(GetAllComponents(childComponentsFolder)); } foreach (CyPhy.Component childComponent in componentsFolder.Children.ComponentCollection) { componentList.Add(childComponent); } return(componentList); }
public static HashSet <CyPhyML.Component> getCyPhyMLComponentSet(CyPhyML.Components cyPhyMLComponents) { HashSet <CyPhyML.Component> cyPhyMLComponentSet = new HashSet <CyPhyML.Component>(); foreach (CyPhyML.Components childComponentsFolder in cyPhyMLComponents.Children.ComponentsCollection) { cyPhyMLComponentSet.UnionWith(getCyPhyMLComponentSet(childComponentsFolder)); } foreach (CyPhyML.Component childComponent in cyPhyMLComponents.Children.ComponentCollection) { cyPhyMLComponentSet.Add(childComponent); } return(cyPhyMLComponentSet); }
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()); }); }
private CyPhy.Components GetImportFolder(CyPhy.RootFolder rf) { CyPhy.Components rtn = null; foreach (CyPhy.Components c in rf.Children.ComponentsCollection) { if (c.Name == ImportedComponentsFolderName) { rtn = c; break; } } if (rtn == null) { rtn = CyPhyClasses.Components.Create(rf); rtn.Name = ImportedComponentsFolderName; } return(rtn); }
private static CyPhy.Components DetermineAndEnsureFolderForComponent(CyPhy.RootFolder rootFolder, avm.Component ac_import) { // Get or create a root Components folder. Components will go in here, unless they have a classification. CyPhy.Components cyPhyMLComponentsFolder = rootFolder.Children.ComponentsCollection .FirstOrDefault(cf => cf.Name.Equals(ImportedComponentsFolderName)); if (cyPhyMLComponentsFolder == null) { cyPhyMLComponentsFolder = CyPhyClasses.Components.Create(rootFolder); cyPhyMLComponentsFolder.Name = ImportedComponentsFolderName; } // Check for classifications. If the component has 1 or more classifications, then // the first one will be used to find/build a corresponding folder structure for this component. if (ac_import.Classifications.Count > 0 && !String.IsNullOrWhiteSpace(ac_import.Classifications.FirstOrDefault())) { var firstClass = ac_import.Classifications.FirstOrDefault(); // Create an iterator and initialize it on the root Components folder. CyPhy.Components folIter = cyPhyMLComponentsFolder; foreach (var folName in firstClass.Split('.')) { // Find a child folder with this name var tmp = folIter.Children.ComponentsCollection .FirstOrDefault(cf => cf.Name.Equals(folName)); // If no folder by that name, create one. if (tmp == null) { tmp = CyPhyClasses.Components.Create(folIter); tmp.Name = folName; } // Set this folder as the current, and move to the next category. folIter = tmp; } cyPhyMLComponentsFolder = folIter; } return(cyPhyMLComponentsFolder); }
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 static bool FolderHasModelicaComponents(CyPhy.Components folder) { foreach (var component in folder.Children.ComponentCollection) { if ((component.Impl as GME.MGA.IMgaModel).GetChildrenOfKind(typeof(CyPhy.ModelicaModel).Name).Count + (component.Impl as GME.MGA.IMgaModel).GetChildrenOfKind(typeof(CyPhy.CyberModel).Name).Count > 0) { return(true); } } bool subFolderHasModelicaComponents = false; foreach (var subFolder in folder.Children.ComponentsCollection) { if (FolderHasModelicaComponents(subFolder)) { subFolderHasModelicaComponents = true; break; } } return(subFolderHasModelicaComponents); }
public void CopyHasInvalidPath() { // Create a new component. // We'll make it look like a copy, but the source (inside/outside) is not important. // That's because we'll give it a path that is invalid. // WHAT DO WE EXPECT THE ADD-ON TO DO? // Warn the user, and create a new folder. // These characters are not valid in Windows paths List <String> invalidCharacters = new List <String>() { "?", "<", ">", "\\", ":", "*", "|", " " }; // Tuple structure: Component Name | Path Changed | Path Exists List <Tuple <String, Boolean, Boolean> > results = new List <Tuple <String, Boolean, Boolean> >(); foreach (var invalidChar in invalidCharacters) { String org_Path = String.Format("components\\invalid{0}", invalidChar); var compName = String.Format("{0}{1}", Utils.GetCurrentMethod(), invalidChar); string objID = ""; var project = fixture.GetProject(); project.EnableAutoAddOns(true); project.PerformInTransaction(delegate { CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project); CyPhy.Components cf = rf.Children.ComponentsCollection.First(); CyPhy.Component c = CyPhyClasses.Component.Create(cf); c.Name = compName; c.Attributes.Path = org_Path; objID = c.ID; CyPhy.Resource res = CyPhyClasses.Resource.Create(c); res.Attributes.Path = "generic_cots_mfg.xml"; res.Name = res.Attributes.Path; }); // Perform tests, but queue them for batch display later. project.PerformInTransaction(delegate { //var c = project.GetComponentsByName(compName).FirstOrDefault(); var c = CyPhyClasses.Component.Cast(project.GetObjectByID(objID)); results.Add(new Tuple <string, bool, bool>( c.Name, org_Path != c.Attributes.Path, Directory.Exists(c.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE)) )); }); } // Did anybody not get a new path? var item2Failures = results.Where(r => r.Item2 == false); if (item2Failures.Any()) { String message = "Components were not assigned a new path: "; foreach (var result in item2Failures) { message += " " + result.Item1; } // Force assert failure Assert.False(true, message); } // Did anybody's path not exist? var item3Failures = results.Where(r => r.Item3 == false); if (item3Failures.Any()) { String message = "New component folders do not exist on disk for: "; foreach (var result in item3Failures) { message += " " + result.Item1; } // Force assert failure Assert.False(true, message); } }
public IMgaFCOs ImportFiles(MgaProject project, string projRootPath, string[] FileNames, bool alwaysReplace = false, bool doNotReplaceAll = false) { Boolean b_CLMAddOnStatus = META.ComponentLibraryManagerAddOn.GetEnabled(project); META.ComponentLibraryManagerAddOn.Enable(false, project); var addons = project.AddOnComponents.Cast <IMgaComponentEx>(); foreach (var addon in addons) { if (addon.ComponentName.ToLowerInvariant() == "CyPhyAddOn".ToLowerInvariant()) { addon.ComponentParameter["DontAssignGuidsOnNextTransaction".ToLowerInvariant()] = true; } } IMgaFCOs importedComponents = (IMgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); try { bool replaceAll = alwaysReplace; CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject); Dictionary <string, CyPhy.Component> avmidComponentMap = getCyPhyMLComponentDictionary_ByAVMID(rootFolder); Dictionary <string, CyPhy.Component> nameComponentMap = getCyPhyMLComponentDictionary_ByName(rootFolder); Boolean b_FirstComponent = true; foreach (String inputFile in FileNames) { var inputFilePath = inputFile; /* Disable validation for now #region Check validation rules * * var errorMessages = new List<string>(); * ComponentImportRules.CheckUniqueNames(inputXMLFile, ref errorMessages); * var isValid = ComponentImportRules.ValidateXsd(inputXMLFile, ref errorMessages); * * foreach (var errorMessage in errorMessages) * { * GMEConsole.Error.WriteLine(errorMessage); * } * * if (!isValid) * { * GMEConsole.Info.WriteLine("XML is not valid. Skip file: {0}", inputXMLFile); * continue; * } #endregion */ GMEConsole.Info.WriteLine("Importing {0}", inputFilePath); // If ZIP file, unzip it to a temporary directory, then import as usual UnzipToTemp unzip = null; bool bZipArchive = (Path.GetExtension(inputFilePath) == ".zip"); if (bZipArchive) { unzip = new UnzipToTemp(GMEConsole); List <string> entries = unzip.UnzipFile(inputFilePath); inputFilePath = entries.Where(entry => Path.GetDirectoryName(entry) == "" && entry.EndsWith(".acm")).FirstOrDefault(); if (inputFilePath != null) { inputFilePath = Path.Combine(unzip.TempDirDestination, inputFilePath); } } using (unzip) try { if (inputFilePath == null) // may be null if .zip didn't contain .acm { throw new FileNotFoundException("No ACM file not found in root directory of ZIP file."); } avm.Component ac_import = null; /* META-3003: Check for old-style ITAR statement */ bool isDistributionD = false; bool isNotItar = false; #region Check for old-style ITAR statements XmlDocument doc = new XmlDocument(); doc.Load(inputFilePath); XmlNode root = doc.DocumentElement; XmlNodeList nodeList = root.SelectNodes("//*[local-name()='DistributionRestriction' and @Level='ITARDistributionD']"); if (nodeList.Count > 0) { isDistributionD = true; } else { nodeList = root.SelectNodes("//*[local-name()='DistributionRestriction' and @Level='NotITAR']"); if (nodeList.Count > 0) { isNotItar = true; } } #endregion using (StreamReader streamReader = new StreamReader(inputFilePath)) { ac_import = DeserializeAvmComponentXml(streamReader); } if (ac_import == null) { throw new Exception("Could not load ACM file."); } /* Throw warning if from an unexpected schema version */ CheckAndWarnOnSchemaVersion(ac_import); /* META-3003: Strip old-style ITAR statement */ #region Strip old-style ITAR statements if (isDistributionD) { // Correct this. if (ac_import.DistributionRestriction == null) { ac_import.DistributionRestriction = new List <avm.DistributionRestriction>(); } ac_import.DistributionRestriction.Add(new avm.DoDDistributionStatement() { Type = DoDDistributionStatementEnum.StatementD }); } else if (isNotItar) { var itar = ac_import.DistributionRestriction.OfType <avm.ITAR>().FirstOrDefault(); if (itar != null) { ac_import.DistributionRestriction.Remove(itar); } } #endregion String acmDir = Path.GetDirectoryName(inputFilePath); #region File Management // Create a new backend folder String compDirAbsPath = META.ComponentLibraryManager.CreateComponentFolder(project); String compDirRelPath = MetaAvmProject.MakeRelativePath(projRootPath, compDirAbsPath); // Copy the ACM file to the new path String newACMRelPath = Path.Combine(compDirRelPath, ac_import.Name + ".acm"); string newACMAbsPath = Path.Combine(compDirAbsPath, ac_import.Name + ".acm"); File.Copy(inputFilePath, newACMAbsPath, true); // Now we have to copy in his resources foreach (var resource in ac_import.ResourceDependency) { try { var dirRelPath = Path.GetDirectoryName(resource.Path); var dirAbsPath = Path.Combine(compDirAbsPath, dirRelPath); var orgAbsPath = Path.Combine(acmDir, resource.Path); var dstAbsPath = Path.Combine(compDirAbsPath, resource.Path); Directory.CreateDirectory(dirAbsPath); File.Copy(orgAbsPath, dstAbsPath, true); } catch (FileNotFoundException) { var message = String.Format("This Component depends on a file which cannot be found in the Component package: {0}", resource.Path); GMEConsole.Warning.WriteLine(message); } catch (DirectoryNotFoundException) { var message = String.Format("This Component depends on a file which cannot be found in the Component package: {0}", resource.Path); GMEConsole.Warning.WriteLine(message); } catch (PathTooLongException) { var message = String.Format("This Component has a Resource that results in a path that is too long: {0}", resource.Path); GMEConsole.Warning.WriteLine(message); } catch (NotSupportedException) { var message = String.Format("This Component has a Resource that could not be loaded: {0}", resource.Path); GMEConsole.Warning.WriteLine(message); } catch (Exception ex) { var message = String.Format("Exception while copying Resource {0}: {1}", resource.Path, ex); GMEConsole.Warning.WriteLine(message); } } #endregion CyPhy.ComponentAssembly cyPhyMLComponentAssembly = null; CyPhy.Components cyPhyMLComponentsFolder = null; CyPhy.Component cyPhyReplaceComponent = null; #region Search for Components that should be Replaced by this new one bool replaceeFound = false; if (ac_import.ID != null) { replaceeFound = avmidComponentMap.TryGetValue(ac_import.ID, out cyPhyReplaceComponent); } if (replaceeFound == false) { replaceeFound = nameComponentMap.TryGetValue(ac_import.Name, out cyPhyReplaceComponent); } if (replaceeFound) { bool replace = false; if (!doNotReplaceAll && !replaceAll) { // Present dialog to see if user wants to replace component with AVMID avmid // Maybe have a "do all" checkbox (which sets "replaceAll" to "true") if many items are being imported. // If yes, replace = true; String s_ExistingName = cyPhyReplaceComponent.Name; String s_ExistingAVMID = cyPhyReplaceComponent.Attributes.AVMID; String s_ExistingVersion = cyPhyReplaceComponent.Attributes.Version; String s_ExistingRevision = cyPhyReplaceComponent.Attributes.Revision; String s_ExistingDescriptor = cyPhyReplaceComponent.Name; if (s_ExistingAVMID != "") { s_ExistingDescriptor += "\nAVM ID: " + s_ExistingAVMID; } if (s_ExistingVersion != "") { s_ExistingDescriptor += "\nVersion: " + s_ExistingVersion; } if (s_ExistingRevision != "") { s_ExistingDescriptor += "\nRevision: " + s_ExistingRevision; } String s_NewName = ac_import.Name; //String s_NewAVMID = ac_import.AVMID; String s_NewVersion = ac_import.Version; //String s_NewRevision = ac_import.Revision; String s_NewDescriptor = ac_import.Name; //if (s_NewAVMID != "") // s_NewDescriptor += "\nAVM ID: " + s_NewAVMID; if (s_NewVersion != "") { s_NewDescriptor += "\nVersion: " + s_NewVersion; } //if (s_NewRevision != "") // s_NewDescriptor += "\nRevision: " + s_NewRevision; String s_MessageBoxPromptTemplate = "Would you like to replace\n\n{0}\n\nwith\n\n{1}"; String s_MessageBoxPrompt = String.Format(s_MessageBoxPromptTemplate, s_ExistingDescriptor, s_NewDescriptor); using (UpdatePrompt up = new UpdatePrompt()) { up.DialogText.Text = s_MessageBoxPrompt; up.ShowDialog(); if (up.DialogResult == DialogResult.Cancel || up.DialogResult == DialogResult.None) { // Skip this component; Continues the "foreach" loop above. GMEConsole.Error.WriteLine("Import canceled for {0}", inputFile); continue; } Dictionary <DialogResult, string> d_TranslateResult = new Dictionary <DialogResult, string>() { { DialogResult.OK, "Replace" }, { DialogResult.Abort, "Import as New" }, }; if (d_TranslateResult[up.DialogResult] == "Replace") { replace = true; if (up.applyToAll.Checked) { replaceAll = true; } } else if (d_TranslateResult[up.DialogResult] == "Import as New") { if (up.applyToAll.Checked) { doNotReplaceAll = true; } } } } if (!replace && !replaceAll || doNotReplaceAll) { cyPhyReplaceComponent = null; } } #endregion if (cyPhyReplaceComponent != null) { Object replaceComponentParent = cyPhyReplaceComponent.ParentContainer; if (replaceComponentParent is CyPhy.ComponentAssembly) { cyPhyMLComponentAssembly = replaceComponentParent as CyPhy.ComponentAssembly; } else { cyPhyMLComponentsFolder = replaceComponentParent as CyPhy.Components; } } else { cyPhyMLComponentsFolder = GetImportFolder(rootFolder); } // The importer uses a map to resolve unit references. // If this is our second run, we shouldn't waste time rebuilding it. Boolean b_ResetUnitMap; if (b_FirstComponent) { b_ResetUnitMap = true; } else { b_ResetUnitMap = false; } CyPhy.Component c = null; if (cyPhyMLComponentAssembly != null) { c = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cyPhyMLComponentAssembly, ac_import, b_ResetUnitMap, GMEConsole); } else { c = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cyPhyMLComponentsFolder, ac_import, b_ResetUnitMap, GMEConsole); } if (c != null) { importedComponents.Append(c.Impl as MgaFCO); c.Attributes.Path = compDirRelPath; } if (cyPhyReplaceComponent != null) { foreach (IMgaReference reference in (cyPhyReplaceComponent.Impl as IMgaFCO).ReferencedBy) { ReferenceSwitcher.Switcher.MoveReferenceWithRefportConnections(c.Impl as IMgaFCO, reference, WriteLine); } cyPhyReplaceComponent.Delete(); } // If icon available, set it in Preferences. // Relative paths here are from our project root. var iconResource = ac_import.ResourceDependency.Where(x => x.Path.Contains("Icon.png")).FirstOrDefault(); //foreach (AVM.File file in ac_import.Files) //{ // if (file.Location.Contains("Icon.png")) // iconRelativePath = componentModelRelativePath + "/" + file.Location; //} if (iconResource != null) { var iconRelativePath = Path.Combine(compDirRelPath, iconResource.Path); // Remove leading "\" if (iconRelativePath.IndexOf("\\") == 0) { iconRelativePath = iconRelativePath.Remove(0, 1); } // Shrink double backslash to single iconRelativePath = iconRelativePath.Replace("\\\\", "\\"); // Replace / with \ iconRelativePath = iconRelativePath.Replace('/', '\\'); // If icon exists, set it if (System.IO.File.Exists(iconRelativePath)) { // Set "icon" regnode (c.Impl as GME.MGA.IMgaFCO).set_RegistryValue("icon", iconRelativePath); } } GMEConsole.Info.WriteLine("Imported {0} to <a href=\"mga:{2}\">{1}</a>", inputFile, SecurityElement.Escape(c.Name), c.ID); } catch (Exception ex) { string error = string.Format("{0} while importing {1}: {2}", ex.GetType().Name, inputFile, ex.Message); GMEConsole.Error.WriteLine(error); this.Errors.Add(error); GMEConsole.Error.WriteLine(ex.StackTrace); } finally { } b_FirstComponent = false; } } finally { // Reset the "enabled" state of the CLM AddOn META.ComponentLibraryManagerAddOn.Enable(b_CLMAddOnStatus, project); } return(importedComponents); }
public void TestCADFileReNaming() { // delete any previous test results if (Directory.Exists(testcreatepath)) { Directory.Delete(testcreatepath, true); } // create a new blank project MgaProject proj = new MgaProject(); proj.Create("MGA=" + testMGApath, "CyPhyML"); // these are the actual steps of the test proj.PerformInTransaction(delegate { // create the environment for the Component authoring class CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(proj); CyPhy.Components components = CyPhyClasses.Components.Create(rf); CyPhy.Component testcomp = CyPhyClasses.Component.Create(components); // Import a CAD file into the test project CyPhyComponentAuthoring.Modules.CADModelImport importcam = new CyPhyComponentAuthoring.Modules.CADModelImport(); // these class variables need to be set to avoid NULL references importcam.SetCurrentComp(testcomp); importcam.CurrentProj = proj; importcam.CurrentObj = testcomp.Impl as MgaFCO; // import the CAD file importcam.ImportCADModel(testpartpath); // Get a path to the imported Cad file var getcadmdl = testcomp.Children.CADModelCollection.First(); string importedpath; getcadmdl.TryGetResourcePath(out importedpath, ComponentLibraryManager.PathConvention.ABSOLUTE); // add in Creo version number importedpath += Path.GetExtension(testpartpath); // Rename the CAD file CyPhyComponentAuthoring.Modules.CADFileRename renamecam = new CyPhyComponentAuthoring.Modules.CADFileRename(); // these class variables need to be set to avoid NULL references renamecam.SetCurrentComp(testcomp); renamecam.CurrentProj = proj; renamecam.CurrentObj = testcomp.Impl as MgaFCO; // call the module with a part file and the new file name renamecam.RenameCADFile(importedpath, RenamedFileNameWithoutExtension); // verify results // 1. Verify the file was renamed var renamecadmdl = testcomp.Children.CADModelCollection.First(); string renamedpath; renamecadmdl.TryGetResourcePath(out renamedpath, ComponentLibraryManager.PathConvention.ABSOLUTE); // add in Creo version renamedpath += ".1"; Assert.True(File.Exists(renamedpath), String.Format("Could not find the renamed CAD file, found {0}", renamedpath)); // 2. Verify the Model was renamed bool model_not_found = false; try { var model_name = testcomp.Children.CADModelCollection.Where(p => p.Name == RenamedFileName).First(); } catch (Exception ex) { model_not_found = true; } Assert.False(model_not_found, String.Format("No CAD model found with the renamed name {0}", RenamedFileName) ); // 3. Verify the resource name and path were changed CyPhy.Resource resource_name = null; bool resource_not_found = false; try { resource_name = testcomp.Children.ResourceCollection.Where(p => p.Name == RenamedFileName).First(); } catch (Exception ex) { resource_not_found = true; } Assert.False(resource_not_found, String.Format("No resource found with the renamed name {0}", RenamedFileName) ); Assert.True(resource_name.Attributes.Path == RenamedFileNameRelativePath, String.Format("{0} should have had value {1}; instead found {2}", resource_name.Name, RenamedFileNameRelativePath, resource_name.Attributes.Path) ); }); proj.Save(); proj.Close(); }
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 FolderTreeNode(CyPhy.Components folder) { this.Folder = folder; this.Children = new List <TreeNodeBase>(); this.Name = folder.Name; }