示例#1
0
        public void CopyMgaAndRunDesignImporter(string asmName)
        {
            //proj.Save(proj.ProjectConnStr + asmName + ".mga", true);
            File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + asmName + ".mga").Substring("MGA=".Length), true);

            MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject"));

            proj2.OpenEx(proj.ProjectConnStr + asmName + ".mga", "CyPhyML", null);
            proj2.BeginTransactionInNewTerr();
            try
            {
                MgaFCO componentAssembly = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + asmName);
                Assert.NotNull(componentAssembly);
                componentAssembly.DestroyObject();
                var        importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj2);
                avm.Design design;
                using (StreamReader streamReader = new StreamReader(Path.Combine(AdmPath, asmName + ".adm")))
                    design = CyPhyDesignImporter.CyPhyDesignImporterInterpreter.DeserializeAvmDesignXml(streamReader);
                var ret = (ISIS.GME.Dsml.CyPhyML.Interfaces.DesignEntity)importer.ImportDesign(design,
                                                                                               "ComponentAssemblies" == FolderName ? CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_CAS : CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS);
            }
            finally
            {
                proj2.CommitTransaction();
                if (Debugger.IsAttached)
                {
                    proj2.Save(null, true);
                }
                proj2.Close(true);
            }
        }
示例#2
0
        public static void ImportXME(string xmePath, string mgaPath, bool enableAutoAddons = false)
        {
            MgaParser parser = new MgaParser();
            string    paradigm;
            string    paradigmVersion;
            object    paradigmGuid;
            string    basename;
            string    version;

            parser.GetXMLInfo(xmePath, out paradigm, out paradigmVersion, out paradigmGuid, out basename, out version);

            parser = new MgaParser();
            MgaProject  project  = new MgaProject();
            MgaResolver resolver = new MgaResolver();

            resolver.IsInteractive = false;
            dynamic dynParser = parser;

            dynParser.Resolver = resolver;
            project.Create("MGA=" + Path.GetFullPath(mgaPath), paradigm);
            if (enableAutoAddons)
            {
                project.EnableAutoAddOns(true);
            }
            try
            {
                parser.ParseProject(project, xmePath);
                project.Save();
            }
            finally
            {
                project.Close();
            }
        }
示例#3
0
        public void CopyMgaAndRunImporter(string tbName)
        {
            //proj.Save(proj.ProjectConnStr + asmName + ".mga", true);
            File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + tbName + ".mga").Substring("MGA=".Length), true);

            MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject"));

            proj2.OpenEx(proj.ProjectConnStr + tbName + ".mga", "CyPhyML", null);
            proj2.BeginTransactionInNewTerr();
            try
            {
                MgaFCO oldTestBench = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + tbName + "|kind=TestBench");
                Assert.NotNull(oldTestBench);
                oldTestBench.DestroyObject();
                CyPhyML.TestBenchType testBench;
                using (StreamReader streamReader = new StreamReader(Path.Combine(AtmPath, tbName + ".atm")))
                {
                    avm.TestBench avmTestBench = OpenMETA.Interchange.AvmXmlSerializer.Deserialize <avm.TestBench>(streamReader);
                    testBench = CyPhy2TestBenchInterchange.TestBenchInterchange2CyPhy.Convert(avmTestBench, proj2);
                }
            }
            finally
            {
                proj2.CommitTransaction();
                if (Debugger.IsAttached)
                {
                    proj2.Save(null, true);
                }
                proj2.Close(true);
            }
        }
示例#4
0
        public static void ImportXME(string xmePath, string mgaPath, bool enableAutoAddons=false)
        {
            MgaParser parser = new MgaParser();
            string paradigm;
            string paradigmVersion;
            object paradigmGuid;
            string basename;
            string version;
            parser.GetXMLInfo(xmePath, out paradigm, out paradigmVersion, out paradigmGuid, out basename, out version);

            parser = new MgaParser();
            MgaProject project = new MgaProject();
            MgaResolver resolver = new MgaResolver();
            resolver.IsInteractive = false;
            dynamic dynParser = parser;
            dynParser.Resolver = resolver;
            project.Create("MGA=" + Path.GetFullPath(mgaPath), paradigm);
            if (enableAutoAddons)
            {
                project.EnableAutoAddOns(true);
            }
            try
            {
                parser.ParseProject(project, xmePath);
                project.Save();
            }
            finally
            {
                project.Close();
            }
        }
示例#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);
        }
示例#6
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();
        }
示例#7
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();
        }
示例#8
0
        protected string CopyMgaAndRunDesignImporter(string asmName, Action <ISIS.GME.Dsml.CyPhyML.Interfaces.ComponentAssembly> caTest)
        {
            string testrunDir = Path.Combine(Path.GetDirectoryName(proj.ProjectConnStr.Substring("MGA=".Length)), "testrun");

            try
            {
                Directory.Delete(testrunDir, true);
            }
            catch (DirectoryNotFoundException)
            {
            }
            Directory.CreateDirectory(testrunDir);
            string importMgaPath = Path.Combine(testrunDir, Path.GetFileNameWithoutExtension(proj.ProjectConnStr.Substring("MGA=".Length)) + asmName + ".mga");

            //proj.Save(proj.ProjectConnStr + asmName + ".mga", true);
            File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), importMgaPath, true);

            MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject"));

            proj2.OpenEx("MGA=" + importMgaPath, "CyPhyML", null);
            proj2.BeginTransactionInNewTerr();
            try
            {
                MgaFCO componentAssembly = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + asmName);
                Assert.NotNull(componentAssembly);
                componentAssembly.DestroyObject();
                var        importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj2);
                avm.Design design;
                var        adpPath = Path.Combine(fixture.AdmPath, asmName + ("ComponentAssemblies" == FolderName ? ".adp" : ".adm"));
                var        ret     = importer.ImportFile(adpPath,
                                                         "ComponentAssemblies" == FolderName ? CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_CAS : CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS);
                if (caTest != null)
                {
                    caTest((ISIS.GME.Dsml.CyPhyML.Interfaces.ComponentAssembly)ret);
                }
            }
            finally
            {
                proj2.CommitTransaction();
                if (Debugger.IsAttached)
                {
                    proj2.Save(null, true);
                }
                proj2.Close(true);
            }
            return(importMgaPath);
        }
示例#9
0
        static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                usage();
                return(1);
            }

            MgaProject mainMgaProject = GetProject(args[0]);

            if (mainMgaProject == null)
            {
                return(2);
            }

            int        retval     = 0;
            MgaGateway mgaGateway = new MgaGateway(mainMgaProject);

            mgaGateway.PerformInTransaction(delegate {
                for (int ix = 1; ix < args.Length; ++ix)
                {
                    string[] mergeInfo = args[ix].Split(new string[] { ".mga/" }, 2, StringSplitOptions.None);

                    string filename = mergeInfo[0] + ".mga";
                    string path     = "/" + mergeInfo[1];

                    MgaFCO currentObject = mainMgaProject.get_ObjectByPath(path) as MgaFCO;
                    if (currentObject == null)
                    {
                        Console.Error.WriteLine("Error: could not find object of path \"" + path + "\" in model of file \"" + args[0] + "\", cannot merge file \"" + filename + "\"");
                        retval |= (int)SubTreeMerge.SubTreeMerge.Errors.PathError;
                        continue;
                    }

                    SubTreeMerge.SubTreeMerge subTreeMerge = new SubTreeMerge.SubTreeMerge();
                    subTreeMerge.gmeConsole = new SubTreeMerge.FlexConsole(SubTreeMerge.FlexConsole.ConsoleType.CONSOLE);

                    subTreeMerge.merge(currentObject, filename);
                    retval = (int)subTreeMerge.exitStatus;
                }
            }, abort: false);

            mainMgaProject.Save();

            return(retval);
        }
示例#10
0
        public void Import(IEnumerable <string> lbrFiles)
        {
            project.Create("MGA=" + Path.GetFullPath(Path.Combine(".", "ComponentCreator", "Components")) + ".mga", "CyPhyML");

            IMgaComponent signalBlocksAddon = (IMgaComponent)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Addon.CyPhySignalBlocksAddOn"));

            signalBlocksAddon.Initialize(project);
            project.Notify(globalevent_enum.GLOBALEVENT_OPEN_PROJECT_FINISHED);
            System.Windows.Forms.Application.DoEvents(); // let CyPhySignalBlocksAddOn create libs

            project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED);
            try
            {
                MgaMetaFolder componentsMeta = (MgaMetaFolder)project.RootMeta.RootFolder.DefinedFolderByName["Components", false];
                var           components     = project.RootFolder.CreateFolder(componentsMeta);
                components.Name = componentsMeta.Name;
            }
            finally
            {
                project.CommitTransaction();
            }

            foreach (string eagleFilePath in lbrFiles)
            {
                //Console.WriteLine(eagleFilePath);
                //Console.WriteLine(string.Join(" ", CyPhyComponentAuthoring.Modules.EDAModelImport.GetDevicesInEagleModel(eagleFilePath).ToArray()));
                foreach (string deviceName in CyPhyComponentAuthoring.Modules.EDAModelImport.GetDevicesInEagleModel(eagleFilePath))
                {
                    try
                    {
                        CreateNewComponentMga(eagleFilePath, deviceName);
                        Console.WriteLine("Imported {0} {1}", eagleFilePath, deviceName);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Import failed: " + e.ToString());
                    }
                }
            }
            project.Save("", true);
            project.Close(true);
        }
示例#11
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string OutputBaseDir = (string)componentParameters["output_dir"];

            SotConfig sotConfig = new SotConfig();

            sotConfig.MultiJobRun             = true;
            sotConfig.OriginalProjectFileName = project.ProjectConnStr.Substring("MGA=".Length);
            sotConfig.ProjectFileName         = Path.Combine(OutputBaseDir, Path.GetFileName(sotConfig.OriginalProjectFileName));
            // can't be in a tx and save the project
            project.AbortTransaction();
            project.Save("MGA=" + sotConfig.ProjectFileName, true);
            project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED);
            MgaGateway.PerformInTransaction(delegate
            {
                sotConfig.SoTID = currentobj.ID;
            }, transactiontype_enum.TRANSACTION_READ_ONLY);
            using (StreamWriter writer = new StreamWriter(Path.Combine(OutputBaseDir, "manifest.sot.json")))
            {
                writer.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(sotConfig, Newtonsoft.Json.Formatting.Indented));
            }

            string configsDir = Path.Combine(Path.GetDirectoryName((string)componentParameters["original_project_file"]), "config");

            if (Directory.Exists(configsDir))
            {
                var    configs      = Directory.EnumerateFiles(configsDir, "*xml").ToList();
                string sotConfigDir = Path.Combine(OutputBaseDir, "config");
                Directory.CreateDirectory(sotConfigDir);
                foreach (var config in configs)
                {
                    File.Copy(config, Path.Combine(sotConfigDir, Path.GetFileName(config)));
                }
            }

            //componentParameters["labels"] = "";
            //componentParameters["runCommand"] = ;
            //componentParameters["results_zip_py"] as string;
            // result.LogFileDirectory = Path.Combine(MainParameters.ProjectDirectory, "log");
            // componentParameters["build_query"] as string;
        }
示例#12
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            string OutputBaseDir = (string)componentParameters["output_dir"];

            SotConfig sotConfig = new SotConfig();
            sotConfig.MultiJobRun = true;
            sotConfig.OriginalProjectFileName = project.ProjectConnStr.Substring("MGA=".Length);
            sotConfig.ProjectFileName = Path.Combine(OutputBaseDir, Path.GetFileName(sotConfig.OriginalProjectFileName));
            // can't be in a tx and save the project
            project.AbortTransaction();
            project.Save("MGA=" + sotConfig.ProjectFileName, true);
            project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED);
            MgaGateway.PerformInTransaction(delegate
            {
                sotConfig.SoTID = currentobj.ID;
            }, transactiontype_enum.TRANSACTION_READ_ONLY);
            using (StreamWriter writer = new StreamWriter(Path.Combine(OutputBaseDir, "manifest.sot.json")))
            {
                writer.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(sotConfig, Newtonsoft.Json.Formatting.Indented));
            }

            string configsDir = Path.Combine(Path.GetDirectoryName((string)componentParameters["original_project_file"]), "config");
            if (Directory.Exists(configsDir))
            {
                var configs = Directory.EnumerateFiles(configsDir, "*xml").ToList();
                string sotConfigDir = Path.Combine(OutputBaseDir, "config");
                Directory.CreateDirectory(sotConfigDir);
                foreach (var config in configs)
                {
                    File.Copy(config, Path.Combine(sotConfigDir, Path.GetFileName(config)));
                }
            }

            //componentParameters["labels"] = "";
            //componentParameters["runCommand"] = ;
            //componentParameters["results_zip_py"] as string;
            // result.LogFileDirectory = Path.Combine(MainParameters.ProjectDirectory, "log");
            // componentParameters["build_query"] as string;

        }
        private static void ConvertAllSchematicsToCyPhy(string path)
        {
            var schematics = ConvertAllDevices(path);

            // Create MGA project on the spot.
            var proj = new MgaProject();
            String connectionString = String.Format("MGA={0}", Path.GetTempFileName());
            proj.Create(connectionString, "CyPhyML");
            proj.EnableAutoAddOns(true);

            var mgaGateway = new MgaGateway(proj);
            proj.CreateTerritoryWithoutSink(out mgaGateway.territory);

            var module = new CyPhyComponentAuthoring.Modules
                                                    .EDAModelImport()
            {
                CurrentProj = proj
            };

            Dictionary<String, String> d_failures = new Dictionary<string, string>();
            mgaGateway.PerformInTransaction(delegate
            {
                var rf = CyPhyClasses.RootFolder.GetRootFolder(proj);
                var cf = CyPhyClasses.Components.Create(rf);

                foreach (var t in schematics)
                {
                    var identifier = t.Item1;
                    var schematic = t.Item2;

                    CyPhy.Component component = CyPhyClasses.Component.Create(cf);
                    component.Name = identifier;

                    module.SetCurrentComp(component);

                    try
                    {
                        var cyphySchematicModel = module.BuildCyPhyEDAModel(schematic, component);

                        Assert.Equal(component.Children.SchematicModelCollection.Count(), 1);
                    }
                    catch (Exception e)
                    {
                        d_failures[identifier] = e.ToString();
                    }
                }
            },
            transactiontype_enum.TRANSACTION_NON_NESTED,
            abort: true);
            
            proj.Save();
            proj.Close();

            if (d_failures.Any())
            {
                String msg = String.Format("Failures in converting {0} component(s):" + Environment.NewLine,
                                           d_failures.Count);
                foreach (var kvp in d_failures)
                {
                    msg += String.Format("{0}: {1}" + Environment.NewLine + Environment.NewLine,
                                         kvp.Key,
                                         kvp.Value);
                }

                Assert.True(false, msg);
            }
        }
示例#14
0
        protected void RunCyPhyMLSync(System.Action<MgaProject, CyPhyMetaLink.CyPhyMetaLinkAddon, CyPhyMetaLink.CyPhyMetalinkInterpreter> testAction)
        {
            try
            {
                if (debugMetalinkStartup)
                {
                    metalink.WaitForExit();
                    string stderr = metalink.StandardError.ReadToEnd();
                    string stdout = metalink.StandardOutput.ReadToEnd();
                }
                Exception exception = null;
                AutoResetEvent workEvent = new AutoResetEvent(false);
                Thread work = new Thread(new ThreadStart(delegate
                {

                    try
                    {
                        // Import XME file to create an MGA
                        String xmeFullPath = Path.Combine(TestModelDir, testXMEFilename);
                        String mgaFullPath = TestModelDir + testInputFilename;
                        MgaUtils.ImportXME(xmeFullPath, mgaFullPath);
                        Assert.True(File.Exists(mgaFullPath), "MGA file not found. XME import may have failed.");

                        MgaProject project = new MgaProject();
                        project.EnableAutoAddOns(true);
                        project.OpenEx("MGA=" + mgaFullPath, "", true);
                        try
                        {
                            Assert.Contains("MGA.Addon.CyPhyMLPropagate", project.AddOnComponents.Cast<IMgaComponentEx>().Select(x => x.ComponentProgID));
                            CyPhyMetaLink.CyPhyMetaLinkAddon propagate = (CyPhyMetaLink.CyPhyMetaLinkAddon)project.AddOnComponents.Cast<IMgaComponent>().Where(comp => comp is CyPhyMetaLink.CyPhyMetaLinkAddon).FirstOrDefault();
                            CyPhyMetaLink.CyPhyMetalinkInterpreter interpreter = new CyPhyMetaLink.CyPhyMetalinkInterpreter();
                            propagate.TestMode = true;
                            interpreter.GMEConsole = GME.CSharp.GMEConsole.CreateFromProject(project);
                            interpreter.MgaGateway = new MgaGateway(project);

                            interpreter.ConnectToMetaLinkBridge(project, 128);
                            propagate.bridgeClient.SocketQueue.EditMessageReceived += msg => addonMessagesQueue.Add(msg);
                            testAction(project, propagate, interpreter);
                        }
                        finally
                        {
                            project.Save(project.ProjectConnStr + "_posttest.mga", true);
                            project.Close(true);
                        }
                    }
                    catch (Exception e)
                    {
                        exception = e;
                        KillMetaLink();
                    }
                    finally
                    {
                        workEvent.Set();
                    }
                }));
                work.SetApartmentState(ApartmentState.STA);
                work.Start();

                ManualResetEvent metalinkEvent = new ManualResetEvent(true);
                metalinkEvent.SafeWaitHandle = new SafeWaitHandle(metalink.Handle, false);

                int handle = WaitHandle.WaitAny(new WaitHandle[] { metalinkEvent, workEvent });
                if (exception != null)
                {
                    throw new Exception("Test failed", exception);
                }
                if (handle == 0)
                {
                    work.Abort();
                    throw new Exception("metalink exited");
                }
            }
            finally
            {
                KillMetaLink();
                lock (metalinkLogStream)
                    metalinkLogStream.Dispose();
            }
        }
        public void DesignPackageImport()
        {
            // Clean the test directory
            var pathTest = Path.Combine(META.VersionInfo.MetaPath,
                                        "test",
                                        "InterchangeTest",
                                        "DesignInterchangeTest",
                                        "ImportTestUnits",
                                        "Package");
            foreach (var path in Directory.EnumerateDirectories(pathTest))
            {
                Directory.Delete(path, true);
            }
            foreach (var path in Directory.EnumerateFiles(pathTest, "*.*"))
            {
                if (!path.Contains("NestedFolders.adp"))
                {
                    File.Delete(path);
                }
            }

            // Create a test project
            var proj = new MgaProject();
            proj.Create("MGA=" + Path.Combine(pathTest,"testmodel.mga"), "CyPhyML");

            try
            {
                String pathCA = null;
                proj.PerformInTransaction(() =>
                {
                    // Instantiate the importer and import the package
                    var importer = new AVMDesignImporter(GMEConsole.CreateFromProject(proj), proj);

                    var mdlCA = importer.ImportFile(Path.Combine(pathTest, "NestedFolders.adp"), AVMDesignImporter.DesignImportMode.CREATE_CAS);
                    var ca = CyPhyClasses.ComponentAssembly.Cast(mdlCA.Impl);
                    pathCA = ca.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
                });

                // Check the design's backend folder for all files except for the ADM.
                var filesExpected = new List<String> 
                { 
                    "testObject.txt",
                    "dir1/testObject.txt",
                    "dir1/dir1a/testObject.txt",
                    "dir2/testObject.txt"
                };
                var filesInDir = Directory.GetFiles(pathCA, "*.*", SearchOption.AllDirectories);

                Assert.Equal(filesExpected.Count(), filesInDir.Count());
                foreach (var file in filesExpected)
                {
                    String fullPath = Path.Combine(pathCA, file);
                    Assert.True(File.Exists(fullPath));
                }
            }
            finally
            {
                proj.Save();
                proj.Close();
            }
        }
示例#16
0
        void TestSubTreeMergeModel()
        {
            string mgaFileCopy = mgaFile + "copy.mga";

            File.Copy(mgaFile, mgaFile + "copy.mga", true);
            MgaProject project = new MgaProject();

            project.OpenEx("MGA=" + this.mgaFile, "CyPhyML", null);
            try
            {
                project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED);
                try
                {
                    string mergeMeModelPath       = "/@ComponentAssemblies/@MergeMe";
                    MgaFCO mergeMe                = (MgaFCO)project.ObjectByPath[mergeMeModelPath];
                    int    startingDescendantFCOs = ((MgaModel)mergeMe).GetDescendantFCOs(mergeMe.Project.CreateFilter()).Count;

                    var fcos = ((MgaModel)mergeMe).GetDescendantFCOs(project.CreateFilter()).Cast <MgaFCO>().Select(
                        x => x.AbsPath).ToList();

                    foreach (MgaObject obj in mergeMe.ChildObjects)
                    {
                        if (obj.MetaBase.Name != "Connector" && obj.MetaBase.Name != "Axis" && /* keep these, since they have refport connections*/
                            obj.Status == (int)objectstatus_enum.OBJECT_EXISTS /* connections may be deleted when their endpoints are */)
                        {
                            obj.DestroyObject();
                        }
                    }

                    var subTreeMerge = new SubTreeMerge.SubTreeMerge();
                    subTreeMerge.merge(mergeMe, mgaFileCopy);
                    Assert.Equal(SubTreeMerge.SubTreeMerge.Errors.NoError, subTreeMerge.exitStatus);
                    MgaFCO newMergeMe = (MgaFCO)project.ObjectByPath[mergeMeModelPath];

                    Assert.Equal(newMergeMe.ID, ((MgaReference)project.ObjectByPath["/@ComponentAssemblies/@AsmWithRef/@MergeMe"]).Referred.ID);
                    Assert.Equal(newMergeMe.ID, ((MgaReference)project.ObjectByPath["/@Testing/@TestBench/@MergeMe"]).Referred.ID);
                    Assert.Equal(2, ((MgaReference)project.ObjectByPath["/@ComponentAssemblies/@AsmWithRef/@MergeMe"]).UsedByConns.Count);
                    Assert.Equal(2, ((MgaReference)project.ObjectByPath["/@Testing/@TestBench/@MergeMe"]).UsedByConns.Count);
                    //Debugging:
                    //var fcos2 = ((MgaModel)newMergeMe).GetDescendantFCOs(project.CreateFilter()).Cast<MgaFCO>().Select(x => x.AbsPath)
                    //    .Where(x => fcos.Contains(x) == false);
                    //HashSet<string> originalObjects = new HashSet<string>();
                    //foreach (string abspath in fcos)
                    //    originalObjects.Add(abspath);
                    //foreach (string abspath in ((MgaModel)newMergeMe).GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>().Select(x => x.AbsPath))
                    //    originalObjects.Remove(abspath);
                    // Console.Out.WriteLine(string.Join("\n", originalObjects));
                    Assert.Equal(startingDescendantFCOs, ((MgaModel)newMergeMe).GetDescendantFCOs(project.CreateFilter()).Count);
                }
                finally
                {
                    project.CommitTransaction();
                }
            }
            finally
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    project.Save(project.ProjectConnStr + "_testoutput.mga", true);
                }
                project.Close(true);
            }
        }
示例#17
0
        protected void RunCyPhyMLSync(System.Action <MgaProject, CyPhyMetaLink.CyPhyMetaLinkAddon, CyPhyMetaLink.CyPhyMetalinkInterpreter> testAction)
        {
            try
            {
                if (debugMetalinkStartup)
                {
                    metalink.WaitForExit();
                    string stderr = metalink.StandardError.ReadToEnd();
                    string stdout = metalink.StandardOutput.ReadToEnd();
                }
                Exception      exception = null;
                AutoResetEvent workEvent = new AutoResetEvent(false);
                Thread         work      = new Thread(new ThreadStart(delegate
                {
                    try
                    {
                        // Import XME file to create an MGA
                        String xmeFullPath = Path.Combine(TestModelDir, testXMEFilename);
                        String mgaFullPath = TestModelDir + testInputFilename;
                        MgaUtils.ImportXME(xmeFullPath, mgaFullPath);
                        Assert.True(File.Exists(mgaFullPath), "MGA file not found. XME import may have failed.");

                        MgaProject project = new MgaProject();
                        project.EnableAutoAddOns(true);
                        project.OpenEx("MGA=" + mgaFullPath, "", true);
                        CyPhyMetaLink.CyPhyMetaLinkAddon propagate = null;
                        try
                        {
                            Assert.Contains("MGA.Addon.CyPhyMLPropagate", project.AddOnComponents.Cast <IMgaComponentEx>().Select(x => x.ComponentProgID));
                            propagate = (CyPhyMetaLink.CyPhyMetaLinkAddon)project.AddOnComponents.Cast <IMgaComponent>().Where(comp => comp is CyPhyMetaLink.CyPhyMetaLinkAddon).FirstOrDefault();
                            CyPhyMetaLink.CyPhyMetalinkInterpreter interpreter = new CyPhyMetaLink.CyPhyMetalinkInterpreter();
                            propagate.TestMode = true;
                            propagate.TestMode_NoAutomaticCreoStart = true;
                            propagate.TestMode_CreoJobObject        = JobObjectPinvoke.CreateKillOnCloseJob();
                            interpreter.GMEConsole = GME.CSharp.GMEConsole.CreateFromProject(project);
                            interpreter.MgaGateway = new MgaGateway(project);

                            var task = Task.Run(async() => await interpreter.ConnectToMetaLinkBridge(project, 128));
                            task.Wait();
                            propagate.bridgeClient.SocketQueue.EditMessageReceived += msg => addonMessagesQueue.Add(msg);
                            testAction(project, propagate, interpreter);
                        }
                        finally
                        {
                            if (propagate != null)
                            {
                                JobObjectPinvoke.CloseHandle(propagate.TestMode_CreoJobObject);
                                propagate.TestMode_CreoJobObject = IntPtr.Zero;
                            }
                            project.Save(project.ProjectConnStr + "_posttest.mga", true);
                            project.Close(true);
                        }
                    }
                    catch (Exception e)
                    {
                        exception = e;
                        KillMetaLink();
                    }
                    finally
                    {
                        workEvent.Set();
                    }
                }));
                work.SetApartmentState(ApartmentState.STA);
                work.Start();

                ManualResetEvent metalinkEvent = new ManualResetEvent(true);
                metalinkEvent.SafeWaitHandle = new SafeWaitHandle(metalink.Handle, false);

                int handle = WaitHandle.WaitAny(new WaitHandle[] { metalinkEvent, workEvent });
                if (exception != null)
                {
                    throw new Exception("Test failed", exception);
                }
                if (handle == 0)
                {
                    work.Abort();
                    throw new Exception("metalink exited");
                }
            }
            finally
            {
                KillMetaLink();
                lock (metalinkLogStream)
                    metalinkLogStream.Dispose();
            }
        }
示例#18
0
        static int Main(string[] args)
        {
            bool   errorInUsage     = false;
            bool   mgaIsGiven       = true;
            bool   generateTemplate = false;
            bool   formattedOutput  = false;
            string outputDirectory  = Path.Combine(Environment.CurrentDirectory, "output");
            string statFileName     = "sample_stats.json";
            string inputFilename    = string.Empty;

            Directory.CreateDirectory(outputDirectory);

            // verify the input arguments
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].StartsWith("-"))
                {
                    switch (args[i].Substring(1))
                    {
                    case "p":
                    case "-prettyPrint":
                        formattedOutput = true;
                        break;

                    case "t":
                    case "-template":
                        generateTemplate = true;
                        break;

                    default:
                        errorInUsage = true;
                        break;
                    }
                }
                else
                {
                    inputFilename = args[i];

                    if (i < args.Length - 1)
                    {
                        Console.WriteLine("Arguments after filename are ignored.");
                    }

                    break;
                }
            }

            if (File.Exists(inputFilename))
            {
                if (Path.GetExtension(inputFilename).ToLowerInvariant() == ".mga")
                {
                    mgaIsGiven = true;
                }
                else if (Path.GetExtension(inputFilename).ToLowerInvariant() == ".xme")
                {
                    mgaIsGiven = false;
                }
                else
                {
                    errorInUsage = true;
                }
            }
            else
            {
                errorInUsage = true;
            }


            if (generateTemplate)
            {
                Statistics.Statistics stats = Process(null);
                SerializeStats(stats, Path.Combine(outputDirectory, statFileName), formattedOutput);
                return(0);
            }

            if (errorInUsage)
            {
                Console.WriteLine("Usage: {0} [arguments] inputfilename.[mga|xme]", Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location));
                Console.WriteLine("");
                Console.WriteLine("Arguments:");
                Console.WriteLine("  -p --prettyPrint   Indents the output json file.");
                Console.WriteLine("  -t --template      Generates a sample json file with random numbers.");
                return(1);
            }


            // copy the file to a temp directory
            string tempXmeFile = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(inputFilename) + ".xme");
            string tempMgaFile = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(inputFilename) + ".mga");

            statFileName = Path.GetFileNameWithoutExtension(inputFilename) + "_stat.json";

            MgaProject project = new MgaProject();

            if (mgaIsGiven)
            {
                if (inputFilename != tempMgaFile)
                {
                    Console.WriteLine("Copying MGA file to temp directory: {0}", tempMgaFile);
                    File.Copy(inputFilename, tempMgaFile, true);
                }

                Console.WriteLine("Opening project");
                int    mgaversion;
                string paradigmName;
                string paradigmVersion;
                object paradigmGUID;
                bool   ro_mode;

                project.QueryProjectInfo("MGA=" + tempMgaFile, out mgaversion, out paradigmName, out paradigmVersion, out paradigmGUID, out ro_mode);

                project.OpenEx("MGA=" + tempMgaFile, paradigmName, true);

                Console.WriteLine("Saving project as xme: {0}", tempXmeFile);
                // export to xme
                GME.MGA.Parser.MgaDumper dumper = new GME.MGA.Parser.MgaDumper();
                dumper.DumpProject(project, tempXmeFile);
            }
            else
            {
                if (inputFilename != tempXmeFile)
                {
                    Console.WriteLine("Copying XME file to temp directory: {0}", tempXmeFile);
                    File.Copy(inputFilename, tempXmeFile, true);
                }

                GME.MGA.Parser.MgaParser parser = new GME.MGA.Parser.MgaParser();
                string paradigmName;

                parser.GetXMLParadigm(tempXmeFile, out paradigmName);

                Console.WriteLine("Creating project");
                project.CreateEx("MGA=" + tempMgaFile, paradigmName, null);

                // import xme file
                Console.WriteLine("Importing project");

                parser.ParseProject(project, tempXmeFile);

                Console.WriteLine("Saving project as mga: {0}", tempMgaFile);
                project.Save("MGA=" + tempMgaFile);
            }

            if (project == null)
            {
                throw new Exception("Project is null.");
            }


            // process the project
            var statistics = Process(project);

            // read in file stats
            FileInfo mgaInfo = new FileInfo(tempMgaFile);
            FileInfo xmeInfo = new FileInfo(tempXmeFile);

            statistics.MgaSizeInBytes = mgaInfo.Length;
            statistics.XmeSizeInBytes = xmeInfo.Length;

            // serialize the object
            SerializeStats(statistics, Path.Combine(outputDirectory, statFileName), formattedOutput);


            return(0);
        }
示例#19
0
        public void DesignPackageImport()
        {
            // Clean the test directory
            var pathTest = Path.Combine(META.VersionInfo.MetaPath,
                                        "test",
                                        "InterchangeTest",
                                        "DesignInterchangeTest",
                                        "ImportTestUnits",
                                        "Package");

            foreach (var path in Directory.EnumerateDirectories(pathTest))
            {
                Directory.Delete(path, true);
            }
            foreach (var path in Directory.EnumerateFiles(pathTest, "*.*"))
            {
                if (!path.Contains("NestedFolders.adp"))
                {
                    File.Delete(path);
                }
            }

            // Create a test project
            var proj = new MgaProject();

            proj.Create("MGA=" + Path.Combine(pathTest, "testmodel.mga"), "CyPhyML");

            try
            {
                String pathCA = null;
                proj.PerformInTransaction(() =>
                {
                    // Instantiate the importer and import the package
                    var importer = new AVMDesignImporter(GMEConsole.CreateFromProject(proj), proj);

                    var mdlCA = importer.ImportFile(Path.Combine(pathTest, "NestedFolders.adp"), AVMDesignImporter.DesignImportMode.CREATE_CAS);
                    var ca    = CyPhyClasses.ComponentAssembly.Cast(mdlCA.Impl);
                    pathCA    = ca.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
                });

                // Check the design's backend folder for all files except for the ADM.
                var filesExpected = new List <String>
                {
                    "testObject.txt",
                    "dir1/testObject.txt",
                    "dir1/dir1a/testObject.txt",
                    "dir2/testObject.txt"
                };
                var filesInDir = Directory.GetFiles(pathCA, "*.*", SearchOption.AllDirectories);

                Assert.Equal(filesExpected.Count(), filesInDir.Count());
                foreach (var file in filesExpected)
                {
                    String fullPath = Path.Combine(pathCA, file);
                    Assert.True(File.Exists(fullPath));
                }
            }
            finally
            {
                proj.Save();
                proj.Close();
            }
        }
示例#20
0
 public void Dispose()
 {
     project.Save();
     project.Close();
 }
        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();
        }
示例#22
0
        private static void ConvertAllSchematicsToCyPhy(string path)
        {
            var schematics = ConvertAllDevices(path);

            // Create MGA project on the spot.
            var    proj             = new MgaProject();
            String connectionString = String.Format("MGA={0}", Path.GetTempFileName());

            proj.Create(connectionString, "CyPhyML");
            proj.EnableAutoAddOns(true);

            var mgaGateway = new MgaGateway(proj);

            var module = new CyPhyComponentAuthoring.Modules.EDAModelImport();

            Dictionary <String, String> d_failures = new Dictionary <string, string>();

            mgaGateway.PerformInTransaction(delegate
            {
                var rf = CyPhyClasses.RootFolder.GetRootFolder(proj);
                var cf = CyPhyClasses.Components.Create(rf);

                foreach (var t in schematics)
                {
                    var identifier = t.Item1;
                    var schematic  = t.Item2;

                    CyPhy.Component component = CyPhyClasses.Component.Create(cf);
                    component.Name            = identifier;

                    module.SetCurrentDesignElement(component);
                    module.CurrentObj = component.Impl as MgaFCO;

                    try
                    {
                        var cyphySchematicModel = module.BuildCyPhyEDAModel(schematic, component);

                        Assert.Equal(component.Children.SchematicModelCollection.Count(), 1);
                    }
                    catch (Exception e)
                    {
                        d_failures[identifier] = e.ToString();
                    }
                }
            },
                                            transactiontype_enum.TRANSACTION_NON_NESTED,
                                            abort: true);

            proj.Save();
            proj.Close();

            if (d_failures.Any())
            {
                String msg = String.Format("Failures in converting {0} component(s):" + Environment.NewLine,
                                           d_failures.Count);
                foreach (var kvp in d_failures)
                {
                    msg += String.Format("{0}: {1}" + Environment.NewLine + Environment.NewLine,
                                         kvp.Key,
                                         kvp.Value);
                }

                Assert.True(false, msg);
            }
        }