PerformInTransaction() public method

public PerformInTransaction ( voidDelegate d, transactiontype_enum mode = transactiontype_enum.TRANSACTION_NON_NESTED, bool abort = true ) : void
d voidDelegate
mode transactiontype_enum
abort bool
return void
Example #1
0
        static int Main(string[] args) {

            if (args.Length < 2) usage();

            MgaProject mainMgaProject = GetProject( args[0] );

            if( mainMgaProject == null ) {
                Environment.Exit( 2 );
            }

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

            mainMgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
            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;
                }

            });

            mainMgaProject.Save();

            if (mgaGateway.territory != null) {
                mgaGateway.territory.Destroy();
            }

            return retval;
        }
Example #2
0
        public static int Main(string[] args)
        {
            var options = new Options();
            if (!Parser.Default.ParseArguments(args, options)) return -1;

            var project = GetProject(options.MgaFile);

            if (project == null)
            {
                Environment.Exit(1);
            }

            try
            {
                var mgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out mgaGateway.territory);

                var designList = new List<CyPhy.DesignEntity>();
                var designName = Safeify(options.DesignName);


                bool bExceptionOccurred = false;
                mgaGateway.PerformInTransaction(delegate
                {
                    try
                    {
                        #region Collect DesignEntities

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

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

                        #endregion

                        #region Process DesignEntities

                        foreach (CyPhy.DesignEntity de in designList)
                        {
                            var currentDesignName = Safeify(de.Name);

                            if (!string.IsNullOrEmpty(options.DesignName) && currentDesignName != designName) continue;

                            var dm = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(de);
                            var outFilePath = String.Format("{0}\\{1}.adm", new FileInfo(options.MgaFile).DirectoryName, currentDesignName);
                            XSD2CSharp.AvmXmlSerializer.SaveToFile(outFilePath, dm);
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("Exception: {0}", ex.Message.ToString());
                        Console.Error.WriteLine("Stack: {0}", ex.StackTrace.ToString());
                        bExceptionOccurred = true;
                    }
                });

                if (bExceptionOccurred)
                    return -1;

                return 0;
            }
            finally
            {
                project.Close(true);
            }
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);


                propagateAddon = GetPropagateAddon(project);
                if (propagateAddon == null)
                {
                    GMEConsole.Error.WriteLine("CyPhyMLSync: Unable to contact CyPhyMLPropagate.");
                    return;
                }
                if (propagateAddon.bridgeClient.IsConnectedToBridge() == false)
                {
                    ConnectToMetaLinkBridge(project, param);
                }

                string currentobjKind = null;
                MgaFCO selectedCADModel = null;
                string componentVersion = null;
                MgaGateway.PerformInTransaction(delegate
                {
                    if (currentobj != null)
                    {
                        currentobjKind = currentobj.Meta.Name;
                        if (currentobjKind == "CADModel")
                        {
                            selectedCADModel = currentobj;
                            currentobj = (MgaFCO)currentobj.ParentModel;
                            currentobjKind = currentobj.Meta.Name;
                        }
                        else
                        {
                            Func<MgaFCO, bool> isCADCreoModel = fco => fco.Meta.Name == "CADModel"
                                && CyPhyMLClasses.CADModel.Cast(fco).Attributes.FileFormat == CyPhyMLClasses.CADModel.AttributesClass.FileFormat_enum.Creo;
                            selectedCADModel = (selectedobjs ?? (System.Collections.IEnumerable)(new List<MgaFCO>())).Cast<MgaFCO>()
                                .FirstOrDefault(isCADCreoModel);
                            if (selectedCADModel == null && currentobj.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL)
                            {
                                // TODO: show dialog instead of picking one at random
                                selectedCADModel = ((MgaModel)currentobj).ChildFCOs.Cast<MgaFCO>().FirstOrDefault(isCADCreoModel);
                            }
                        }
                        if (currentobj != null && currentobj.Meta.Name == typeof(CyPhyMLClasses.Component).Name)
                        {
                            componentVersion = CyPhyMLClasses.Component.Cast(currentobj).Attributes.Version;
                        }
                    }
                }, transactiontype_enum.TRANSACTION_GENERAL, abort: false);
                if (currentobjKind != null && currentobjKind != "Component" && currentobjKind != "CADModel" && currentobjKind != "ComponentAssembly")
                {
                    System.Windows.Forms.MessageBox.Show("Please open a Component or a Component Assembly");
                    return;
                }
                if (currentobjKind == "Component")
                {
                    CyPhyML.Component component = CyPhyMLClasses.Component.Cast(currentobj);
                    if (selectedCADModel == null)
                    {
                        GMEConsole.Error.WriteLine("This component has no CADModels to edit.");
                        return;
                    }
                    bool connected = true;
                    if (propagateAddon.bridgeClient.IsConnectedToBridge() == false)
                    {
                        connected = ConnectToMetaLinkBridge(project, param);
                    }
                    if (connected)
                    {
                        LinkComponent(component, selectedCADModel);
                    }
                    return;
                }

                if (currentobjKind == null)
                {
                    propagateAddon.StartCreoEmpyMode();
                    return;
                }

                //GMEConsole.Out.WriteLine("Running CyPhySync interpreter...");

                if (propagateAddon.AssemblyID != null)
                {
                    GMEConsole.Warning.WriteLine("A ComponentAssembly is already synced");
                }
                else
                {
                    bool connected = propagateAddon.bridgeClient.IsConnectedToBridge();
                    if (connected == false)
                    {
                        GMEConsole.Info.WriteLine("Connecting to MetaLink Bridge ...");

                        connected = ConnectToMetaLinkBridge(project, param);
                    }

                    if (connected)
                    {
                        StartAssemblySync(project, currentobj, param);
                    }
                }

                //GMEConsole.Out.WriteLine("End of CyPhySync interpreter...");
            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public static int Main(String[] args)
        {

            if (args.Length < 1)
            {
                Console.Out.WriteLine("Usage: <program> CyberFile.mga [-f] [outputDirectory]");
                Environment.Exit(1);
            }

            MgaProject mgaProject = null;

            string outputDirectory = ".";
            bool flat = false;

            String mgaFilePath = null;
            for (int ix = 0; ix < args.Length; ++ix)
            {
                if (args[ix] == "-f")
                {
                    flat = true;
                }
                else if (mgaProject == null)
                {
                    mgaProject = CyberModelUtil.MgaUtil.GetProject(args[ix]);
                    mgaFilePath = args[ix];
                }
                else
                {
                    outputDirectory = args[ix];
                }
            }

            if (mgaProject == null)
            {
                Console.Out.WriteLine("Usage: <program> CyberFile.mga [-f] [outputDirectory]");
                Environment.Exit(1);
            }

            MgaGateway mgaGateway = new MgaGateway(mgaProject);
            mgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);

            bool bExceptionOccurred = false;

            mgaGateway.PerformInTransaction(delegate
            {
                try
                {
                    Cyber.RootFolder cyberRootFolder = ISIS.GME.Common.Utils.CreateObject<CyberClasses.RootFolder>(mgaProject.RootFolder);
                    HashSet<Cyber.ModelicaComponent> cyberComponentSet = ComponentLister.getCyberComponentSet(cyberRootFolder);

                    //ParallelOptions options = new ParallelOptions();
                    //options.MaxDegreeOfParallelism = 4;

                    //var ruleChecker = new DesignConsistencyChecker.Framework.Checker(null, mgaProject);
                    //ruleChecker.RegisterRuleDll("DesignConsistencyChecker.dll");
                    //var uniqueNameRule = ruleChecker.GetRegisteredRules.FirstOrDefault(x => x.Name == "UniquePPMNames");

                    int i_Counter = 1;
                    foreach (var cyberComponent in cyberComponentSet)
                    {
                        try
                        {
                            //if (uniqueNameRule != null)
                            //{
                            //    var feedBacks = uniqueNameRule.Check((MgaFCO)cyberComponent.Impl).ToList();
                            //    if (feedBacks.Any(x => x.FeedbackType == FeedbackTypes.Error))
                            //    {
                            //        foreach (var fb in feedBacks.Where(x => x.FeedbackType == FeedbackTypes.Error))
                            //        {
                            //            Console.Error.WriteLine("Rule {0} failed: {1}", uniqueNameRule.Name, fb.Message);
                            //        }
                            //        continue;
                            //    }
                            //}

                            //foreach (Cyber.ModelicaComponent cyberComponent in cyberComponentList) {
                            AVMComponentBuilder avmComponentBuilder = new AVMComponentBuilder();
                            avmComponentBuilder.createAVMCyberModel(cyberComponent, mgaFilePath);
                            avm.Component avmComponent = avmComponentBuilder.getAVMComponent();
                            string componentPath = null;

                            if (flat)
                            {
                                componentPath = outputDirectory;
                            }
                            else
                            {
                                componentPath = cyberComponent.Path;
                                componentPath = outputDirectory + "/" + componentPath.Substring(componentPath.IndexOf("/"));
                            }

                            Directory.CreateDirectory(componentPath);

                            // delete below
                            //if (!flat)
                            //{
                            //    Directory.CreateDirectory(componentPath + "/images");
                            //    //Directory.CreateDirectory( componentPath + "/Cyber" );
                            //    Directory.CreateDirectory(componentPath + "/doc");
                            //    Directory.CreateDirectory(componentPath + "/CAD");
                            //}

                            String s_outFilePath = String.Format("{0}/{1}.component.acm", componentPath, META2AVM_Util.UtilFuncs.Safeify(cyberComponent.Name));
                            META2AVM_Util.UtilFuncs.SerializeAvmComponent(avmComponent, s_outFilePath);
                            //StreamWriter streamWriter = new StreamWriter(s_outFilePath);

                            //System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(avm.Component), META2AVM_Util.UtilFuncs.getAVMClasses());

                            //serializer.Serialize(streamWriter, avmComponent);
                            //streamWriter.Close();

                            Console.Out.WriteLine(string.Format("({0}/{1}) {2}", i_Counter++, cyberComponentSet.Count, META2AVM_Util.UtilFuncs.Safeify(cyberComponent.Name)));
                            //}
                        }
                        catch (Exception ex)
                        {
                            Console.Error.WriteLine("Exception: {0}", ex.Message.ToString());
                            Console.Error.WriteLine("Stack: {0}", ex.StackTrace.ToString());
                            bExceptionOccurred = true;
                        }
                    }

                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("Exception: {0}", ex.Message.ToString());
                    Console.Error.WriteLine("Stack: {0}", ex.StackTrace.ToString());
                    bExceptionOccurred = true;
                }
            });

            mgaProject.Close();

            if (bExceptionOccurred)
                return -1;
            return 0;
        }
        public void InvokeEx(MgaProject project,
                            MgaFCO currentobj,
                            MgaFCOs selectedobjs,
                            int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);

                if (currentobj == null)
                {
                    this.Logger.WriteError("Invalid context. This interpreter can only be run if open in the correct context (E.g., test bench).");
                    return;
                }

                GMEConsole.Out.WriteLine(DateTime.Now.ToString() + " running CyPhyPrepIFab Interpreter");

                //InitLogger();

                // [1] CyPhy2CAD                                 
                // [2] Export DDP, Manufacture XML, Manufacture Manifest
                // [3] Generate AppendArtifact.py - script to append artifacts to testbench_manifest.json files
                // [4] Generate DesignModel1BOM.py - script to generate .bom.json from ddp file
                // [5] Generate main run bat file

                //CallCAD(project, currentobj, selectedobjs, param);                              // CyPhy2CAD                  
                MgaGateway.PerformInTransaction(delegate
                {
                    string kindName = string.Empty;
                    if (currentobj != null)
                    {
                        kindName = currentobj.MetaBase.Name;
                    }

                    if (string.IsNullOrEmpty(kindName) == false && kindName != typeof(CyPhyClasses.TestBench).Name)
                    {
                        Logger.WriteFailed("CyPhyPrepIFAB must be called from a TestBench.");
                        return;
                    }

                    ElaborateModel(project, currentobj, selectedobjs, param);                       // elaborate model        
                    CallCAD(project, currentobj, selectedobjs, param);                              // CyPhy2CAD
                    ManufacturingGeneration(currentobj);                                            // DDP, Manufacture XML, Manufacture Manifest

                },
                transactiontype_enum.TRANSACTION_NON_NESTED);


                GenerateAppendArtifactScript();                                                     // AppendArtifact.py                                               
                GenerateBOMGenScript();                                                             // DesignModel1BOM.py                                                 
                GenerateRunBatFile();                                                               // main run bat file                                            

                GMEConsole.Out.WriteLine("CyPhyPrepIFab Interpreter Finished!");
            }
            catch (Exception)
            {
                Logger.WriteError("{0} has finished with critical errors. Please see above.", this.ComponentName);   
            }

            finally
            {
                //Trace.Close();
                MgaGateway = null;
                if (Logger != null) Logger.Dispose();
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public static int Main( String[] args ) {

            if( args.Length < 2 || args.Length > 4 ) usage();

            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();
                    rOptionUsed = true;

                    if ( ++ix >= args.Length ) usage();

                    if( avmFilePath != null && avmFilePath != "" ) {
                        if( mgaProjectPath != null && mgaProjectPath != "" ) usage();
                        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();
                    pOptionUsed = true;

                    if ( ++ix >= args.Length ) usage();
                    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();
                    mgaProjectPath = args[ ix ];
                }

            }


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

                    mgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
                    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);
                        bExceptionOccurred = importer.Errors.Count > 0;
                    });

                    mgaProject.Save();

                    if (mgaGateway.territory != null)
                    {
                        mgaGateway.territory.Destroy();
                    }

                    if (bExceptionOccurred)
                    {
                        return -1;
                    }
                }
            }
            finally
            {
                mgaProject.Close(true);
            }
            return 0;
        }
        public static int Main( String[] args ) {

            if( args.Length < 1 ) {
                Console.Out.WriteLine( "Usage: <program> CyPhyMLFile.mga [-f] [outputDirectory]" );
                Environment.Exit( 1 );
            }

            MgaProject mgaProject = null;

            string outputDirectory = ".";
            bool flat = false;

            for( int ix = 0; ix < args.Length; ++ix ) {
                if( args[ ix ] == "-f" ) {
                    flat = true;
                } else if ( mgaProject == null ) {
                    mgaProject = GetProject( args[ ix ] );
                } else {
                    outputDirectory = args[ ix ];
                }
            }

            if ( mgaProject == null ) {
                Console.Out.WriteLine( "Usage: <program> CyPhyMLFile.mga [-f] [outputDirectory]" );
                Environment.Exit( 1 );
            }

            MgaGateway mgaGateway = new MgaGateway( mgaProject );

            bool bExceptionOccurred = false;

            mgaGateway.PerformInTransaction( delegate {
                try {
                    CyPhyML.RootFolder cyPhyMLRootFolder = ISIS.GME.Common.Utils.CreateObject<CyPhyMLClasses.RootFolder>( mgaProject.RootFolder );
                    HashSet<CyPhyML.Component> cyPhyMLComponentSet = CyPhy2ComponentModel.ComponentLister.getCyPhyMLComponentSet( cyPhyMLRootFolder );

                    var ruleChecker = new DesignConsistencyChecker.Framework.Checker(null, mgaProject);
                    ruleChecker.RegisterRuleDll("DesignConsistencyChecker.dll");
                    var uniqueNameRule = ruleChecker.GetRegisteredRules.FirstOrDefault(x => x.Name == "UniquePPMNames");

                    int i_Counter = 1;
                    foreach (var cyPhyMLComponent  in cyPhyMLComponentSet)
                        {
                            try
                            {
                                if (uniqueNameRule != null)
                                {
                                    var feedBacks = uniqueNameRule.Check((MgaFCO)cyPhyMLComponent.Impl).ToList();
                                    if (feedBacks.Any(x => x.FeedbackType == FeedbackTypes.Error))
                                    {
                                        foreach (var fb in feedBacks.Where(x => x.FeedbackType == FeedbackTypes.Error))
                                        {
                                            Console.Error.WriteLine("Rule {0} failed: {1}", uniqueNameRule.Name, fb.Message);
                                        }
                                        continue;
                                    }
                                }

                                //foreach (CyPhyML.Component cyPhyMLComponent in cyPhyMLComponentList) {
                                avm.Component avmComponent = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(cyPhyMLComponent);
                                string componentPath = null;

                                if (flat) {
                                    componentPath = outputDirectory;
                                } else {
                                    componentPath = cyPhyMLComponent.Path;
                                    componentPath = outputDirectory + "/" + componentPath.Substring(componentPath.IndexOf("/"));
                                }

                                Directory.CreateDirectory(componentPath);

                                if (!flat) {
                                    Directory.CreateDirectory(componentPath + "/images");
                                    //Directory.CreateDirectory( componentPath + "/CyPhyML" );
                                    Directory.CreateDirectory(componentPath + "/doc");
                                    Directory.CreateDirectory(componentPath + "/CAD");
                                }

                                String s_outFilePath = String.Format("{0}/{1}.component.acm", componentPath, Safeify(cyPhyMLComponent.Name));
                                using (FileStream stream = new FileStream(s_outFilePath, FileMode.Create))
                                {
                                    XSD2CSharp.AvmXmlSerializer.Serialize(avmComponent, stream);
                                    stream.Close();
                                }
                                    
                                Console.Out.WriteLine(string.Format("({0}/{1}) {2}", i_Counter++, cyPhyMLComponentSet.Count, Safeify(cyPhyMLComponent.Name)));
                                //}
                            } catch( Exception ex ) {
                                Console.Error.WriteLine( "Exception: {0}", ex.Message.ToString() );
                                Console.Error.WriteLine( "Stack: {0}", ex.StackTrace.ToString() );
                                bExceptionOccurred = true;
                            }
                        }
                    
                } catch( Exception ex ) {
                    Console.Error.WriteLine( "Exception: {0}", ex.Message.ToString() );
                    Console.Error.WriteLine("Stack: {0}", ex.StackTrace.ToString());
                    bExceptionOccurred = true;
                }
            }, abort: false );

            mgaProject.Close();

            if (bExceptionOccurred)
                return -1;
            return 0;
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                if (currentobj == null)
                {
                    // TODO: Add Ballistic TB here once supported.
                    this.GMEConsole.Error.Write("CyPhyMultiJobRun must be called from either a BlastTestBench, CFDTestBench, or BallisticTestBench.");
                    return;
                }

                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);
                string kindName = null;
                MgaGateway.PerformInTransaction(delegate 
                {
                    kindName = currentobj.MetaBase.Name;
                });

                if (kindName == "CFDTestBench" || kindName == "BlastTestBench" || kindName == "BallisticTestBench")
                {
                }
                else
                {
                    this.GMEConsole.Error.Write("CyPhyMultiJobRun must be called from either a BlastTestBench or CFDTestBench, not '{0}'", kindName);
                    return;
                }

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                if (MgaGateway != null && MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #9
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                MgaGateway = new MgaGateway(project);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                }, abort: false);
            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            this.mainParameters = (InterpreterMainParameters)parameters;

            try
            {
                MgaGateway = new MgaGateway(mainParameters.Project);

                var result = new InterpreterResult() { Success = true, RunCommand = "" };

                MgaGateway.PerformInTransaction(delegate
                {
                    MainInTransaction((InterpreterMainParameters)parameters);


                    // TODO: this part needs to be refactored!
                    var workflowRef = this.mainParameters
                        .CurrentFCO
                        .ChildObjects
                        .OfType<MgaReference>()
                        .FirstOrDefault(x => x.Meta.Name == "WorkflowRef");
                    
                    if (workflowRef != null)
                    {
                        string Parameters = workflowRef
                            .Referred
                            .ChildObjects
                            .OfType<MgaAtom>()
                            .FirstOrDefault(fco => fco.Meta.Name == typeof(CyPhy.Task).Name
                                && String.Equals(CyPhyClasses.Task.Cast(fco).Attributes.COMName, this.ComponentProgID, StringComparison.InvariantCultureIgnoreCase))
                            .StrAttrByName["Parameters"];

                        Dictionary<string, string> workflowParameters = new Dictionary<string, string>();

                        try
                        {
                            workflowParameters = (Dictionary<string, string>)Newtonsoft.Json.JsonConvert.DeserializeObject(Parameters, typeof(Dictionary<string, string>));
                            if (workflowParameters == null)
                            {
                                workflowParameters = new Dictionary<string, string>();
                            }
                        }
                        catch (Newtonsoft.Json.JsonReaderException)
                        {
                        }

                        META.AnalysisTool.ApplyToolSelection(this.ComponentProgID, workflowParameters, result, this.mainParameters);
                    }
                });

                return result;
            }
            finally
            {
                MgaGateway = null;                
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public bool RunInTransaction(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, string outputDirectory=null)
        {
            bool success = false;
            bool shouldDisposeLogger = false;

            try
            {
                MgaGateway = new MgaGateway(project);

                // populate a test model
                /*MgaGateway.PerformInTransaction(delegate
                {
                    currentobj = GenerateTestModel(project, currentobj);
                }, transactiontype_enum.TRANSACTION_NON_NESTED);*/

                if (this.Logger == null)
                {
                    this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);
                    this.Logger.LoggingLevel = this.Logger.GMEConsoleLoggingLevel = this.Convert(param) == ComponentStartMode.GME_SILENT_MODE ?
                        CyPhyGUIs.SmartLogger.MessageType_enum.Warning :
                        CyPhyGUIs.SmartLogger.MessageType_enum.Info;
                    shouldDisposeLogger = true;
                }

                HashSet<string> m_addonNames = new HashSet<string>()
                {
                    "ConstraintManager".ToLowerInvariant(),
                    "CyPhyAddOn".ToLowerInvariant(),
                    "CyPhyDecoratorAddon".ToLowerInvariant(),
                    "CyPhyMdaoAddOn".ToLowerInvariant(),
                    "CyPhySignalBlocksAddOnAddon".ToLowerInvariant(),
                    "ComponentLibraryManagerAddOn".ToLowerInvariant()
                };

                // turn off all addons specified above
                var addons = project.AddOnComponents.Cast<IMgaComponentEx>();
                foreach (var addon in addons)
                {
                    if (addon.ComponentName.ToLowerInvariant() == "CyPhyAddOn".ToLowerInvariant())
                    {
                        addon.ComponentParameter["DontAssignGuidsOnNextTransaction".ToLowerInvariant()] = true;
                    }

                    if (m_addonNames.Contains(addon.ComponentName.ToLowerInvariant()))
                    {
                        try
                        {
                            addon.Enable(false);
                        }
                        catch (Exception ex)
                        {
                            // if one fails keep trying the other ones.
                            this.Logger.WriteError("Turing off addon failed: {0} --> {1}", addon.ComponentName, ex.ToString());
                        }
                    }
                }

                try
                {
                    MgaGateway.PerformInTransaction(delegate
                    {
                        success = this.Main(project, currentobj, selectedobjs, this.Convert(param));

                        if (String.IsNullOrEmpty(outputDirectory) == false)
                        {
                            UpdateMetricsInTestbenchManifest(currentobj, outputDirectory);
                        }
                    },
                    transactiontype_enum.TRANSACTION_NON_NESTED);

                    // call old elaborator
                    ////this.CallOldElaborator(project, currentobj);
                }
                catch (Exception ex)
                {
                    this.Logger.WriteDebug(ex.ToString());
                    success = false;
                }
                finally
                {
                    foreach (var addon in addons)
                    {
                        if (m_addonNames.Contains(addon.ComponentName.ToLowerInvariant()))
                        {
                            try
                            {
                                addon.Enable(true);
                            }
                            catch (Exception ex)
                            {
                                // if one fails keep trying the other ones.
                                this.Logger.WriteError("Turing off addon failed: {0} --> {1}", addon.ComponentName, ex.ToString());
                            }
                        }
                    }
                }
            }
            finally
            {
                if (shouldDisposeLogger &&
                    this.Logger != null)
                {
                    this.Logger.Dispose();
                }

                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return success;
        }
        public bool checkForPortErasure() {

            bool retval = false;

            MgaProject mainMgaProject = GetProject(Path.Combine(META.VersionInfo.MetaPath, "test", "GenericSubtreeSwapTest", "Models", "TopLevelPortDeleteTest", "Master.mga"));

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

            MgaGateway mgaGateway = new MgaGateway(mainMgaProject);

            mainMgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
            mgaGateway.PerformInTransaction(delegate {
                MgaFCO currentObject = mainMgaProject.get_ObjectByPath("/DesignSpace ricardoSystemAssembly/ricardoSystemAssembly/SubsystemToReplace/pin_n_alternator") as MgaFCO;
                retval = currentObject == null;
            });

            return retval;
        }
        public bool checkForErasure() {

            bool retval = false;

            MgaProject mainMgaProject = GetProject(Path.Combine(META.VersionInfo.MetaPath, "test", "GenericSubtreeSwapTest", "Models", "MergeOverwriteTest", "Master.mga"));
            try
            {

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

                MgaGateway mgaGateway = new MgaGateway(mainMgaProject);

                mainMgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
                mgaGateway.PerformInTransaction(delegate
                {
                    MgaFCO currentObject = mainMgaProject.get_ObjectByPath("/DesignSpace ricardoSystemAssembly/ricardoSystemAssembly/SubsystemToReplace/ShouldBeErased") as MgaFCO;
                    retval = currentObject == null;
                });
            }
            finally
            {
                mainMgaProject.Close();
            }

            return retval;
        }
Example #14
0
        public void ProjectManifestPopulationTest()
        {
            var testPath = Path.Combine(Common._importModelDirectory, "ProjectManifestPopulation");
            var xmePath = Path.Combine(testPath, "InputModel.xme");

            var pathGeneratedManifest = Path.Combine(testPath, "manifest.project.json");
            // Delete manifest, if it exists
            if (File.Exists(pathGeneratedManifest))
                File.Delete(pathGeneratedManifest);

            var mgaFilename = Path.ChangeExtension(xmePath, "mga");
            GME.MGA.MgaUtils.ImportXME(xmePath, mgaFilename);

            var mgaProject = Common.GetProject( mgaFilename );
            Assert.True(mgaProject != null,"Could not load MGA project.");

            AVM.DDP.MetaAvmProject proj = null;
            bool resultIsNull = false;
            var mgaGateway = new MgaGateway(mgaProject);
            mgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
            mgaGateway.PerformInTransaction(delegate {
                var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                importer.Initialize(mgaProject);

                var result = importer.ImportFile(mgaProject,testPath,Path.Combine(testPath,"InputModel.component.acm"));
                if (result == null)
                    resultIsNull = true;

                // Load manifest while we're in a transaction
                proj = AVM.DDP.MetaAvmProject.Create(mgaProject);
            });
            Assert.False(resultIsNull,"Exception occurred during import.");
            Assert.False(File.Exists(pathGeneratedManifest), "Manifest erroneously generated");
        }
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            this.mainParameters = (InterpreterMainParameters)parameters;

            try
            {
                MgaGateway = new MgaGateway(mainParameters.Project);
                parameters.Project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                MgaGateway.PerformInTransaction(delegate
                {
                    MainInTransaction((InterpreterMainParameters)parameters);
                });
                return new InterpreterResult() { Success = true, RunCommand = "" };
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;                
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);
                this.Logger = new CyPhyGUIs.GMELogger(project, this.GetType().Name);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                });
            }
            finally
            {
                if (Logger != null)
                {
                    Logger.Dispose();
                }
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                Logger = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #17
0
        //[Fact]
        public void DesignSpaceWithRefs()
        {
            var fullTestPath = Path.Combine(_exportModelDirectory, "DesignSpaceWithRefs");
            var xmeFilePath = Path.Combine(fullTestPath, "DesignSpaceWithRefs.xme");
            var pathExportedDesign = Path.Combine(fullTestPath, "DesignSpace.adm");

            // delete design file if it already exists
            if (File.Exists(pathExportedDesign))
            {
                File.Delete(pathExportedDesign);
            }

            String connectionString;
            GME.MGA.MgaUtils.ImportXMEForTest(xmeFilePath, out connectionString);

            var proj = new MgaProject();
            bool ro_mode;
            proj.Open(connectionString, out ro_mode);
            proj.EnableAutoAddOns(true);

            try
            {
                var designExporter = new CyPhyDesignExporter.CyPhyDesignExporterInterpreter();
                designExporter.Initialize(proj);

                var mgaGateway = new MgaGateway(proj);
                MgaFCO currentFCO = null;
                mgaGateway.PerformInTransaction(delegate
                {
                    currentFCO = proj.get_ObjectByPath("/@DesignSpaces|kind=DesignSpace|relpos=0/@DesignSpace|kind=DesignContainer|relpos=0") as MgaFCO;
                    Assert.NotNull(currentFCO);
                });

                var parameters = new CyPhyGUIs.InterpreterMainParameters()
                {
                    CurrentFCO = currentFCO,
                    Project = proj,
                    OutputDirectory = fullTestPath
                };

                var result = designExporter.Main(parameters);

                var design = avm.Design.LoadFromFile(pathExportedDesign);

                /// Add assert statements to check structure
                var root = design.RootContainer;
                Assert.NotNull(root);

                Assert.Equal(1, root.Container1.Count(c => c.Name == "AltContainer"));
                var AltContainer = root.Container1.First(c => c.Name == "AltContainer");

                Assert.Equal(1, AltContainer.ComponentInstance.Count(ci => ci.Name == "CompA_5"));
                Assert.Equal(1, AltContainer.ComponentInstance.Count(ci => ci.Name == "CompA_6"));
                Assert.Equal(1, AltContainer.ComponentInstance.Count(ci => ci.Name == "CompA_7"));

                Assert.Equal(1, root.Container1.Count(c => c.Name == "DesignContainer"));
                var DesignContainer = root.Container1.First(c => c.Name == "DesignContainer");

                Assert.Equal(1, DesignContainer.ComponentInstance.Count(ci => ci.Name == "CompA3"));

                Assert.Equal(1, DesignContainer.Container1.Count(c => c.Name == "Assembly1"));
                var Assembly1 = DesignContainer.Container1.First(c => c.Name == "Assembly1");

                Assert.Equal(1, Assembly1.ComponentInstance.Count(ci => ci.Name == "CompA1"));
                Assert.Equal(1, Assembly1.ComponentInstance.Count(ci => ci.Name == "CompA2"));

                Assert.Equal(1, root.Container1.Count(c => c.Name == "ReusableContainer"));
                var ReusableContainer = root.Container1.First(c => c.Name == "ReusableContainer");

                Assert.Equal(1, ReusableContainer.Container1.Count(c => c.Name == "Assembly4"));
                var Assembly4 = ReusableContainer.Container1.First(c => c.Name == "Assembly4");

                Assert.Equal(1, Assembly4.ComponentInstance.Count(ci => ci.Name == "CompA1"));
                Assert.Equal(1, Assembly4.ComponentInstance.Count(ci => ci.Name == "CompA2"));

                Assert.Equal(1, ReusableContainer.ComponentInstance.Count(ci => ci.Name == "CompA4"));

                Assert.Equal(1, root.ComponentInstance.Count(ci => ci.Name == "CompA"));

                Assert.Equal(1, root.ComponentInstance.Count(ci => ci.Name == "CompA"));
            }
            finally
            {
                proj.Close();
            }
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                },
                abort: true);
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);

                MgaGateway = new MgaGateway(project);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                }, abort: false);
            }
            finally
            {
                if (this.Logger != null)
                {
                    this.Logger.Dispose();
                    this.Logger = null;
                }

                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #20
0
        public void merge(MgaFCO currentObject, string filename) {

            _currentMgaProject = currentObject.Project;

            MgaProject mgaProject = GetProject(filename, currentObject.Project.MetaName);

            if (mgaProject == null)
                return;
            try
            {

                _projectFilename = filename;

                MgaGateway mgaGateway = new MgaGateway(mgaProject);

                mgaGateway.PerformInTransaction(delegate
                {

                    // "DO" LOOP IS ONLY TO ALLOW "break" TO TERMINATE THIS INTERPRETER
                    do
                    {

                        int origPrefs = _currentMgaProject.Preferences;
                        // Magic word allows us to remove ConnPoints
                        _currentMgaProject.Preferences = origPrefs | (int)GME.MGA.preference_flags.MGAPREF_IGNORECONNCHECKS | (int)GME.MGA.preference_flags.MGAPREF_FREEINSTANCEREFS;

                        try
                        {
                            // GET FCO TO BE MERGED FROM OTHER MGA FILE
                            IMgaFCO otherCurrentObject = mgaProject.get_ObjectByPath(currentObject.AbsPath) as IMgaFCO;
                            if (otherCurrentObject == null)
                            {
                                gmeConsole.Error.WriteLine("Could not perform merge:  could not find object of path \"" + currentObject.AbsPath + "\" in file \"" + filename + "\"");
                                _exitStatus |= Errors.PathError;
                                break;
                            }

                            recordConnections(otherCurrentObject);

                            // GET PARENT (IN CURRENT MODEL) OF THE FCO TO BE MERGED INTO THE CURRENT MODEL
                            MgaObject currentParentMGAObject = null;
                            GME.MGA.Meta.objtype_enum currentParentObjTypeEnum;
                            currentObject.GetParent(out currentParentMGAObject, out currentParentObjTypeEnum);


                            // THE ROOT OF THE MERGED FCO
                            IMgaFCO newCurrentObject = null;

                            IMgaFCO otherArchetype = otherCurrentObject.ArcheType;
                            if (otherArchetype != null)
                            {

                                MgaFCO newArchetype = mgaProject.get_ObjectByPath(otherArchetype.AbsPath) as MgaFCO;
                                if (newArchetype == null)
                                {
                                    gmeConsole.Error.WriteLine("Could not find object of path \"" + otherArchetype.AbsPath + "\" (archetype of \"" + otherCurrentObject.AbsPath + "\" in file \"" + filename + "\") in current model.");
                                    _exitStatus |= Errors.PathError;
                                    break;
                                }

                                if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER)
                                {
                                    newCurrentObject = (currentParentMGAObject as MgaFolder).DeriveRootObject(newArchetype, otherCurrentObject.IsInstance);
                                }
                                else if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL)
                                {
                                    newCurrentObject = (currentParentMGAObject as MgaModel).DeriveChildObject(newArchetype, otherCurrentObject.MetaRole, otherCurrentObject.IsInstance);
                                }
                                else
                                {
                                    gmeConsole.Error.WriteLine("Unable to merge \"" + otherCurrentObject.AbsPath + "\" of file \"" + filename + "\":  prospective parent neither a folder nor a model.");
                                    _exitStatus |= Errors.GMEError;
                                    break;
                                }

                                attributesAndRegistryCopy(newCurrentObject, otherCurrentObject);
                                connectionCopy();

                            }
                            else
                            {

                                if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER)
                                {
                                    newCurrentObject = (currentParentMGAObject as MgaFolder).CreateRootObject(currentObject.Meta);
                                }
                                else if (currentParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL)
                                {
                                    newCurrentObject = (currentParentMGAObject as MgaModel).CreateChildObject(currentObject.MetaRole);
                                }
                                else
                                {
                                    gmeConsole.Error.WriteLine("Unable to merge \"" + otherCurrentObject.AbsPath + "\" of file \"" + filename + "\":  prospective parent neither a folder nor a model.");
                                    _exitStatus |= Errors.GMEError;
                                    break;
                                }

                                subTreeCopy(newCurrentObject, otherCurrentObject);
                                instanceCopy();
                                attributesAndRegistryCopy(newCurrentObject, otherCurrentObject);
                                referenceCopy();
                                connectionCopy();
                                //referenceConnectionCopy();
                            }
                        }
                        finally
                        {
                            _currentMgaProject.Preferences = origPrefs;
                        }


                    } while (false);

                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);

                currentObject.DestroyObject();
            }
            finally
            {
                mgaProject.Close(true);
            }
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE;

                //bool runNewImplementationOnly = true;
                //runNewImplementationOnly = false;

                //if (runNewImplementationOnly)
                //{
                //    this.NewMasterInterpreterImplementationFull(currentobj);
                //    return;
                //}

                List<IMgaFCO> objectsToCheck = new List<IMgaFCO>();
                List<IMgaFCO> objectsToGetConfigurations = new List<IMgaFCO>();

                MgaGateway.PerformInTransaction(() =>
                {
                    if (currentobj == null)
                    {
                        var allObjects = project
                           .RootFolder
                           .ChildFolders
                           .Cast<MgaFolder>()
                           .Where(x => x.Name.StartsWith("0"))
                           .SelectMany(x => x.GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>())
                           .Where(x => x.RootFCO == x);

                        // get all objects from folders starts with 0 within the root folder.
                        objectsToCheck.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingContextChecker")));

                        objectsToGetConfigurations.AddRange(allObjects.Where(x => x.AbsPath.Contains("TestingGetConfigurations")));
                    }
                    else
                    {
                        objectsToCheck.Add(currentobj);
                        //objectsToGetConfigurations.Add(currentobj);
                    }

                    objectsToCheck.Sort((x, y) =>
                    {
                        return x.Meta.Name.CompareTo(y.Meta.Name) != 0 ?
                            x.Meta.Name.CompareTo(y.Meta.Name) :
                            x.AbsPath.CompareTo(y.AbsPath);
                    });
                });




                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

                sw.Start();

                int numContexts = objectsToCheck.Count;
                int numSuccess = 0;
                int numFailures = 0;

                StringBuilder sbAssumptions = new StringBuilder();

                sbAssumptions.Append("Implemented".PadToCenter(11));
                sbAssumptions.Append("Valid".PadToCenter(11));
                sbAssumptions.Append("Context".PadToCenter(30));
                sbAssumptions.Append("Assumption");
                sbAssumptions.AppendLine();

                foreach (var subject in objectsToCheck)
                {
                    var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI();

                    IEnumerable<CyPhyMasterInterpreter.Rules.ContextCheckerResult> contextCheckerResults = null;

                    // check context
                    var checkerSuccess = masterInterpreter.TryCheckContext(subject as MgaModel, out contextCheckerResults);

                    List<CyPhyMasterInterpreter.Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList();

                    // sort results Passed, Failed, then alphabetically based on message.
                    sortedResults.Sort((x, y) => { return x.Success == y.Success ? x.Message.CompareTo(y.Message) : y.Success.CompareTo(x.Success); });


                    // print out nicely in the GME console
                    MgaGateway.PerformInTransaction(() =>
                    {
                        MgaObject parent = null;
                        GME.MGA.Meta.objtype_enum type;
                        subject.GetParent(out parent, out type);

                        var successExpected = parent.Name.ToLowerInvariant() == "invalid" ? false : true;

                        sbAssumptions.AppendFormat("{0}{1}{2}{3}",
                            (successExpected == checkerSuccess).ToString().PadToCenter(11),
                            successExpected.ToString().PadToCenter(11),
                            subject.Meta.Name.PadToCenter(30),
                            subject.Name.ToSentenceCase());

                        sbAssumptions.AppendLine();

                        if (successExpected == checkerSuccess)
                        {
                            numSuccess++;
                            //GMEConsole.Info.WriteLine("OK");
                            if (currentobj != null)
                            {
                                foreach (var result in sortedResults)
                                {
                                    TextWriter tw = null;
                                    StringBuilder sb = new StringBuilder();
                                    if (result.Success)
                                    {
                                        sb.Append("[<b style=\"color:darkgreen\">Passed</b>]");
                                        tw = GMEConsole.Info;
                                    }
                                    else
                                    {
                                        sb.Append("[<b style=\"color:red\">Failed</b>]");
                                        tw = GMEConsole.Error;
                                    }

                                    sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name);

                                    sb.Append(result.Message);

                                    tw.WriteLine(sb);
                                }
                            }
                        }
                        else
                        {
                            foreach (var result in sortedResults)
                            {
                                TextWriter tw = null;
                                StringBuilder sb = new StringBuilder();
                                if (result.Success)
                                {
                                    sb.Append("[<b style=\"color:darkgreen\">Passed</b>]");
                                    tw = GMEConsole.Info;
                                }
                                else
                                {
                                    sb.Append("[<b style=\"color:red\">Failed</b>]");
                                    tw = GMEConsole.Error;
                                }

                                sb.AppendFormat(" <i><a href=\"mga:{0}\">{1}</a></i> ", result.Subject.ID, result.Subject.Name);

                                sb.Append(result.Message);

                                tw.WriteLine(sb);
                            }

                            numFailures++;
                            GMEConsole.Error.WriteLine("========= FAILED ==========");
                            GMEConsole.Error.WriteLine("= {0}", subject.Name);
                            GMEConsole.Error.WriteLine("= {0}", subject.AbsPath);
                            GMEConsole.Error.WriteLine("===========================");
                        }


                    });

                    if (currentobj != null)
                    {
                        CyPhyMasterInterpreter.AnalysisModelProcessor analysisModelProcessor = null;

                        MgaGateway.PerformInTransaction(() =>
                        {
                            analysisModelProcessor = CyPhyMasterInterpreter.AnalysisModelProcessor.GetAnalysisModelProcessor(subject as MgaModel);
                        });

                        GMEConsole.Info.WriteLine("AnalysisProcessor type: {0}", analysisModelProcessor.GetType().Name);
                        GMEConsole.Info.WriteLine("Interpreters: {0}", string.Join(", ", analysisModelProcessor.Interpreters));
                        GMEConsole.Info.WriteLine("InterpretersToConfigure: {0}", string.Join(", ", analysisModelProcessor.InterpretersToConfiguration));

                        MgaFCO configuration = null;
                        configuration = masterInterpreter.GetConfigurations(subject as MgaModel).Cast<MgaFCO>().FirstOrDefault();

                        var results = masterInterpreter.RunInTransaction(subject as MgaModel, configuration, keepTempModels: true);

                        MgaGateway.PerformInTransaction(() =>
                        {
                            foreach (var result in results)
                            {
                                TextWriter tw = null;
                                StringBuilder sb = new StringBuilder();
                                if (result.Success)
                                {
                                    sb.Append("[<b style=\"color:darkgreen\">Passed</b>]");
                                    tw = GMEConsole.Info;
                                }
                                else
                                {
                                    sb.Append("[<b style=\"color:red\">Failed</b>]");
                                    tw = GMEConsole.Error;
                                }

                                sb.AppendFormat(" <i>{0}</i> {1} ", result.Context.Name, result.Configuration.Name);

                                sb.Append(result.Message);

                                tw.WriteLine(sb);
                            }
                        });
                    }

                }

                File.WriteAllText("master_interpreter_assumptions.txt", sbAssumptions.ToString());

                foreach (var subject in objectsToGetConfigurations)
                {
                    var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI();

                    // we are not checking the models again, these test models must be valid enough to get configurations from them

                    var configurations = masterInterpreter.GetConfigurations(subject as MgaModel);

                    // print out nicely in the GME console
                    MgaGateway.PerformInTransaction(() =>
                    {
                        GMEConsole.Info.WriteLine("{0} has {1} configurations.", subject.Name, configurations.Count);
                        //GMEConsole.Info.WriteLine("- {0}", string.Join(", ", configurations.Cast<MgaFCO>().Select(x => x.Name)));
                    });

                    //CyPhyMasterInterpreter.MasterInterpreterResult[] masterInterpreterResults = null;

                    //using (var progressDialog = new CyPhyMasterInterpreter.ProgressDialog())
                    //{
                    //    masterInterpreter.MultipleConfigurationProgress += progressDialog.MultipleConfigurationProgressHandler;
                    //    masterInterpreter.SingleConfigurationProgress += progressDialog.SingleConfigurationProgressHandler;

                    //    progressDialog.ShowWithDisabledMainWindow();

                    //    masterInterpreterResults = masterInterpreter.RunInTransaction(subject as IMgaModel, configurations);
                    //}
                }

                GMEConsole.Info.WriteLine("ContextChecks: {0}", numContexts);
                GMEConsole.Info.WriteLine("Successful   : {0}", numSuccess);
                GMEConsole.Info.WriteLine("Failures     : {0}", numFailures);

                if (numContexts == numSuccess)
                {
                    GMEConsole.Info.WriteLine("ALL GREEN :-)");
                }
                else
                {
                    GMEConsole.Error.WriteLine("You need to work more on the code...");
                }

                GMEConsole.Info.WriteLine(
                    "Duration: {0}.",
                    sw.Elapsed.ToString("c"));

            }
            finally
            {
                System.Windows.Forms.Application.DoEvents();

                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
 public static void PerformInTransaction(this MgaProject project, MgaGateway.voidDelegate del)
 {
     var mgaGateway = new MgaGateway(project);
     project.CreateTerritoryWithoutSink(out mgaGateway.territory);
     mgaGateway.PerformInTransaction(del);
 }
Example #23
0
 public static void PerformInTransaction(this MgaProject project, MgaGateway.voidDelegate del)
 {
     var mgaGateway = new MgaGateway(project);
     mgaGateway.PerformInTransaction(del, abort: false);
 }
        public void InvokeEx(MgaProject project,
                            MgaFCO currentobj,
                            MgaFCOs selectedobjs,
                            int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                //ComponentIndex ci = new ComponentIndex();
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);

                if (currentobj == null)
                {
                    this.Logger.WriteError("Invalid context. This interpreter can only be run if open in the correct context (E.g., test bench).");
                    return;
                }

                GMEConsole.Out.WriteLine(DateTime.Now.ToString() + " running CyPhyCADAnalysis Interpreter");

                //InitLogger();

                // [1] create avmproj
                string projectName = "";
                MgaGateway.PerformInTransaction(delegate
                {
                    projectName = project.Name;
                },
                transactiontype_enum.TRANSACTION_NON_NESTED);

                // META-3080: use passed in project directory, especially in SOTs where .mga file is in a different directory than manifest.project.json
                if (String.IsNullOrEmpty(this.ProjectRootDirectory))
                    this.ProjectRootDirectory = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
                string avmProjFileName = Path.Combine(this.ProjectRootDirectory, "manifest.project.json");
                //string avmProjFileName = Path.Combine(Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)), "manifest.project.json");
                //this.ProjectRootDirectory = Path.GetDirectoryName(avmProjFileName);
                AVM.DDP.MetaAvmProject avmProj = new AVM.DDP.MetaAvmProject();

                if (File.Exists(avmProjFileName))
                {
                    string sjson = "{}";
                    using (StreamReader reader = new StreamReader(avmProjFileName))
                    {
                        sjson = reader.ReadToEnd();
                        avmProj = JsonConvert.DeserializeObject<AVM.DDP.MetaAvmProject>(sjson);
                        this.AVMComponentList = avmProj.Project.Components;
                    }
                }
                // end create avmproj


                // [1] CyPhy2CAD                                 
                // [2] Export DDP, Manufacture XML, Manufacture Manifest
                // [3] Generate AppendArtifact.py - script to append artifacts to testbench_manifest.json files
                // [4] Generate DesignModel1BOM.py - script to generate .bom.json from ddp file
                // [5] Generate main run bat file

                //CallCAD(project, currentobj, selectedobjs, param);                              // CyPhy2CAD                  
                MgaGateway.PerformInTransaction(delegate
                {
                    string kindName = string.Empty;
                    if (currentobj != null)
                    {
                        kindName = currentobj.MetaBase.Name;
                    }

                    if (string.IsNullOrEmpty(kindName) == false && kindName != typeof(CyPhyClasses.TestBench).Name)
                    {
                        Logger.WriteFailed("CyPhyCADAnalysis must be called from a TestBench.");
                        return;
                    }


                    ElaborateModel(project, currentobj, selectedobjs, param);                       // elaborate model        
                    CallCAD(project, currentobj, selectedobjs, param);                              // CyPhy2CAD
                    CallComponentExporter(project, currentobj, selectedobjs, param);                // JS: 7-15-13

                    ManufacturingGeneration(currentobj);                                            // DDP, Manufacture XML, Manufacture Manifest
                },
                transactiontype_enum.TRANSACTION_NON_NESTED);


                GenerateAppendArtifactScript();                                                     // AppendArtifact.py                                               
                GenerateBOMGenScript();                                                             // DesignModel1BOM.py                                                 
                //GenerateAnalysisFilesScript(wkflow_param);

                GenerateRunBatFile();                                                               // main run bat file                                            

                GMEConsole.Out.WriteLine("CyPhyCADAnalysis Interpreter Finished!");
            }

            catch (Exception ex)
            {
                Logger.WriteError("{0} has finished with critical errors. Please see above.", this.ComponentName);
                Logger.WriteError("Error Message: {0}", ex.Message);
            }
            finally
            {
                if (Logger!=null) Logger.Dispose();
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            Trace.Flush();
            Trace.Close();
        }
        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);
            }
        }