Exemplo n.º 1
0
        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();
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
        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);
            });
        }
Exemplo n.º 4
0
        private CyPhy.ComponentAssembly CreateComponentAssemblyRoot(avm.Design ad_import)
        {
            CyPhy.ComponentAssemblies cyphy_cas;
            CyPhy.RootFolder          rf = CyPhyClasses.RootFolder.GetRootFolder((MgaProject)project);
            cyphy_cas = rf.Children.ComponentAssembliesCollection.Where(d => d.Name == typeof(CyPhyClasses.ComponentAssemblies).Name).FirstOrDefault();
            if (cyphy_cas == null)
            {
                cyphy_cas      = CyPhyClasses.ComponentAssemblies.Create(rf);
                cyphy_cas.Name = typeof(CyPhyClasses.ComponentAssemblies).Name;
            }
            CyPhy.ComponentAssembly cyphy_container = CyPhyClasses.ComponentAssembly.Create(cyphy_cas);
            // container.Name = ad_import.Name; RootContainer has a name too
            // TODO: check ad_import.SchemaVersion
            int designID;

            if (int.TryParse(ad_import.DesignID, out designID))
            {
                cyphy_container.Attributes.ID = designID;
            }
            if (string.IsNullOrEmpty(ad_import.RootContainer.Description) == false)
            {
                cyphy_container.Attributes.Description = ad_import.RootContainer.Description;
            }
            return(cyphy_container);
        }
Exemplo n.º 5
0
        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);
        }
Exemplo n.º 6
0
 private void getCyPhyMLUnits(CyPhyML.RootFolder rootFolder)
 {
     foreach (CyPhyML.TypeSpecifications typeSpecifications in rootFolder.Children.TypeSpecificationsCollection)
     {
         foreach (CyPhyML.Units units in typeSpecifications.Children.UnitsCollection)
         {
             _cyPhyMLUnitsFolders.Add(units);
         }
     }
 }
Exemplo n.º 7
0
        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));
        }
Exemplo n.º 8
0
        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();
        }
Exemplo n.º 9
0
        public static HashSet <CyPhyML.Component> getCyPhyMLComponentSet(CyPhyML.RootFolder cyPhyMLRootFolder)
        {
            HashSet <CyPhyML.Component> cyPhyMLComponentSet = new HashSet <CyPhyML.Component>();

            foreach (CyPhyML.Components childComponentsFolder in cyPhyMLRootFolder.Children.ComponentsCollection)
            {
                cyPhyMLComponentSet.UnionWith(getCyPhyMLComponentSet(childComponentsFolder));
            }

            return(cyPhyMLComponentSet);
        }
Exemplo n.º 10
0
        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();
        }
Exemplo n.º 11
0
        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();
        }
Exemplo n.º 12
0
        public Model[] ImportFiles(string[] fileNames, DesignImportMode mode = AVMDesignImporter.DesignImportMode.CREATE_DS)
        {
            List <Model> ret = new List <Model>();

            CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);
            Dictionary <string, CyPhy.Component> avmidComponentMap = CyPhyComponentImporterInterpreter.getCyPhyMLComponentDictionary_ByAVMID(rootFolder);

            foreach (var inputFilePath in fileNames)
            {
                var container = ImportFile(inputFilePath, mode);
                ret.Add(container);
            }
            return(ret.ToArray());
        }
Exemplo n.º 13
0
        public static void init(CyPhyML.RootFolder rootFolder)
        {
            if (!isInitialized)
            {
                // Save the rootFolder
                _cyPhyMLRootFolder = rootFolder;

                // Add units to the dictionary
                getCyPhyMLUnits();
                getCyPhyMLNamedUnits();

                isInitialized = true;
            }
        }
Exemplo n.º 14
0
        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();
        }
Exemplo n.º 15
0
        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();
        }
Exemplo n.º 16
0
        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());
            });
        }
Exemplo n.º 17
0
        public void TestComponentInstance()
        {
            // these are the actual steps of the test
            fixture.proj.PerformInTransaction(delegate
            {
                // create the environment for the Component authoring class
                CyPhy.RootFolder rf      = CyPhyClasses.RootFolder.GetRootFolder(fixture.proj);
                CyPhy.Component testcomp = fixture.proj.GetComponentsByName("JustAComponent").First();
                string ret_msg;

                // new instance of the class to test
                CyPhyComponentAuthoring.CyPhyComponentAuthoringInterpreter testcai = new CyPhyComponentAuthoring.CyPhyComponentAuthoringInterpreter();
                // these class variables need to be set to avoid NULL references
                var CurrentObj = testcomp.Impl as MgaFCO;

                // We are in a Component, check valid pre-conditions
                Assert.True(testcai.CheckPreConditions(CurrentObj, out ret_msg),
                            String.Format("{0} should allow CAT to run in it, but it is not. Err=({1})", testcomp.Name, ret_msg)
                            );

                // create a subcomponent and set it as current
                CyPhy.Component testsubcomp = fixture.proj.GetComponentsByName("ComponentSubtype").First();
                CurrentObj = testsubcomp.Impl as MgaFCO;
                // We are in a sub-Component, check valid pre-conditions
                Assert.True(testcai.CheckPreConditions(CurrentObj, out ret_msg),
                            String.Format("{0} should allow CAT to run in it, but it is not. Err=({1})", testsubcomp.Name, ret_msg)
                            );

                // create a component instance and set it as current
                CyPhy.Component testcompinst = fixture.proj.GetComponentsByName("ComponentInstance").First();
                CurrentObj = testcompinst.Impl as MgaFCO;
                // We are in a Component instance, check valid pre-conditions
                Assert.False(testcai.CheckPreConditions(CurrentObj, out ret_msg),
                             String.Format("{0} should NOT allow CAT to run in it, yet it is. Err=({1})", testcompinst.Name, ret_msg)
                             );

                // create a library object and set it as current
                CyPhy.Component testlibcomp = fixture.proj.GetComponentsByName("LibComponent").First();
                CurrentObj = testlibcomp.Impl as MgaFCO;
                // We are in a library object, check valid pre-conditions
                Assert.False(testcai.CheckPreConditions(CurrentObj, out ret_msg),
                             String.Format("{0} should NOT allow CAT to run in it, yet it is. Err=({1})", testlibcomp.Name, ret_msg)
                             );
            });
        }
Exemplo n.º 18
0
        public static CyPhyML.unit getCyPhyMLUnitFromString(string units, CyPhyML.RootFolder rootFolder)
        {
            CyPhyML.unit rVal = null;
            init(rootFolder);

            if (!String.IsNullOrWhiteSpace(units))
            {
                if (_unitSymbolCyPhyMLUnitMap.ContainsKey(units))
                {
                    rVal = _unitSymbolCyPhyMLUnitMap[units];
                }
                else
                {
                    // writeMessage(String.Format("WARNING: No unit lib match found for: {0}", units), MessageType.WARNING);
                }
            }

            return(rVal);
        }
Exemplo n.º 19
0
        public void TestCATDialogBoxCentering()
        {
            // these are the actual steps of the test
            fixture.proj.PerformInTransaction(delegate
            {
                // create the environment for the Component authoring class
                CyPhy.RootFolder rf      = CyPhyClasses.RootFolder.GetRootFolder(fixture.proj);
                CyPhy.Component testcomp = fixture.proj.GetComponentsByName("JustAComponent").First();

                // new instance of the class to test
                CyPhyComponentAuthoring.CyPhyComponentAuthoringInterpreter testcai = new CyPhyComponentAuthoring.CyPhyComponentAuthoringInterpreter();

                // Call the create dialog box method
                testcai.PopulateDialogBox(true);
                // Get the dialog box location and verify it is in the center of the screen
                Assert.True(testcai.ThisDialogBox.StartPosition == FormStartPosition.CenterScreen,
                            String.Format("CAT dialog box is not in the center of the screen")
                            );
            });
        }
Exemplo n.º 20
0
        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);
        }
Exemplo n.º 21
0
        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);
        }
Exemplo n.º 22
0
        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());
            });
        }
Exemplo n.º 23
0
        public IMgaFCO CreateComponentForAcm(MgaProject project, string filename)
        {
            Component ac_import;

            InitializeLogger(project);

            using (Logger)
            {
                using (StreamReader streamReader = new StreamReader(filename))
                {
                    ac_import = this.DeserializeAvmComponentXml_NonStatic(streamReader);
                }
                if (ac_import == null)
                {
                    throw new Exception("Could not load ACM file.");
                }
                CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);
                var cyPhyMLComponentsFolder = DetermineAndEnsureFolderForComponent(rootFolder, ac_import);
                var c = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(cyPhyMLComponentsFolder, ac_import, true, Logger);
                return((IMgaFCO)c.Impl);
            }
        }
Exemplo n.º 24
0
        private CyPhy.DesignContainer CreateDesignSpaceRoot(avm.Design ad_import)
        {
            CyPhy.DesignSpace ds;
            CyPhy.RootFolder  rf = CyPhyClasses.RootFolder.GetRootFolder((MgaProject)project);
            ds = rf.Children.DesignSpaceCollection.Where(d => d.Name == "DesignSpaces").FirstOrDefault();
            if (ds == null)
            {
                ds      = CyPhyClasses.DesignSpace.Create(rf);
                ds.Name = "DesignSpaces";
            }

            CyPhy.DesignContainer cyphy_container = CyPhyClasses.DesignContainer.Create(ds);
            // container.Name = ad_import.Name; RootContainer has a name too
            int designID;

            if (int.TryParse(ad_import.DesignID, out designID))
            {
                cyphy_container.Attributes.ID = designID;
            }
            cyphy_container.Attributes.ContainerType = CyPhyClasses.DesignContainer.AttributesClass.ContainerType_enum.Compound;
            return(cyphy_container);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Call this function within a transaction!
        /// </summary>
        /// <param name="outputDirectory"></param>
        /// <param name="project"></param>
        /// <param name="rootDS"></param>
        /// <param name="textWriter"></param>
        /// <returns></returns>
        public static MetaAvmProject Create(
            string outputDirectory,
            MgaProject project            = null,
            MgaModel rootDS               = null,
            GME.CSharp.GMEConsole console = null
            )
        {
            MetaAvmProject avmProj = new MetaAvmProject();

            outputDirectory = Path.GetFullPath(outputDirectory);
            Directory.CreateDirectory(outputDirectory);

            string avmProjFileName = Path.GetFullPath(Path.Combine(outputDirectory, "manifest.project.json"));

            using (new MutexWrapper(avmProjFileName))
            {
                if (File.Exists(avmProjFileName))
                {
                    string sjson = "{}";
                    using (StreamReader reader = new StreamReader(avmProjFileName))
                    {
                        sjson = reader.ReadToEnd();

                        try
                        {
                            avmProj = JsonConvert.DeserializeObject <AVM.DDP.MetaAvmProject>(sjson);
                        }
                        catch (Newtonsoft.Json.JsonReaderException ex)
                        {
                            throw new Exception(string.Format("{0} file is probably malformed. Not a valid json. {1}{2}", Path.GetFullPath(avmProjFileName), Environment.NewLine, ex.Message));
                        }
                    }
                }
            }

            if (console != null)
            {
                avmProj.infoTextWriter  = console.Info;
                avmProj.errorTextWriter = console.Error;
            }

            avmProj.OutputDirectory = outputDirectory;
            avmProj.m_filename      = avmProjFileName;


            avmProj.Project.LastModified = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");

            if (avmProj.Project.Results.UrlHints.Contains("./results/results.metaresults.json") == false)
            {
                avmProj.Project.Results.UrlHints.Add("./results/results.metaresults.json");
            }

            if (avmProj.Project.Requirements.UrlHints.Contains("./requirements/requirements.json") == false)
            {
                avmProj.Project.Requirements.UrlHints.Add("./requirements/requirements.json");
            }

            string reqSourceRepository = string.Empty;
            string reqId   = string.Empty;
            string reqText = string.Empty;

            if (project != null)
            {
                avmProj.Project.CyPhyProjectFileName = MgaExtensions.MgaExtensions.GetProjectName(project);

                CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project);

                var topLevelLinks = rf.Children.RequirementsCollection
                                    .SelectMany(x => x.Children.RequirementLinkCollection);

                var defaults   = topLevelLinks.Where(x => x.Name.ToLowerInvariant() == "default");
                var reqDefault = defaults.FirstOrDefault();
                if (defaults.Count() > 1)
                {
                    // more requ found first one will be used
                    string msg = string.Format("More than one Requirement was not found {0} in use.", reqDefault.Impl.AbsPath);
                    Trace.TraceWarning(msg);
                    avmProj.infoTextWriter.WriteLine(msg);
                }

                if (reqDefault != null)
                {
                    reqSourceRepository = reqDefault.Attributes.SourceRepository;
                    reqId   = reqDefault.Attributes.ID;
                    reqText = reqDefault.Attributes.Text;
                }
                else
                {
                    // requ not found
                    string msg = "Requirement was not found.";
                    Trace.TraceWarning(msg);

                    // RESTORE THIS MESSAGE ONCE WE SWITCH TO USING GMELOGGER
                    // avmProj.infoTextWriter.WriteLine(msg);
                }
            }

            avmProj.Project.Requirements.vfLink = reqSourceRepository;
            avmProj.Project.Requirements.id     = reqId;
            avmProj.Project.Requirements.text   = reqText;

            string dirName = Path.Combine(outputDirectory, "requirements");

            if (Directory.Exists(dirName) == false)
            {
                Directory.CreateDirectory(dirName);
                string requFileName = Path.GetFullPath(Path.Combine(dirName, "requirements.json"));

                using (new MutexWrapper(requFileName))
                {
                    if (File.Exists(requFileName) == false)
                    {
                        using (StreamWriter writer = new StreamWriter(requFileName))
                        {
                            // default requirement
                            writer.WriteLine(@"{");
                            writer.WriteLine("    \"name\": \"Undefined\",");
                            writer.WriteLine("    \"children\": []");
                            writer.WriteLine(@"}");
                        }
                    }
                }
            }

            string designSpaceFolder = "design-space";

            dirName = Path.GetFullPath(Path.Combine(outputDirectory, designSpaceFolder));

            Directory.CreateDirectory(dirName);

            if (rootDS != null)
            {
                // export designspace
                var dsProjectJsonLink = Path.Combine(".", designSpaceFolder, rootDS.Name + ".adm").Replace('\\', '/');
                var dsFileName        = Path.Combine(dirName, rootDS.Name + ".adm");

                if (avmProj.Project.DesignSpaceModels.Contains(dsProjectJsonLink) == false)
                {
                    avmProj.Project.DesignSpaceModels.Add(dsProjectJsonLink);
                }
                var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(rootDS);
                var design          = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(designContainer);
                using (new MutexWrapper(dsFileName))
                {
                    design.SaveToFile(dsFileName);
                }
            }

            return(avmProj);
        }
Exemplo n.º 26
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            Boolean disposeLogger = false;

            if (Logger == null)
            {
                Logger        = new CyPhyGUIs.GMELogger(project, "CyPhyDesignExporter");
                disposeLogger = true;
            }

            // TODO: Add your interpreter code
            Logger.WriteInfo("Running Design Exporter...");

            #region Prompt for Output Path
            // Get an output path from the user.
            if (this.OutputDir == null)
            {
                using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
                {
                    Description = "Choose a path for the generated files.",
                    //ShowNewFolderButton = true,
                    SelectedPath = Environment.CurrentDirectory,
                })
                {
                    DialogResult dr = fbd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        OutputDir = fbd.SelectedPath;
                    }
                    else
                    {
                        Logger.WriteWarning("Design Exporter cancelled");
                        return;
                    }
                }
            }
            #endregion

            Logger.WriteInfo("Beginning Export...");
            List <CyPhy.DesignEntity>  lde_allCAandDC = new List <CyPhy.DesignEntity>();
            List <CyPhy.TestBenchType> ltbt_allTB     = new List <CyPhy.TestBenchType>();

            if (currentobj != null &&
                currentobj.Meta.Name == "ComponentAssembly")
            {
                lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(currentobj));
            }
            else if (currentobj != null &&
                     currentobj.Meta.Name == "DesignContainer")
            {
                lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(currentobj));
            }
            else if (currentobj != null &&
                     IsTestBenchType(currentobj.MetaBase.Name))
            {
                ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(currentobj));
            }
            else if (selectedobjs != null && selectedobjs.Count > 0)
            {
                foreach (MgaFCO mf in selectedobjs)
                {
                    if (mf.Meta.Name == "ComponentAssembly")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(mf));
                    }
                    else if (mf.Meta.Name == "DesignContainer")
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(mf));
                    }
                    else if (IsTestBenchType(mf.MetaBase.Name))
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(mf));
                    }
                }
            }
            else
            {
                CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);

                MgaFilter filter = project.CreateFilter();
                filter.Kind = "ComponentAssembly";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.ComponentAssembly.Cast(item));
                    }
                }

                filter      = project.CreateFilter();
                filter.Kind = "DesignContainer";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        lde_allCAandDC.Add(CyPhyClasses.DesignContainer.Cast(item));
                    }
                }

                filter      = project.CreateFilter();
                filter.Kind = "TestBenchType";
                foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>())
                {
                    if (item.ParentFolder != null)
                    {
                        ltbt_allTB.Add(CyPhyClasses.TestBenchType.Cast(item));
                    }
                }
            }

            foreach (CyPhy.DesignEntity de in lde_allCAandDC)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    if (de is CyPhy.ComponentAssembly)
                    {
                        ExportToPackage(de as CyPhy.ComponentAssembly, OutputDir);
                    }
                    else
                    {
                        ExportToFile(de, OutputDir);
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", de.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", de.Name, OutputDir);
            }

            foreach (CyPhy.TestBenchType tbt in ltbt_allTB)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    ExportToFile(tbt, OutputDir);
                }
                catch (Exception ex)
                {
                    Logger.WriteError("{0}: Exception encountered ({1})", tbt.Name, ex.Message);
                }
                Logger.WriteInfo("{0}: {1}", tbt.Name, OutputDir);
            }

            Logger.WriteInfo(String.Format("{0} model(s) exported", lde_allCAandDC.Count + ltbt_allTB.Count));
            Logger.WriteInfo("Design Exporter finished");

            if (disposeLogger)
            {
                DisposeLogger();
            }
        }
Exemplo n.º 27
0
        private static Dictionary <string, CyPhy.Component> getCyPhyMLComponentDictionary_ByName(CyPhy.RootFolder cyPhyMLRootFolder)
        {
            var rtn = new Dictionary <string, CyPhy.Component>();

            var       project = cyPhyMLRootFolder.Impl.Project;
            MgaFilter filter  = project.CreateFilter();

            filter.Kind = "Component";
            foreach (var item in project.AllFCOs(filter).Cast <MgaFCO>().Where(x => x.ParentFolder != null))
            {
                var comp = CyPhyClasses.Component.Cast(item);
                rtn[comp.Name] = comp;
            }

            return(rtn);
        }
        public ModelicaModelPicker(
            bool createMultipleComponents, 
            MgaProject thisProject, 
            CyPhyGUIs.GMELogger logger, 
            CyPhy.ComponentType cyphyComponent=null)
        {
            this.InitializeComponent();

            this.componentDetails = new List<ComponentDetail>();
            this.externalPackagePaths = new List<string>();
            this.externalPackageNames = new List<string>();
            this.UpdateModelPickerDataSource_detailed();

            this.m_Logger = logger;
            this.m_Project = thisProject;
            this.m_createMultipleComponents = createMultipleComponents;
            this.dgvModelPicker.MultiSelect = true;

            //string testFilePath = "";

            //if (File.Exists(testFilePath))
            //{
            //    this.ReadFileAndImportComponents_Flat(testFilePath);
            //    return;
            //}
            
            if (this.m_createMultipleComponents)
            {
                this.gbComponentType.Visible = true;
                this.btnImportSelected.Text = "Import Selected Component(s)";
            }

            if (!this.m_createMultipleComponents && 
                cyphyComponent != null)
            {
                this.m_CyPhyComponent = cyphyComponent;
            }

            this.pictureBoxLoader.Visible = false;
            this.btnImportSelected.Enabled = false;
            this.btnViewWebDoc.Enabled = false;
            this.cbIncludeMSL.Checked = true;
            this.cbIncludeMSL.Enabled = false;

            lbExternalLibList.Items.Add("ModelicaStandardLibrary");

            this.rootFolder = CyPhyClasses.RootFolder.GetRootFolder(this.m_Project);

            if (this.rootFolder != null)
            {
                this.localConnectorLibrary =
                    this.rootFolder.Children.ConnectorsCollection.FirstOrDefault(x => x.Name == "ImportedConnectors");

                if (this.localConnectorLibrary != null)
                {
                    this.localPortLibrary =
                        this.localConnectorLibrary.Children.PortsCollection.FirstOrDefault(x =>
                        x.Name == "ImportedPortTypes");

                    if (this.localPortLibrary != null)
                    {
                        this.localPortMap =
                            this.localPortLibrary.Children.ModelicaConnectorCollection.ToDictionary(mc => mc.Attributes.Class);
                    }
                    else
                    {
                        this.localPortLibrary = CyPhyClasses.Ports.Create(this.localConnectorLibrary);
                        this.localPortLibrary.Name = "ImportedPortTypes";
                        this.localPortMap = new Dictionary<string, CyPhy.ModelicaConnector>();
                    }
                }
                else
                {
                    this.localConnectorLibrary = CyPhyClasses.Connectors.Create(this.rootFolder);
                    this.localConnectorLibrary.Name = "ImportedConnectors";
                    this.localPortLibrary = CyPhyClasses.Ports.Create(this.localConnectorLibrary);
                    this.localPortLibrary.Name = "ImportedPortTypes";
                    this.localPortMap = new Dictionary<string, CyPhy.ModelicaConnector>();
                }
            }
            else
            {
                this.m_Logger.WriteError("Could not get the root folder!");
                return;
            }

            this.backgroundWorkerTreeImport.DoWork += backgroundWorkerTreeImport_DoWork;
            this.backgroundWorkerTreeImport.RunWorkerCompleted += backgroundWorkerTreeImport_RunWorkerCompleted;

            this.backgroundWorkerComponentImport.DoWork += backgroundWorkerComponentImport_DoWork;
            this.backgroundWorkerComponentImport.RunWorkerCompleted += backgroundWorkerComponentImport_RunWorkerCompleted;

            this.numModelicaModels = 0;

            this.numComponentParams = 0;
            this.numModelicaParams = 0;

            this.numComponentPorts = 0;
            this.numModelicaPorts = 0;
        }
Exemplo n.º 29
0
        public static int Main(String[] args)
        {
            if (args.Length < 2 || args.Length > 4)
            {
                usage();
                return(1);
            }
            MgaProject    mgaProject;
            List <String> lp_FilesToImport         = new List <string>();
            string        avmFilePath              = "";
            string        mgaProjectPath           = "";
            string        componentReplacementPath = "";

            bool rOptionUsed = false;
            bool pOptionUsed = false;

            for (int ix = 0; ix < args.Length; ++ix)
            {
                if (args[ix].ToLower() == "-r")
                {
                    if (pOptionUsed)
                    {
                        usage();
                        return(1);
                    }
                    rOptionUsed = true;

                    if (++ix >= args.Length)
                    {
                        usage();
                        return(1);
                    }

                    if (avmFilePath != null && avmFilePath != "")
                    {
                        if (mgaProjectPath != null && mgaProjectPath != "")
                        {
                            usage();
                            return(1);
                        }
                        mgaProjectPath = avmFilePath;
                        avmFilePath    = "";
                        lp_FilesToImport.Clear();
                    }

                    String sImportDirectory = args[ix];

                    String   startingDirectory = Path.GetFullPath(sImportDirectory);
                    string[] xmlFiles          = Directory.GetFiles(startingDirectory, "*.acm", SearchOption.AllDirectories);

                    foreach (String p_XMLFile in xmlFiles)
                    {
                        lp_FilesToImport.Add(Path.GetFullPath(p_XMLFile));
                    }
                }
                else if (args[ix].ToLower() == "-p")
                {
                    if (rOptionUsed)
                    {
                        usage();
                        return(1);
                    }
                    pOptionUsed = true;

                    if (++ix >= args.Length)
                    {
                        usage();
                        return(1);
                    }
                    componentReplacementPath = args[ix];
                }
                else if (lp_FilesToImport.Count == 0 && avmFilePath == "")
                {
                    avmFilePath = args[ix];
                    try
                    {
                        lp_FilesToImport.Add(Path.GetFullPath(avmFilePath));
                    }
                    catch (System.ArgumentException ex)
                    {
                        Console.Out.WriteLine(ex.Message);
                        Console.Out.WriteLine(avmFilePath);
                        throw ex;
                    }
                }
                else
                {
                    if (mgaProjectPath != null && mgaProjectPath != "")
                    {
                        usage();
                        return(1);
                    }
                    mgaProjectPath = args[ix];
                }
            }


            mgaProject = GetProject(mgaProjectPath);
            try
            {
                bool bExceptionOccurred = false;
                if (mgaProject != null)
                {
                    MgaGateway mgaGateway = new MgaGateway(mgaProject);

                    mgaGateway.PerformInTransaction(delegate
                    {
                        string libroot = Path.GetDirectoryName(Path.GetFullPath(mgaProjectPath));

                        CyPhyML.RootFolder cyPhyMLRootFolder = ISIS.GME.Common.Utils.CreateObject <CyPhyMLClasses.RootFolder>(mgaProject.RootFolder as MgaObject);

                        #region Attach QUDT library if needed
                        IMgaFolder oldQudt = mgaProject.RootFolder.ChildFolders.Cast <IMgaFolder>().Where(x => x.LibraryName != "" && (x.Name.ToLower().Contains("qudt"))).FirstOrDefault();
                        string mgaQudtPath = Meta_Path + "\\meta\\CyPhyMLQudt.mga";

                        bool needAttach = false;
                        if (oldQudt == null)
                        {
                            needAttach = true;
                        }
                        else
                        {
                            long loldModTime;
                            DateTime oldModTime = long.TryParse(oldQudt.RegistryValue["modtime"], out loldModTime) ? DateTime.FromFileTimeUtc(loldModTime) : DateTime.MinValue;
                            needAttach          = System.IO.File.GetLastWriteTimeUtc(mgaQudtPath).CompareTo(oldModTime) > 0;
                            if (!needAttach)
                            {
                                Console.Error.WriteLine("QUDT is up-to-date: embedded library modified " + oldModTime.ToString() + ", CyPhyMLQudt.mga modified " + System.IO.File.GetLastWriteTimeUtc(mgaQudtPath).ToString());
                            }
                        }

                        if (needAttach)
                        {
                            Console.Error.WriteLine("Attaching library " + mgaQudtPath);
                            ISIS.GME.Common.Interfaces.RootFolder newQudt = ISIS.GME.Common.Classes.RootFolder.GetRootFolder(mgaProject).AttachLibrary("MGA=" + mgaQudtPath);
                            DateTime modtime = System.IO.File.GetLastWriteTimeUtc(mgaQudtPath);
                            ((newQudt as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).RegistryValue["modtime"] =
                                modtime.ToFileTimeUtc().ToString();

                            if (oldQudt != null)
                            {
                                ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(oldQudt, newQudt.Impl, null);
                                sw.UpdateSublibrary();
                                oldQudt.DestroyObject();
                            }
                            ((newQudt as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).LibraryName = "UnitLibrary QUDT";
                            Console.Error.WriteLine((oldQudt == null ? "Attached " : "Refreshed") + " Qudt library.");
                        }
                        #endregion

                        var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                        importer.Initialize(cyPhyMLRootFolder.Impl.Project);
                        importer.ImportFiles(cyPhyMLRootFolder.Impl.Project, libroot, lp_FilesToImport.ToArray(), true);
                        importer.DisposeLogger();
                        bExceptionOccurred = importer.Errors.Count > 0;
                    }, abort: false);

                    mgaProject.Save();

                    if (bExceptionOccurred)
                    {
                        return(-1);
                    }
                }
            }
            finally
            {
                mgaProject.Close(true);
            }
            return(0);
        }
Exemplo n.º 30
0
        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);
        }
Exemplo n.º 31
0
        public static Dictionary <string, CyPhy.Component> getCyPhyMLComponentDictionary_ByAVMID(CyPhy.RootFolder cyPhyMLRootFolder)
        {
            var rtn = new Dictionary <string, CyPhy.Component>();

            var       project = cyPhyMLRootFolder.Impl.Project;
            MgaFilter filter  = project.CreateFilter();

            filter.Kind = "Component";

            // The only folder that can contain components is "Components"
            foreach (var componentsFolder in cyPhyMLRootFolder.Children.ComponentsCollection)
            {
                IMgaFolder mgaComponentsFolder = (IMgaFolder)componentsFolder.Impl;

                foreach (var item in mgaComponentsFolder.GetDescendantFCOs(filter).Cast <MgaFCO>().Where(x => x.ParentFolder != null))
                {
                    var comp = CyPhyClasses.Component.Cast(item);
                    rtn[comp.Attributes.AVMID] = comp;
                }
            }
            return(rtn);
        }