/// <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);       
 }
        public IInterpreterResult Main(IInterpreterMainParameters parameters)
        {
            this.mainParameters = (InterpreterMainParameters)parameters;

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

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

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


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

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

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

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

                return result;
            }
            finally
            {
                MgaGateway = null;                
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        /// <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);
        }
Example #4
0
        static int Main(string[] args) {

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

            MgaProject mainMgaProject = GetProject( args[0] );

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

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

            mainMgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
            mgaGateway.PerformInTransaction(delegate {

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

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

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

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

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

            });

            mainMgaProject.Save();

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

            return retval;
        }
        /// <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)
        {
            // TODO: Add your initialization code here...   
            Contract.Requires(project != null);

            GMEConsole = GMEConsole.CreateFromProject(project);
            MgaGateway = new MgaGateway(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);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                },
                abort: true);
            }
            finally
            {
                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public static int Main( String[] args ) {

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

            MgaProject mgaProject = null;

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

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

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

            MgaGateway mgaGateway = new MgaGateway( mgaProject );

            bool bExceptionOccurred = false;

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

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

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

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

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

                                Directory.CreateDirectory(componentPath);

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

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

            mgaProject.Close();

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

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                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();
            }
        }
Example #9
0
 public static void PerformInTransaction(this MgaProject project, MgaGateway.voidDelegate del)
 {
     var mgaGateway = new MgaGateway(project);
     mgaGateway.PerformInTransaction(del, abort: false);
 }
Example #10
0
        public void merge(MgaFCO currentObject, string filename) {

            _currentMgaProject = currentObject.Project;

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

            if (mgaProject == null)
                return;
            try
            {

                _projectFilename = filename;

                MgaGateway mgaGateway = new MgaGateway(mgaProject);

                mgaGateway.PerformInTransaction(delegate
                {

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

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

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

                            recordConnections(otherCurrentObject);

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


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

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

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

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

                                attributesAndRegistryCopy(newCurrentObject, otherCurrentObject);
                                connectionCopy();

                            }
                            else
                            {

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

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


                    } while (false);

                }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false);

                currentObject.DestroyObject();
            }
            finally
            {
                mgaProject.Close(true);
            }
        }
 /// <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)
 {
     GMEConsole = GMEConsole.CreateFromProject(project);
     MgaGateway = new MgaGateway(project);
 }
Example #12
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 (!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();
            }
        }
Example #14
0
        public static int Main(string[] args)
        {
            var options = new Options();
            if (!Parser.Default.ParseArguments(args, options)) return -1;

            var project = GetProject(options.MgaFile);

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

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

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


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

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

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

                        #endregion

                        #region Process DesignEntities

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

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

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

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

                if (bExceptionOccurred)
                    return -1;

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

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                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();
            }
        }
 /// <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)
 {
     MgaGateway = new MgaGateway(project);
 }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

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


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

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

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

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

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

                        connected = ConnectToMetaLinkBridge(project, param);
                    }

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

                //GMEConsole.Out.WriteLine("End of CyPhySync interpreter...");
            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (this.enabled == false)
            {
                return;
            }

            try
            {
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);
                // Need to call this interpreter in the same way as the MasterInterpreter will call it.
                // initialize main parameters

                if (currentobj == null)
                {
                    this.Logger.WriteError("CyPhy2Modelica_v2 must be invoked on a Test Bench.");
                    return;
                }

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

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

                // set up the output directory
                MgaGateway.PerformInTransaction(delegate
                {
                    string outputDirName = project.Name;
                    if (currentobj != null)
                    {
                        outputDirName = currentobj.Name;
                    }

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

                    //this.Parameters.PackageName = Modelica.Factory.GetModifiedName(currentobj.Name);
                });

                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(CyPhy2Modelica_v2Settings),
                    this.ComponentProgID);

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

                if (config == null)
                {
                    this.Logger.WriteWarning("Operation cancelled by the user.");
                    return;
                }

                // 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
            {
                if (this.Logger != null)
                {
                    this.Logger.Dispose();
                    this.Logger = null;
                }
                if (MgaGateway != null &&
                    MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = 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);
                MgaGateway = new MgaGateway(project);

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #20
0
        public void ProjectManifestPopulationTest()
        {
            var testPath = Path.Combine(Common._importModelDirectory, "ProjectManifestPopulation");
            var xmePath = Path.Combine(testPath, "InputModel.xme");

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

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

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

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

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

                // Load manifest while we're in a transaction
                proj = AVM.DDP.MetaAvmProject.Create(mgaProject);
            });
            Assert.False(resultIsNull,"Exception occurred during import.");
            Assert.False(File.Exists(pathGeneratedManifest), "Manifest erroneously generated");
        }
Example #21
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);

                Main(project, currentobj, selectedobjs, Convert(param));
            }
            finally
            {
                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)
 {
     InitializeLogger(project);
     MgaGateway = new MgaGateway(project);
     project.CreateTerritoryWithoutSink(out MgaGateway.territory);
 }
        public static int Main( String[] args ) {

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

            MgaProject mgaProject;
            List<String> lp_FilesToImport = new List<string>();
            string avmFilePath = "";
            string mgaProjectPath = "";
            string componentReplacementPath = "";

            bool rOptionUsed = false;
            bool pOptionUsed = false;

            for( int ix = 0 ; ix < args.Length ; ++ix ) {

                if( args[ ix ].ToLower() == "-r" ) {

                    if( pOptionUsed ) usage();
                    rOptionUsed = true;

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

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

                    String sImportDirectory = args[ ix ];

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

                    foreach( String p_XMLFile in xmlFiles ) {
                        lp_FilesToImport.Add( Path.GetFullPath( p_XMLFile ) );
                    }

                } else if( args[ ix ].ToLower() == "-p" ) {

                    if( rOptionUsed ) usage();
                    pOptionUsed = true;

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

                } else if ( lp_FilesToImport.Count == 0 && avmFilePath == "" ) {

                    avmFilePath = args[ ix ];
                    try
                    {
                        lp_FilesToImport.Add(Path.GetFullPath(avmFilePath));
                    }
                    catch (System.ArgumentException ex)
                    {
                        Console.Out.WriteLine(ex.Message);
                        Console.Out.WriteLine(avmFilePath);
                        throw ex;
                    }

                } else {

                    if( mgaProjectPath != null && mgaProjectPath != "" ) usage();
                    mgaProjectPath = args[ ix ];
                }

            }


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

                    mgaProject.CreateTerritoryWithoutSink(out mgaGateway.territory);
                    mgaGateway.PerformInTransaction(delegate
                    {

                        string libroot = Path.GetDirectoryName(Path.GetFullPath(mgaProjectPath));

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

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

                        bool needAttach = false;
                        if (oldQudt == null)
                        {

                            needAttach = true;

                        }
                        else
                        {

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

                        if (needAttach)
                        {

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

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

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

                    mgaProject.Save();

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

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

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

                MgaGateway = new MgaGateway(project);

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

                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
 public static void PerformInTransaction(this MgaProject project, MgaGateway.voidDelegate del)
 {
     var mgaGateway = new MgaGateway(project);
     project.CreateTerritoryWithoutSink(out mgaGateway.territory);
     mgaGateway.PerformInTransaction(del);
 }
        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
            {
                //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();
        }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                // Create a new instance of the logger
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);

                if (currentobj == null)
                {
                    this.Logger.WriteFailed("CyPhyReliabilityAnalysis must be called from a Test Bench.");
                    return;
                }

                // Need to call this interpreter in the same way as the MasterInterpreter will call it.
                // initialize main parameters
                var parameters = new InterpreterMainParameters()
                {
                    Project = project,
                    CurrentFCO = currentobj,
                    SelectedFCOs = selectedobjs,
                    StartModeParam = param,
                    VerboseConsole = true
                };

                this.mainParameters = parameters;
                parameters.ProjectDirectory = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length));

                // Set up the output directory and check kind of currentObj.
                string kindName = string.Empty;
                MgaGateway.PerformInTransaction(delegate
                {
                    string outputDirName = project.Name;
                    if (currentobj != null)
                    {
                        outputDirName = currentobj.Name;
                        kindName = currentobj.MetaBase.Name;
                    }

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

                if (string.IsNullOrEmpty(kindName) == false && kindName != "TestBench")
                {
                    this.Logger.WriteFailed("CyPhyReliabilityAnalysis must be called from a Test Bench.");
                    return;
                }

                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(CyPhyReliabilityAnalysisSettings),
                    this.ComponentProgID);

                // get interpreter config through GUI
                var config = this.DoGUIConfiguration(preConfig, previousConfig);
                if (config == null)
                {
                    this.Logger.WriteWarning("Operation cancelled by the user.");
                    return;
                }

                //#region CyPhy2Modelica_v2Configuration

                //var cyPhy2Modelica_v2 = new META.ComComponent("MGA.Interpreter.CyPhy2Modelica_v2");
                //if (cyPhy2Modelica_v2.DoGUIConfiguration(parameters.ProjectDirectory) == false)
                //{
                //    this.Logger.WriteWarning("Operation cancelled by the user.");
                //    return;
                //}
                //#endregion

                // TODO: put here any other interpreters that we have to call.

                // 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
            {
                if (this.Logger != null)
                {
                    this.Logger.Dispose();
                    this.Logger = null;
                }
                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 (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();
            }
        }
        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();
            }
        }