Exemplo n.º 1
0
        public myMigrator(MgaProject p)
        {
            project = p;
            GMEConsole = GMEConsole.CreateFromProject(p);
            oldToNewRole = new Dictionary<string, string>()
            {
                { "StructuralInterface" , "Connector" },
                {"AxisGeometry", "Axis"},
                {"SurfaceGeometry", "Surface"},
                {"PointGeometry", "Point"},
                {"CoordinateSystemGeometry", "CoordinateSystem"},
                {"StructuralInterfaceForwarder", "Connector"},
                {"FeatureMap", "PortComposition"},
                {"AnalysisPointMap", "PortComposition"},
                {"AnalysisPoint", "Point"},
                {"JoinStructures", "ConnectorComposition"},
                //{"FeatureMap", "SurfaceReverseMap"}, //special, not general case
                //{"CADModel", ""}, //special, addition not replacement
            };
            oldToNewFCO = new Dictionary<MgaFCO, MgaFCO>();
            oldConnsAndRefs = new List<MgaFCO>();
            oldSubsAndInstances = new List<MgaFCO>();
            migratedModels = new List<MgaModel>();

            foreach (MgaFolder child in project.RootFolder.ChildFolders)
                if (child.MetaFolder.Name == "Components")
                {
                    List<MgaFolder> folders = getAllFolders(child);
                    foreach (MgaFolder folder in folders)
                        foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                            createNewFCOs(model);
                }
        }
Exemplo n.º 2
0
        //[System.Diagnostics.DebuggerStepThrough]
        //[System.Diagnostics.DebuggerNonUserCode] // enable Just My Code in debugger settings
        public static GMEConsole CreateFromProject(GME.MGA.MgaProject project)
        {
            GMEConsole console = new GMEConsole();

            /* if (System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName).Contains("xunit")
            || System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName).Contains(".vshost"))
            || {
            ||  console.normal = new CyPhyGUIs.ConsoleTextWriter();
            ||  return console;
            || } */
            // Initializing console
            var gme = project.Clients.Cast <MGA.MgaClient>().Where(c => c.Name == "GME.Application").FirstOrDefault();

            if (gme != null)
            {
                console.gme = (IGMEOLEApp)gme.OLEServer;
            }
            else
            {
                // if GME is not present, the interpreter is called from standalone test application
                console.gme = null;

                console.normal = new CyPhyGUIs.ConsoleTextWriter();
            }
            //catch (ArgumentException ex)
            //{
            //    // missing paramter exception
            //    console.gme = null;

            //    console.normal = new CyPhyGUIs.ConsoleTextWriter();
            //}

            return(console);
        }
Exemplo n.º 3
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));
                },
                abort: true);
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Makes a GME hyperlink for the specified object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="console"></param>
        /// <param name="subject"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string MakeObjectHyperlink <T>(
            this GMEConsole console,
            T subject,
            string text)
            where T : IMgaObject
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<a href=\"mga:");
            sb.Append(subject.ID);
            sb.Append("\">");
            sb.Append(text);
            sb.Append("</a>");
            return(sb.ToString());
        }
Exemplo n.º 5
0
        public static GMEConsole CreateFromProject(GME.MGA.MgaProject project)
        {
            GMEConsole console = new GMEConsole();

            try
            {
                // Initializing console
                console.gme = (IGMEOLEApp)project.GetClientByName("GME.Application").OLEServer;
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                // if GME is not present, the interpreter is called from standalone test application
                if (ex.ErrorCode != -2023423888)                 // HResult 0x87650070: "Search by name failed"
                {
                    throw;
                }
                console.gme = null;
            }
            return(console);
        }
Exemplo n.º 6
0
 public GMETextWriter(msgtype_enum type, GMEConsole console)
 {
     this.type    = type;
     this.console = console;
 }
        public void InvokeEx(
                            MgaProject project, 
                            MgaFCO currentobj, 
                            MgaFCOs selectedobjs, 
                            int param)
        {
            if (!enabled)
            {
                return;
            }

            if (currentobj == null)
            {
                GMEConsole.Error.WriteLine("Please select a CADTestBench, Ballistic Testbench, FEA Testbench, Blast Testbench or CadAssembly.");
                return;
            }

            string currentWorkDir = System.IO.Directory.GetCurrentDirectory();

            try
            {
                var parameters = new InterpreterMainParameters();
                this.mainParameters = parameters;
                parameters.ProjectDirectory = Path.GetDirectoryName(currentobj.Project.ProjectConnStr.Substring("MGA=".Length));

                FetchSettings();

                // Show UI
                using (MainForm mf = new MainForm(settings))
                {
                    mf.ShowDialog();
                    DialogResult ok = mf.DialogResult;
                    if (ok == DialogResult.OK)
                    {
                        settings = mf.ConfigOptions;
                        parameters.OutputDirectory = settings.OutputDirectory;
                        parameters.config = settings;
                    }
                    else
                    {
                        GMEConsole.Warning.WriteLine("Process was cancelled.");
                        return;
                    }
                }

                SaveSettings();

                MgaGateway.PerformInTransaction(delegate
                {
                    Elaborate(project, currentobj, selectedobjs, param);
                    Main(project, currentobj, selectedobjs, Convert(param));
                },
                abort: true);


            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Exemplo n.º 8
0
 public AVMDesignImporter(GMEConsole console, IMgaProject project, object messageConsoleParameter = null)
     : base(CyPhyClasses.RootFolder.GetRootFolder((MgaProject)project), messageConsoleParameter)
 {
     projroot = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));
     init(true);
 }
        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();
            }
        }
        private void TriggerQudtRefreshIfNeeded()
        {
            if (!firstTime)
            {
                // put the arguments into private variables where they can be reached by the timer code
                if (GMEConsole == null)
                {
                    GMEConsole = GMEConsole.CreateFromProject(project);
                }
#if DEBUG
                GMEConsole.Info.WriteLine("CyPhySignalBlocksAddOn starting up...");
#endif

                //GMEConsole.Info.WriteLine(eventMask.ToString());
                if (!componentEnabled)
                {
                    GMEConsole.Info.WriteLine("CyPhySignalBlocksAddOn not enabled...");
                    return;
                }

                // First, check to see whether the libraries have already been loaded
                //CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.RootFolder>(rf as MgaObject);

                IMgaFolder rootFolder = project.RootFolder;
                IMgaFolders subFolders = rootFolder.ChildFolders;

                // META-1320: refactored some
                // Run this on any event, but only once (if not already loaded)
                QudtLibraryInfo.Go();
                PortLibraryInfo.Go(); // portLibTimer.go();
                MaterialLibraryInfo.Go();
                CADResourceLibraryInfo.Go();

                firstTime = true;
            }
        }
Exemplo n.º 11
0
 public Migrator(MgaProject project)
 {
     GMEConsole = GMEConsole.CreateFromProject(project);
     dfco_OldToNewMap = new Dictionary<MgaFCO, MgaFCO>();
     //SeedPortMap(project);
     getObjectsByFilter(project);
 }
        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 UnzipToTemp(GMEConsole console)
 {
     GMEConsole = console;
 }
Exemplo n.º 14
0
        public FlexConsole(ConsoleType consoleType, MgaProject mgaProject = null) {

            switch (consoleType) {
                case ConsoleType.NONE:
                    _info = _warning = _error = _out = new NullTextWriter();
                    break;
                case ConsoleType.CONSOLE:
                    _info = _warning = _error = Console.Error;
                    _out = Console.Out;
                    break;
                case ConsoleType.GMECONSOLE:
                    _gmeConsole = GMEConsole.CreateFromProject(mgaProject);
                    _info = _gmeConsole.Info;
                    _warning = _gmeConsole.Warning;
                    _error = _gmeConsole.Error;
                    _out = _gmeConsole.Out;
                    break;
            }

        }
Exemplo n.º 15
0
        private void CallElaboratorAndMain(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            string keyName = @"HKEY_LOCAL_MACHINE\Software\META";
            string value = @"META_PATH";

            META_PATH = (string)Microsoft.Win32.Registry.GetValue(
                keyName,
                value,
                "ERROR: " + keyName + value + " does not exist!");

            GMEConsole = GMEConsole.CreateFromProject(project);

            #region Elaborate the TestBench
            // call elaborator and expand the references
            Type t = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate");
            IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx;
            elaborator.Initialize(project);
            elaborator.ComponentParameter["automated_expand"] = "true";
            elaborator.ComponentParameter["console_messages"] = "off";
            elaborator.InvokeEx(project, currentobj, selectedobjs, (int)ComponentStartMode.GME_SILENT_MODE);
            #endregion

            MgaGateway.PerformInTransaction(delegate
            {
                Main(project, currentobj, selectedobjs, Convert(param));
            });
        }
Exemplo n.º 16
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }
            if (currentobj == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                GMEConsole.Warning.WriteLine("Please run in the context of a TestBench");
                return;
            }

            // Make sure running within the context of a testbench
            bool inTBContext = false;
            MgaGateway.PerformInTransaction(delegate
            {
                if (currentobj.Meta.Name == "TestBench")
                {
                    inTBContext = true;
                }
            });
            if (!inTBContext)
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                GMEConsole.Warning.WriteLine("Please run in the context of a TestBench");
                return;
            }

            // Need to get an output path from the user.
            using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog())
            {
                fbd.Description = "Choose a path for the generated files.";
                //fbd.ShowNewFolderButton = true;
                DialogResult dr = fbd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    OutputDirectory = fbd.SelectedPath;
                }
                else
                {
                    GMEConsole = GMEConsole.CreateFromProject(project);
                    GMEConsole.Out.WriteLine("CyPhyComplexity: Operation cancelled");
                    return;
                }
            }

            try
            {
                CallElaboratorAndMain(project, currentobj, selectedobjs, param);
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Exemplo n.º 17
0
        private void CallElaboratorAndMain(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            META_PATH = META.VersionInfo.MetaPath;

            GMEConsole = GMEConsole.CreateFromProject(project);

            #region Elaborate the TestBench
            // call elaborator and expand the references
            Type t = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate");
            IMgaComponentEx elaborator = Activator.CreateInstance(t) as IMgaComponentEx;
            elaborator.Initialize(project);
            elaborator.ComponentParameter["automated_expand"] = "true";
            elaborator.ComponentParameter["console_messages"] = "off";
            elaborator.InvokeEx(project, currentobj, selectedobjs, (int)ComponentStartMode.GME_SILENT_MODE);
            #endregion

            MgaGateway.PerformInTransaction(delegate
            {
                Main(project, currentobj, selectedobjs, Convert(param));
            });
        }
        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();
            }
        }
Exemplo n.º 19
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

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

                MgaGateway.BeginTransaction();
                Main(project, currentobj, selectedobjs, Convert(param));
                MgaGateway.AbortTransaction();
            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Exemplo n.º 20
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();
            }
        }
Exemplo n.º 21
0
 public static GMEConsole CreateFromProject(GME.MGA.MgaProject project)
 {
     GMEConsole console = new GMEConsole();
     try
     {
         // Initializing console               
         console.gme = (IGMEOLEApp)project.GetClientByName("GME.Application").OLEServer;
     }
     catch (System.Runtime.InteropServices.COMException ex)
     {
         // if GME is not present, the interpreter is called from standalone test application
         if (ex.ErrorCode != -2023423888) // HResult 0x87650070: "Search by name failed"
         {
             throw;
         }
         console.gme = null;
     }
     return console;
 }
Exemplo n.º 22
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 void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Exemplo n.º 24
0
 public GMETextWriter(msgtype_enum type, GMEConsole console)
 {
     this.type = type;
     this.console = console;
 }
        /// <summary>
        /// Called when an FCO or folder changes
        /// </summary>
        /// <param name="subject">the object the event(s) happened to</param>
        /// <param name="eventMask">objectevent_enum values ORed together</param>
        /// <param name="param">extra information provided for cetertain event types</param>
        public void ObjectEvent(MgaObject subject, uint eventMask, object param)
        {
            if (!componentEnabled)
            {
                return;
            }

            if (subject.HasReadOnlyAccess())
            {
                return;
            }

            if (GMEConsole == null)
            {
                GMEConsole = GMEConsole.CreateFromProject(subject.Project);
            }

            // TODO: Handle object events (OR eventMask with the members of objectevent_enum)
            // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask
            uint uOBJEVENT_ATTR = 0;
            uint uOBJEVENT_CREATED = 0;
            uint uOBJEVENT_NEWCHILD = 0;
            uint uOBJEVENT_LOSTCHILD = 0;
            uint uOBJEVENT_OPENMODEL = 0;

            unchecked { uOBJEVENT_ATTR = (uint)objectevent_enum.OBJEVENT_ATTR; }
            unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; }
            unchecked { uOBJEVENT_NEWCHILD = (uint)objectevent_enum.OBJEVENT_NEWCHILD; }
            unchecked { uOBJEVENT_LOSTCHILD = (uint)objectevent_enum.OBJEVENT_LOSTCHILD; }
            unchecked { uOBJEVENT_OPENMODEL = (uint)objectevent_enum.OBJEVENT_OPENMODEL; }

            if ((eventMask & uOBJEVENT_CREATED) != 0)
            {
                if (subject.IsLibObject || subject.IsWritable == false)
                    return;
                if (subject.MetaBase.Name == "TestBenchRef")
                {
                    // set the port label lenght 0
                    // FIXME: why not just change it in the meta?
                    (subject as MgaFCO).RegistryValue["portLabelLength"] = "0";
                    if (subject as MgaReference != null)
                    {
                        UpdateColor((subject as MgaReference).Referred);
                    }
                }
                else if (subject.MetaBase.Name == "Optimizer")
                {
                    (subject as MgaFCO).RegistryValue["portLabelLength"] = "0";
                    UpdateColor(subject as MgaFCO);
                }
                else if (subject.MetaBase.Name == "VariableSweep")
                {
                    (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow";
                    (subject as MgaFCO).RegistryValue["color"] = "0xff80c0";
                }
                else if (subject.MetaBase.Name == "ObjectiveMapping")
                {
                    (subject as MgaFCO).RegistryValue["dstStyle"] = "arrow";
                    (subject as MgaFCO).RegistryValue["color"] = "0x7cadde";
                }
            }
            else if ((eventMask & uOBJEVENT_ATTR) != 0)
            {
                this.DisplayPCCIterations(subject, true);

                if (subject.MetaBase.Name == "ValueFlow")
                {
                    // set the src custom formula's name to the specified name
                    // in the ValueFlow attribute field
                    MgaConnection ValueFlow = subject as MgaConnection;
                    foreach (MgaConnPoint cp in ValueFlow.ConnPoints)
                    {
                        if (cp.ConnRole == "src")
                        {
                            if (cp.Target.Meta.Name == "CustomFormula")
                            {
                                foreach (MgaAttribute attr in ValueFlow.Attributes)
                                {
                                    if (attr.Meta.Name == "FormulaVariableName")
                                    {
                                        if (string.IsNullOrEmpty(attr.StringValue) == false)
                                        {
                                            cp.Target.Name = attr.StringValue;
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                else if (subject.MetaBase.Name == "TestBench")
                {
                    // Excel import helper
                    MgaModel testBench = subject as MgaModel;

                    // call color helper
                    UpdateColor(testBench as MgaFCO);
                }
            }
            else if ((eventMask & uOBJEVENT_NEWCHILD) != 0 || (eventMask & uOBJEVENT_LOSTCHILD) != 0)
            {
                this.DisplayPCCIterations(subject, false);
            }
            else if ((eventMask & uOBJEVENT_OPENMODEL) != 0)
            {
            if (subject.MetaBase.Name == "ParametricExploration")
            {
                var pet = subject as MgaModel;
                foreach (MgaModel PCCDriver in pet.GetChildrenOfKind("PCCDriver"))
                {
                    var upMethod = PCCDriver.StrAttrByName["PCC_UP_Methods"];
                    if (upMethod == "UP_MPP" || upMethod == "UP_PCE")
                    {
                        GMEConsole.Out.WriteLine("{1}The output of the selected method ({0}) is not compatible with the project analyzer Dashboard.", upMethod, WARNING_BADGE);
                        if (upMethod == "UP_PCE")
                        {
                            GMEConsole.Out.WriteLine("{0}Trying to display such data might require a refresh in order to view other data again.", WARNING_BADGE);
                        }
                    }
                }
            }
            }
            //MessageBox.Show(eventMask.ToString());

        }
Exemplo n.º 26
0
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                if (currentobj == null)
                {
                    GMEConsole.Error.WriteLine("No model opened.");
                    return;
                }

                var parameters = new InterpreterMainParameters()
                {
                    Project = project,
                    CurrentFCO = currentobj,
                    SelectedFCOs = selectedobjs,
                    VerboseConsole = true
                };

                parameters.ProjectDirectory = Path.GetDirectoryName(currentobj.Project.ProjectConnStr.Substring("MGA=".Length));

                MgaGateway.PerformInTransaction(delegate
                {
                    string outputDirName = project.Name;
                    if (currentobj != null)
                    {
                        outputDirName = currentobj.Name;
                    }

                    parameters.OutputDirectory = Path.GetFullPath(Path.Combine(
                        parameters.ProjectDirectory,
                        "results",
                        outputDirName));
                });

                PreConfigArgs preConfigArgs = new PreConfigArgs();
                preConfigArgs.ProjectDirectory = parameters.ProjectDirectory;

                // call the preconfiguration with no parameters and get preconfig
                var preConfig = this.PreConfig(preConfigArgs);

                // get previous GUI config
                var previousConfig = META.ComComponent.DeserializeConfiguration(parameters.ProjectDirectory,
                    typeof(CyPhyCarSettings),
                    this.ComponentProgID);

                // get interpreter config through GUI
                var config = this.DoGUIConfiguration(preConfig, previousConfig);

                // if config is valid save it and update it on the file system
                META.ComComponent.SerializeConfiguration(parameters.ProjectDirectory, config, this.ComponentProgID);

                // assign the new configuration to mainParameters
                parameters.config = config;


                // call the main (ICyPhyComponent) function
                this.Main(parameters);


            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Exemplo n.º 27
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);
                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();
        }
 /// <summary>
 /// Called when an FCO or folder changes
 /// </summary>
 /// <param name="subject">the object the event(s) happened to</param>
 /// <param name="eventMask">objectevent_enum values ORed together</param>
 /// <param name="param">extra information provided for cetertain event types</param>
 public void ObjectEvent(MgaObject subject, uint eventMask, object param)
 {
     // TODO: Handle object events (OR eventMask with the members of objectevent_enum)
     // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask
     if (GMEConsole == null)
     {
         GMEConsole = GMEConsole.CreateFromProject(project);
     }
     TriggerQudtRefreshIfNeeded();
 }