/// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a tansaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     if (Logger == null)
         Logger = new CyPhyGUIs.GMELogger(project, ComponentName);
     MgaGateway = new MgaGateway(project);
     project.CreateTerritoryWithoutSink(out MgaGateway.territory);       
 }
Esempio n. 2
0
        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));
                });
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        /// <summary>
        /// This function is called for each interpreter invocation before Main.
        /// Don't perform MGA operations here unless you open a transaction.
        /// </summary>
        /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
        public void Initialize(MgaProject project)
        {
            // TODO: Add your initialization code here...  

            GMEConsole = GMEConsole.CreateFromProject(project);
            MgaGateway = new MgaGateway(project);
            project.CreateTerritoryWithoutSink(out MgaGateway.territory);
        }
Esempio n. 4
0
        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));
                },
                                                transactiontype_enum.TRANSACTION_NON_NESTED);
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                //ISIS.GME.Common.Utils.ObjectCache.Clear();


                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
        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();
            }
        }
Esempio n. 6
0
        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.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();
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                if (Logger != null) Logger.Dispose();
                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
            {
                if (Logger == null)
                {
                    Logger = new GMELogger(project, ComponentName);
                }
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                this.mainParameters = new InterpreterMainParameters()
                {
                    Project = project,
                    CurrentFCO = currentobj as MgaFCO,
                    SelectedFCOs = selectedobjs,
                    StartModeParam = param
                };

                Main(this.mainParameters);

                //this.PrintRuntimeStatistics();
            }
            catch (Exception ex)
            {
                Logger.WriteError("Exception: {0}<br> {1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                if (MgaGateway != null &&
                    MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null; 
                DisposeLogger();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        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);
            }
        }
 /// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a transaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     InitializeLogger(project);
     MgaGateway = new MgaGateway(project);
     project.CreateTerritoryWithoutSink(out MgaGateway.territory);
 }
Esempio n. 10
0
        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);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);
                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 (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                if (Logger!=null) Logger.Dispose();
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            Trace.Flush();
            Trace.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);

                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();
            }
        }
Esempio n. 12
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            if (currentobj == null) {
                MessageBox.Show("Please select the subtree to be replaced (via merge) so that it is displayed in the main window.");
                return;
            }

            currentMgaProject = project;

            try
            {
                gmeConsole = new FlexConsole(FlexConsole.ConsoleType.GMECONSOLE, project);
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                gmeConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Esempio n. 13
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);
                proj.CreateTerritoryWithoutSink(out mgaGateway.territory);
                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);

                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 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();
            }
        }
        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();
            }
        }
Esempio n. 17
0
 /// <summary>
 /// This function is called for each interpreter invocation before Main.
 /// Don't perform MGA operations here unless you open a tansaction.
 /// </summary>
 /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param>
 public void Initialize(MgaProject project)
 {
     //GMEConsole = GMEConsole.CreateFromProject(project);
     MgaGateway = new MgaGateway(project);
     project.CreateTerritoryWithoutSink(out MgaGateway.territory);
 }
        public void InvokeEx(
                MgaProject project,
                MgaFCO currentobj,
                MgaFCOs selectedobjs,
                int param)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (selectedobjs == null)
            {
                throw new ArgumentNullException("selectedobjs");
            }

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

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

                this.GMEConsole.Clear();
                System.Windows.Forms.Application.DoEvents();

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

                this.Logger = new CyPhyGUIs.GMELogger(project, this.GetType().Name);

                this.Logger.GMEConsoleLoggingLevel = Properties.Settings.Default.bVerboseLogging ?
                    CyPhyGUIs.SmartLogger.MessageType_enum.Debug :
                    CyPhyGUIs.SmartLogger.MessageType_enum.Info;

                //this.Logger.WriteDebug("Hello debug");
                //this.Logger.WriteError("Hello error {0} {1} {2}", 1, "string", true);
                //this.Logger.WriteInfo("Hello info");
                //this.Logger.WriteWarning("Hello WriteWarning");
                //this.Logger.WriteFailed("Hello WriteFailed");
                //this.Logger.WriteSuccess("Hello WriteSuccess");
                //this.Logger.WriteCheckFailed("Hello WriteCheckFailed");
                //this.Logger.WriteCheckPassed("Hello WriteCheckPassed");

                this.Logger.WriteInfo("Master Interpreter 2.0");
                System.Windows.Forms.Application.DoEvents();

                this.Logger.MakeVersionInfoHeader();

                // control was held
                this.Process(currentobj);

                foreach (var filename in this.Logger.LogFilenames)
                {
                    this.Logger.WriteInfo("Log file was generated here: <a href=\"file:///{0}\" target=\"_blank\">{1}</a>", Path.GetDirectoryName(filename), filename);
                }

                this.Logger.WriteInfo("Master Interpreter 2.0 finished");
            }
            finally
            {
                this.Logger.Dispose();
                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();
            }
        }
Esempio n. 19
0
        public bool RunInTransaction(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            bool success = false;
            bool shouldDisposeLogger = false;

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

                // 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));
                    },
                    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();
                }

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

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

            return success;
        }