Example #1
0
        public static ISIS.GME.Common.Interfaces.FCO CastReferred(
            MgaReference mgaReference,
            Dictionary <int, Type> metaRefTypes,
            string kind)
        {
            Contract.Requires(mgaReference != null);

            IMgaFCO referred = mgaReference.Referred;

            if (referred == null)
            {
                return(null);
            }
            else
            {
                ISIS.GME.Common.Interfaces.FCO result = null;
                Type t;
                if (metaRefTypes.TryGetValue(referred.MetaBase.MetaRef, out t) == false)
                {
                    // backwards compat dictates that this exception must be KeyNotFoundException
                    throw new System.Collections.Generic.KeyNotFoundException(String.Format("Tried to retrieve Referred.{0}, but the referred object is \"{1}\", which does not inherit from \"{0}\"", kind, referred.MetaBase.Name));
                }
                result = Activator.CreateInstance(t) as ISIS.GME.Common.Interfaces.FCO;
                (result as ISIS.GME.Common.Classes.FCO).Impl = referred as IMgaObject;
                return(result);
            }
        }
Example #2
0
        private String GetLayout(IMgaFCO fco)
        {
            Boolean hasAllAspect = false;

            foreach (IMgaPart part in fco.Parts)
            {
                if (part.MetaAspect.Name == "All")
                {
                    hasAllAspect = true;
                }
            }

            foreach (IMgaPart part in fco.Parts)
            {
                if (part.MetaAspect.Name == "All" || hasAllAspect == false)
                {
                    String icon;
                    int    xpos = 0;
                    int    ypos = 0;
                    part.GetGmeAttrs(out icon, out xpos, out ypos);

                    return(String.Format("{0},{1}", xpos, ypos));
                }
            }

            return("");
        }
Example #3
0
        public static IEnumerable <ISIS.GME.Common.Interfaces.FCO> CastReferencedBy(
            IMgaFCO IMgaFCO,
            Dictionary <int, Type> dictionary)
        {
            Contract.Requires(IMgaFCO != null);

            int metaRef;

            ISIS.GME.Common.Interfaces.FCO fco = null;

            foreach (IMgaFCO item in IMgaFCO.ReferencedBy)
            {
                try
                {
                    metaRef = item.MetaBase.MetaRef;
                    Type type = null;
                    if (dictionary.TryGetValue(metaRef, out type))
                    {
                        // can be casted to the requested type
                        fco = Activator.CreateInstance(type) as ISIS.GME.Common.Interfaces.FCO;
                        (fco as ISIS.GME.Common.Classes.FCO).Impl = item as IMgaObject;
                    }
                    else
                    {
                        // cannot be casted to DSML types
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                yield return(fco);
            }
        }
Example #4
0
 internal static void SetAspects(IMgaFCO impl, IEnumerable <Aspect> value)
 {
     Contract.Requires(impl != null);
     if (impl.ParentModel != null)
     {
         foreach (var aspect in value)
         {
             MgaPart part = impl.Parts.Cast <MgaPart>().FirstOrDefault(x => x.MetaAspect.Name == aspect.Name);
             if (part == null)
             {
                 throw new ArgumentOutOfRangeException(String.Format(
                                                           "{0} aspect was not found for {1} object.",
                                                           aspect.Name,
                                                           impl.Meta.Name));
             }
             else
             {
                 Aspect newValue = new Aspect(impl, aspect.Name);
                 newValue.Icon = aspect.Icon;
                 newValue.X    = aspect.X;
                 newValue.Y    = aspect.Y;
             }
         }
     }
 }
Example #5
0
        public void ImportOldITARStatement_ITAR()
        {
            // There should be only an ITAR object, with attribute set to ITAR
            var acmPath = Path.Combine(testPath, "ITAR.oldstyle.acm");

            IMgaFCO fco = null;

            proj.PerformInTransaction(delegate
            {
                var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                importer.Initialize(fixture.proj);
                fco = importer.ImportFiles(fixture.proj, fixture.proj.GetRootDirectoryPath(), new[] { acmPath }, doNotReplaceAll: true)[1];
            });

            proj.PerformInTransaction(delegate
            {
                var comp = CyPhyClasses.Component.Cast(fco);

                var itarCollection = comp.Children.ITARCollection;
                Assert.True(itarCollection.Count() == 1);

                var itar = itarCollection.First();
                Assert.True(itar.Attributes.RestrictionLevel == CyPhyClasses.ITAR.AttributesClass.RestrictionLevel_enum.ITAR);

                Assert.False(comp.Children.DoDDistributionStatementCollection.Any());
            });
        }
Example #6
0
        // RECORD ALL CONNECTIONS AND ALL OBJECTS THAT HAVE CONNECTIONS
        public void recordConnections(IMgaFCO otherCurrentObject)
        {
            if (otherCurrentObject.PartOfConns.Count != 0)
            {
                _hasConnectionList.Add(otherCurrentObject);
            }
            if (otherCurrentObject is IMgaReference)
            {
                IMgaReference otherReference = (IMgaReference)otherCurrentObject;
                if (otherReference.UsedByConns.Count > 0)
                {
                    _hasConnectionList.Add(otherReference);
                }
            }

            if (otherCurrentObject.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL)
            {
                return;
            }
            foreach (MgaObject otherChildMgaObject in otherCurrentObject.ChildObjects)
            {
                if (otherChildMgaObject.MetaBase.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION)
                {
                    _iMgaConnectionSet.Add(otherChildMgaObject as IMgaConnection);
                    continue;
                }

                recordConnections(otherChildMgaObject as IMgaFCO);
            }
        }
Example #7
0
        public void ImportOldITARStatement_ITARDistributionD()
        {
            // There should be both an ITAR element and a DistributionD element
            var acmPath = Path.Combine(testPath, "DistD.oldstyle.acm");

            IMgaFCO fco = null;

            proj.PerformInTransaction(delegate
            {
                var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                importer.Initialize(fixture.proj);

                fco = importer.ImportFiles(fixture.proj, fixture.proj.GetRootDirectoryPath(), new[] { acmPath }, doNotReplaceAll: true)[1];
                importer.DisposeLogger();
            });

            proj.PerformInTransaction(delegate
            {
                var comp = CyPhyClasses.Component.Cast(fco);

                var itarCollection = comp.Children.ITARCollection;
                Assert.True(itarCollection.Count() == 1);

                var itar = itarCollection.First();
                Assert.True(itar.Attributes.RestrictionLevel == CyPhyClasses.ITAR.AttributesClass.RestrictionLevel_enum.ITAR);

                var distStatementCollection = comp.Children.DoDDistributionStatementCollection;
                Assert.True(distStatementCollection.Count() == 1);

                var distStatement = distStatementCollection.First();
                Assert.True(distStatement.Attributes.DoDDistributionStatementEnum == CyPhyClasses.DoDDistributionStatement.AttributesClass.DoDDistributionStatementEnum_enum.StatementD);
            });
        }
Example #8
0
        public void NoCategory()
        {
            String compName = GetCurrentMethodName();

            avm.Component comp = new avm.Component()
            {
                Classifications = null,
                Name            = compName
            };
            String pathComp = Path.Combine(pathTest, comp.Name + ".acm");

            comp.SaveToFile(pathComp);

            IMgaFCO cyphyComp = null;

            proj.PerformInTransaction(delegate
            {
                cyphyComp = importer.ImportFile(proj, pathTest, pathComp);
            });

            String expectedPath = "RootFolder/Components/" + compName;

            proj.PerformInTransaction(delegate
            {
                Assert.NotNull(cyphyComp);
                String pathCyPhyComp = GetSimplePath(cyphyComp as MgaObject);
                Assert.Equal(expectedPath, pathCyPhyComp);
            });
        }
Example #9
0
        public Aspect(IMgaFCO impl, string aspectName = "")
        {
            Contract.Requires(impl != null);

            Impl = impl;
            Name = aspectName;
        }
Example #10
0
        public static int GetEnumItemNumber(IMgaFCO IMgaFCO, string attributeName)
        {
            Contract.Requires(IMgaFCO != null);
            Contract.Requires(IMgaFCO.MetaBase is MgaMetaFCO);
            Contract.Requires(string.IsNullOrEmpty(attributeName) == false);

            try
            {
                MgaMetaFCO       meta = (IMgaFCO.MetaBase as MgaMetaFCO);
                MgaMetaAttribute attr = meta.AttributeByName[attributeName];

                string selectedItemValue = IMgaFCO.Attribute[attr].StringValue;
                int    i = 0;
                foreach (MgaMetaEnumItem item in attr.EnumItems)
                {
                    if (item.Value == selectedItemValue)
                    {
                        return(i);
                    }
                    i++;
                }
                throw new Exception("Attribute / selected item was not found.");
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #11
0
        private void ReportFeedBack(IEnumerable <RuleFeedbackBase> feedBacks, IMgaFCO context, string ruleName, string ruleDescription)
        {
            if (feedBacks.Count() == 0)
            {
                this.Logger.WriteSuccess("{0} : {1} - {2}", context.ToMgaHyperLink(this.Traceability), ruleName, ruleDescription);
                this.NbrOfSuccesses += 1;
            }
            else
            {
                foreach (var feedBack in feedBacks)
                {
                    if (feedBack.FeedbackType == FeedbackTypes.Error)
                    {
                        this.Logger.WriteFailed(feedBack.Message);
                        if (feedBack.InvolvedObjectsByRole != null)
                        {
                            this.Logger.WriteFailed("Involved Objects : ");
                            foreach (var fco in feedBack.InvolvedObjectsByRole)
                            {
                                if (fco != null)
                                {
                                    // TODO: turn object references to valid objects using Traceability map
                                    this.Logger.WriteFailed("[ {0} ]", fco.ToMgaHyperLink(this.Traceability));
                                }
                                else
                                {
                                    this.Logger.WriteError("[ Could not get fco from InvolvedObjectsByRole for this error. (fco was null) ]");
                                }
                            }
                        }

                        this.Success      = false;
                        this.NbrOfErrors += 1;
                    }
                    else if (feedBack.FeedbackType == FeedbackTypes.Warning)
                    {
                        this.Logger.WriteWarning(feedBack.Message);
                        if (feedBack.InvolvedObjectsByRole != null)
                        {
                            this.Logger.WriteWarning("Involved Objects : ");
                            foreach (var fco in feedBack.InvolvedObjectsByRole)
                            {
                                if (fco != null)
                                {
                                    // TODO: turn object references to valid objects using Traceability map
                                    this.Logger.WriteWarning("[ {0} ]", fco.ToMgaHyperLink(this.Traceability));
                                }
                                else
                                {
                                    this.Logger.WriteError("[ Could not get fco from InvolvedObjectsByRole for this error. (fco was null) ]");
                                }
                            }
                        }

                        this.NbrOfWarnings += 1;
                    }
                }
            }
        }
Example #12
0
        private void ReportFeedBack(IEnumerable<RuleFeedbackBase> feedBacks, IMgaFCO context, string ruleName, string ruleDescription)
        {
            if (feedBacks.Count() == 0)
            {
                this.Logger.WriteSuccess("{0} : {1} - {2}", context.ToMgaHyperLink(this.Traceability), ruleName, ruleDescription);
                this.NbrOfSuccesses += 1;
            }
            else
            {
                foreach (var feedBack in feedBacks)
                {
                    if (feedBack.FeedbackType == FeedbackTypes.Error)
                    {
                        this.Logger.WriteFailed(feedBack.Message);
                        if (feedBack.InvolvedObjectsByRole != null)
                        {
                            this.Logger.WriteFailed("Involved Objects : ");
                            foreach (var fco in feedBack.InvolvedObjectsByRole)
                            {
                                if (fco != null)
                                {
                                    // TODO: turn object references to valid objects using Traceability map
                                    this.Logger.WriteFailed("[ {0} ]", fco.ToMgaHyperLink(this.Traceability));
                                }
                                else
                                {
                                    this.Logger.WriteError("[ Could not get fco from InvolvedObjectsByRole for this error. (fco was null) ]");
                                }
                            }
                        }

                        this.Success = false;
                        this.NbrOfErrors += 1;
                    }
                    else if (feedBack.FeedbackType == FeedbackTypes.Warning)
                    {
                        this.Logger.WriteWarning(feedBack.Message);
                        if (feedBack.InvolvedObjectsByRole != null)
                        {
                            this.Logger.WriteWarning("Involved Objects : ");
                            foreach (var fco in feedBack.InvolvedObjectsByRole)
                            {
                                if (fco != null)
                                {
                                    // TODO: turn object references to valid objects using Traceability map
                                    this.Logger.WriteWarning("[ {0} ]", fco.ToMgaHyperLink(this.Traceability));
                                }
                                else
                                {
                                    this.Logger.WriteError("[ Could not get fco from InvolvedObjectsByRole for this error. (fco was null) ]");
                                }
                            }
                        }

                        this.NbrOfWarnings += 1;
                    }
                }
            }
        }
Example #13
0
        public static IEnumerable<IMgaObject> getAncestorsAndSelf(IMgaFCO fco, IMgaObject stopAt = null)
        {
            yield return fco;
            foreach (var parent in getAncestors(fco, stopAt))
            {
                yield return parent;
            }

        }
 private static void WriteLine(Func<string, string, string> f, IMgaFCO a, IMgaFCO b) {
     //if (GMEConsole != null)
     //{
     //    GMEConsole.Out.WriteLine(f(GetLink(a, a.Name), GetLink(b, b.Name)));
     //}
     //else
     {
         Console.Out.WriteLine(  f( a.AbsPath, b.AbsPath )  );
     }
 }
Example #15
0
        public void copyRegistry(IMgaFCO newCurrentObject, IMgaFCO otherCurrentObject)
        {
            MgaRegNodes otherMgaRegNodes = otherCurrentObject.Registry;

            foreach (MgaRegNode otherMgaRegNode in otherMgaRegNodes)
            {
                MgaRegNode newMgaRegNode = newCurrentObject.get_RegistryNode(otherMgaRegNode.Path);
                copyRegistry(newMgaRegNode, otherMgaRegNode);
            }
        }
Example #16
0
 private static void WriteLine(Func <string, string, string> f, IMgaFCO a, IMgaFCO b)
 {
     //if (GMEConsole != null)
     //{
     //    GMEConsole.Out.WriteLine(f(GetLink(a, a.Name), GetLink(b, b.Name)));
     //}
     //else
     {
         Console.Out.WriteLine(f(a.AbsPath, b.AbsPath));
     }
 }
Example #17
0
 public void WriteLine(Func <string, string, string> f, IMgaFCO a, IMgaFCO b)
 {
     if (GMEConsole != null)
     {
         GMEConsole.Out.WriteLine(f(GetLink(a, a.Name), GetLink(b, b.Name)));
     }
     else
     {
         Console.Out.WriteLine(f(getPath(a), getPath(b)));
     }
 }
Example #18
0
 public static IEnumerable <Aspect> GetAspects(IMgaFCO impl)
 {
     Contract.Requires(impl != null);
     if (impl.ParentModel != null)
     {
         foreach (MgaPart part in impl.Parts)
         {
             yield return(new Aspect(impl, part.MetaAspect.Name));
         }
     }
 }
Example #19
0
        /// <summary>
        /// Gets a component's hyperlinked name string for use in GME Logger messages, based on its IMgaFCO object.
        /// </summary>
        /// <param name="defaultString">A default text string that will be shown if the component is null or has no ID.</param>
        /// <param name="myComponent">The IMgaFCO object of the component to be referenced.</param>
        /// <returns>The hyperlinked text, if all is OK; otherwise the defaultString.</returns>
        /// <remarks>Added for MOT-228: Modify SystemC CAT Module messages to use GME-hyperlinks.
        ///
        ///  Instead of accepting CyPhy.Port or CyPhy.Property as an argument, this method accepts an IMgaFCO.
        ///  IMgaFCO objects have the same ID and Name fields. An example of an IMgaFCO object would be a "CyPhy.Port.Impl as IMgaFCO".
        ///
        ///  When calling this function, you can use this code snippet to get an MgaFCO version of a CyPhy object:
        ///         GetHyperlinkStringFromComponent("default", myComponent.Impl as IMgaFCO);
        ///
        /// </remarks>
        /// <see cref="https://metamorphsoftware.atlassian.net/browse/MOT-228"/>

        private static string GetHyperlinkStringFromComponent(string defaultString, IMgaFCO myComponent)
        {
            string rVal = defaultString;

            if ((null != myComponent) && (myComponent.ID.Length > 0) && (myComponent.Name.Length > 0))
            {
                rVal = string.Format("<a href=\"mga:{0}\">{1}</a>",
                                     myComponent.ID,
                                     myComponent.Name);
            }
            return(rVal);
        }
        public string ExportComponentToString(IMgaFCO component)
        {
            if (component.Meta.Name != typeof(Component).Name)
            {
                throw new ApplicationException("Component must be of kind 'Component'");
            }
            var dsmlComponent = new CyPhyClasses.Component();

            dsmlComponent.Impl = component;
            var avmComponentModel = CyPhyML2AVM.AVMComponentBuilder.CyPhyML2AVM(dsmlComponent);

            return(SerializeAvmComponentToString(avmComponentModel));
        }
        public void ExportComponent(IMgaFCO component, String s_outFilePath)
        {
            if (component.Meta.Name != typeof(Component).Name)
            {
                throw new ApplicationException("Component must be of kind 'Component'");
            }
            var dsmlComponent = new CyPhyClasses.Component();

            dsmlComponent.Impl = component;
            var avmComponentModel = CyPhyML2AVM.AVMComponentBuilder.CyPhyML2AVM(dsmlComponent);

            SerializeAvmComponent(avmComponentModel, s_outFilePath);
        }
Example #22
0
        private void SwitchAllTipReferences()
        {
            HashSet <string> tipKinds = new HashSet <string>()
            {
                typeof(CyPhy.TestInjectionPoint).Name,
                typeof(CyPhy.BallisticTarget).Name,
                typeof(CyPhy.CriticalComponent).Name
            };

            List <IMgaReference> tips = (this.expandedTestBenchType.Impl as MgaModel)
                                        .ChildFCOs
                                        .OfType <IMgaReference>()
                                        .Where(x => tipKinds.Contains(x.MetaBase.Name))
                                        .ToList();

            foreach (var tip in tips)
            {
                // find new destination
                IMgaFCO newTipTarget = FindTestInjectionTarget(
                    this.testBenchType.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(),
                    tip,
                    this.expandedTestBenchType.Children.TopLevelSystemUnderTestCollection.FirstOrDefault());

                if (newTipTarget == null)
                {
                    throw new AnalysisModelTipNotFoundException(string.Format("Referenced test injection entity {0} [{1}] was not found in the generated component assembly (design). {2}", tip.Name, tip.Meta.Name, this.Configuration.Path));
                }

                try
                {
                    var numObjectsBefore = (this.expandedTestBenchType.Impl as MgaModel).ChildObjects.Count;

                    var switcher = new ReferenceSwitcher.ReferenceSwitcherInterpreter();
                    switcher.SwitchReference(newTipTarget, tip);

                    var numObjectsAfter = (this.expandedTestBenchType.Impl as MgaModel).ChildObjects.Count;
                    if (numObjectsBefore != numObjectsAfter)
                    {
                        var message = string.Format("Some connections were lost for test injection point. Most likely becasue in the generated design the target object does not have the same interface (that are connected in the test bench) compare interfaces {0} [{1}] -> {2}", tip.Name, tip.Meta.Name, newTipTarget.AbsPath);

                        throw new AnalysisModelExpandFailedException(message);
                    }
                }
                catch (Exception ex)
                {
                    throw new AnalysisModelExpandFailedException("ReferenceSwitcher failed.", ex);
                }
            }
        }
Example #23
0
        public static TResult CastDstEndRef <TResult, TSource>(
            this TSource source, string kind = "")
            where TResult : ISIS.GME.Common.Classes.Base, new()
            where TSource : IMgaFCO
        {
            Contract.Requires(source != null);
            Contract.Requires(source is MgaSimpleConnection);
            Contract.Requires((source as MgaSimpleConnection).Dst != null);

            MgaSimpleConnection simple = source as MgaSimpleConnection;

            // TODO: use factory for valid casts
            if (kind == simple.Dst.MetaBase.Name)
            {
                IMgaFCO Ref = simple.DstReferences.Cast <IMgaFCO>().FirstOrDefault();
                if (Ref != null)
                {
                    TResult result = new TResult()
                    {
                        Impl = Ref as IMgaObject
                    };
                    return(result);
                }
                else
                {
                    return(null);
                }
            }
            else if (string.IsNullOrEmpty(kind))
            {
                IMgaFCO Ref = simple.DstReferences.Cast <IMgaFCO>().FirstOrDefault();
                if (Ref != null)
                {
                    TResult result = new TResult()
                    {
                        Impl = Ref as IMgaObject
                    };
                    return(result);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Example #24
0
        public void instanceCopy()
        {
            foreach (InstanceInfo instanceInfo in _instanceInfoList)
            {
                MgaFCO newArchetype = getCorrespondingIMgaFCO(instanceInfo.getOtherInstance().ArcheType) as MgaFCO;
                if (newArchetype == null)
                {
                    gmeConsole.Error.WriteLine("Could not find object of path \"" + instanceInfo.getOtherInstance().ArcheType.AbsPath + "\" (archetype of \"" + instanceInfo.getOtherInstance().AbsPath + "\" in file \"" + _projectFilename + "\") in current model.");
                    _exitStatus |= Errors.PathError;
                    continue;
                }

                IMgaFCO iMgaFCO = (instanceInfo.getNewInstanceParent() as MgaModel).DeriveChildObject(newArchetype, instanceInfo.getOtherInstance().MetaRole, instanceInfo.getOtherInstance().IsInstance);
                iMgaFCO.Name = instanceInfo.getOtherInstance().Name;
            }
        }
 private string getPath(IMgaFCO fco)
 {
     string path = fco.Name;
     while (fco.ParentModel != null)
     {
         path = fco.ParentModel.Name + "/" + path;
         fco = fco.ParentModel;
     }
     IMgaFolder folder = fco.ParentFolder;
     while (folder != null)
     {
         path = folder.Name + "/" + path;
         folder = folder.ParentFolder;
     }
     return "/" + path;
 }
Example #26
0
        private string getPath(IMgaFCO fco)
        {
            string path = fco.Name;

            while (fco.ParentModel != null)
            {
                path = fco.ParentModel.Name + "/" + path;
                fco  = fco.ParentModel;
            }
            IMgaFolder folder = fco.ParentFolder;

            while (folder != null)
            {
                path   = folder.Name + "/" + path;
                folder = folder.ParentFolder;
            }
            return("/" + path);
        }
Example #27
0
        public static void SetEnumItem(IMgaFCO IMgaFCO, string attributeName, int index)
        {
            Contract.Requires(IMgaFCO != null);
            Contract.Requires(IMgaFCO.MetaBase is MgaMetaFCO);
            Contract.Requires(string.IsNullOrEmpty(attributeName) == false);

            try
            {
                MgaMetaFCO       meta = (IMgaFCO.MetaBase as MgaMetaFCO);
                MgaMetaAttribute attr = meta.AttributeByName[attributeName];

                IMgaFCO.Attribute[attr].StringValue = attr.EnumItems[index + 1].Value;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #28
0
        public void CategoryIsBlankString()
        {
            var category = new List <String> {
                ""
            };
            String compName = GetCurrentMethodName();

            // Create the test component and export it to disk.
            avm.Component comp = new avm.Component()
            {
                Classifications = new List <String>()
                {
                    ""
                },
                Name = compName
            };
            String pathComp = Path.Combine(pathTest, comp.Name + ".acm");

            comp.SaveToFile(pathComp);

            // Import the component
            IMgaFCO cyphyComp = null;

            proj.PerformInTransaction(delegate
            {
                cyphyComp = importer.ImportFile(proj, pathTest, pathComp);
            });

            // Check that its path is what we expected
            var expectedPath = String.Join("/",
                                           new List <String>()
            {
                "RootFolder",
                "Components",
                compName
            });

            proj.PerformInTransaction(delegate
            {
                Assert.NotNull(cyphyComp);
                String pathCyPhyComp = GetSimplePath(cyphyComp as MgaObject);
                Assert.Equal(expectedPath, pathCyPhyComp);
            });
        }
Example #29
0
        private IMgaFCO getCorrespondingIMgaFCO(IMgaFCO iMgaFCO)
        {
            IMgaFCO correspondingIMgaFCO = null;

            if (_fcoMap.ContainsKey(iMgaFCO))
            {
                correspondingIMgaFCO = _fcoMap[iMgaFCO];
            }
            if (correspondingIMgaFCO == null)
            {
                correspondingIMgaFCO = _currentMgaProject.get_ObjectByPath(iMgaFCO.AbsPath) as IMgaFCO;
                if (correspondingIMgaFCO != null)
                {
                    _fcoMap[iMgaFCO] = correspondingIMgaFCO;
                }
            }

            return(correspondingIMgaFCO);
        }
Example #30
0
        public void subTreeCopy(IMgaFCO newCurrentObject, IMgaFCO otherCurrentObject)
        {
            _fcoMap[otherCurrentObject] = newCurrentObject;

            // NAME
            newCurrentObject.Name = otherCurrentObject.Name;

            // CHILDREN
            if (otherCurrentObject.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL)
            {
                return;
            }

            foreach (MgaObject otherChildMgaObject in otherCurrentObject.ChildObjects)
            {
                // CONNECTIONS ARE PUT OFF UNTIL THE END, WHEN ALL NEEDED OBJECTS ARE CREATED
                if (otherChildMgaObject.MetaBase.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION)
                {
                    continue;
                }

                IMgaFCO otherChildIMgaFCO = otherChildMgaObject as IMgaFCO;

                // INSTANCE ARCHETYPE MAY NOT HAVE BEEN CREATED (I.E. COPIED OVER) YET.  POSTPONE INSTANCE CREATION UNTIL LATER.
                if (otherChildIMgaFCO.ArcheType != null)
                {
                    _instanceInfoList.Add(new InstanceInfo(otherChildIMgaFCO, newCurrentObject));
                    continue;
                }

                MgaFCO newChildMgaFCO = (newCurrentObject as MgaModel).CreateChildObject(otherChildIMgaFCO.MetaRole);

                if (newChildMgaFCO is IMgaReference)
                {
                    _fcoMap[otherChildIMgaFCO] = newChildMgaFCO;
                    newChildMgaFCO.Name        = otherChildIMgaFCO.Name;
                    _referenceInfoList.Add(new ReferenceInfo(otherChildIMgaFCO as IMgaReference, newChildMgaFCO as IMgaReference));
                    continue;
                }

                subTreeCopy(newChildMgaFCO, otherChildIMgaFCO);
            }
        }
Example #31
0
        public static FidelitySelectionRules DeserializeSpiceFidelitySelection(IMgaFCO currentobj)
        {
            FidelitySelectionRules xpaths = null;
            var settings = currentobj.RegistryValue["SpiceFidelitySettings"];

            if (settings == null)
            {
                return(null);
            }
            try
            {
                xpaths = JsonConvert.DeserializeObject <FidelitySelectionRules>(settings);
            }
            catch (JsonException)
            {
            }

            return(xpaths);
        }
Example #32
0
        private void CreateComponent_ImportComponent_CheckPath(List <string> category, String compName)
        {
            // Create the test component and export it to disk.
            avm.Component comp = new avm.Component()
            {
                Classifications = new List <String>()
                {
                    String.Join(".", category)
                },
                Name = compName
            };
            String pathComp = Path.Combine(pathTest, comp.Name + ".acm");

            comp.SaveToFile(pathComp);

            // Import the component
            IMgaFCO cyphyComp = null;

            proj.PerformInTransaction(delegate
            {
                cyphyComp = importer.ImportFile(proj, pathTest, pathComp);
            });

            // Check that its path is what we expected
            var expectedPath = String.Join("/",
                                           new List <String>()
            {
                "RootFolder",
                "Components",
                String.Join("/", category),
                compName
            });

            proj.PerformInTransaction(delegate
            {
                Assert.NotNull(cyphyComp);
                String pathCyPhyComp = GetSimplePath(cyphyComp as MgaObject);
                Assert.Equal(expectedPath, pathCyPhyComp);
            });
        }
Example #33
0
        public void ImportOldITARStatement_NotITAR()
        {
            var acmPath = Path.Combine(testPath, "NotITAR.oldstyle.acm");

            IMgaFCO fco = null;

            proj.PerformInTransaction(delegate
            {
                var importer = new CyPhyComponentImporter.CyPhyComponentImporterInterpreter();
                importer.Initialize(fixture.proj);

                fco = importer.ImportFiles(fixture.proj, fixture.proj.GetRootDirectoryPath(), new[] { acmPath }, doNotReplaceAll: true)[1];
            });

            proj.PerformInTransaction(delegate
            {
                var comp = CyPhyClasses.Component.Cast(fco);

                Assert.False(comp.Children.ITARCollection.Any());
                Assert.False(comp.Children.DoDDistributionStatementCollection.Any());
            });
        }
Example #34
0
        public static IEnumerable <Interfaces.FCO> CastMembersOfSet(
            IMgaFCO mgaFco,
            Dictionary <int, Type> dictionary)
        {
            Contract.Requires(mgaFco != null);

            int metaRef;

            ISIS.GME.Common.Interfaces.FCO fco = null;
            Type t = null;

            foreach (IMgaFCO item in mgaFco.MemberOfSets)
            {
                metaRef = item.MetaBase.MetaRef;
                if (dictionary.TryGetValue(metaRef, out t))
                {
                    fco = Activator.CreateInstance(t) as ISIS.GME.Common.Interfaces.FCO;
                    (fco as ISIS.GME.Common.Classes.FCO).Impl = item as IMgaObject;
                    yield return(fco);
                }
            }
        }
Example #35
0
 public static IEnumerable<IMgaObject> getAncestors(IMgaFCO fco, IMgaObject stopAt = null)
 {
     if (fco.ParentModel != null)
     {
         IMgaModel parent = fco.ParentModel;
         while (parent != null && (stopAt == null || parent.ID != stopAt.ID))
         {
             yield return parent;
             if (parent.ParentModel == null)
             {
                 break;
             }
             parent = parent.ParentModel;
         }
         fco = parent;
     }
     IMgaFolder folder = fco.ParentFolder;
     while (folder != null && (stopAt == null || folder.ID != stopAt.ID))
     {
         yield return folder;
         folder = folder.ParentFolder;
     }
 }
        /// <summary>
        /// Gets a component's hyperlinked name string for use in GME Logger messages, based on its IMgaFCO object.
        /// </summary>
        /// <param name="defaultString">A default text string that will be shown if the component is null or has no ID.</param>
        /// <param name="myComponent">The IMgaFCO object of the component to be referenced.</param>
        /// <returns>The hyperlinked text, if all is OK; otherwise the defaultString.</returns>
        /// <remarks>Added for MOT-228: Modify SPICE CAT Module messages to use GME-hyperlinks.
        /// 
        ///  Instead of accepting CyPhy.Port or CyPhy.Property as an argument, this method accepts an IMgaFCO.
        ///  IMgaFCO objects have the same ID and Name fields. An example of an IMgaFCO object would be a "CyPhy.Port.Impl as IMgaFCO".
        ///  
        ///  When calling this function, you can use this code snippet to get an MgaFCO version of a CyPhy object:
        ///         GetHyperlinkStringFromComponent("default", myComponent.Impl as IMgaFCO);
        /// 
        /// </remarks>
        /// <see cref="https://metamorphsoftware.atlassian.net/browse/MOT-228"/>

        private static string GetHyperlinkStringFromComponent(string defaultString, IMgaFCO myComponent)
        {
            string rVal = defaultString;
            if ((null != myComponent) && (myComponent.ID.Length > 0) && (myComponent.Name.Length > 0))
            {
                rVal = string.Format("<a href=\"mga:{0}\">{1}</a>",
                    myComponent.ID,
                    myComponent.Name);
            }
            return rVal;
        }
Example #37
0
        public void attributesAndRegistryCopy(IMgaFCO newCurrentObject, IMgaFCO otherCurrentObject) {

            // AT THIS POINT, INSTANCE FCO'S HAVEN'T YET MADE IT INTO THE _fcoMap.  AS ALL FCO'S ARE TRAVERSED
            // TO SET ATTRIBUTE AND REGISTRY ENTRIES, A GOOD PLACE TO PUT THEM INTO THE _fcoMap IS HERE.
            if (!_fcoMap.ContainsKey(otherCurrentObject)) {
                _fcoMap[otherCurrentObject] = newCurrentObject;
            }

            foreach (IMgaReference otherReferencedBy in otherCurrentObject.ReferencedBy) {

                // THIS CHECK PREVENTS REFERENCES THAT ARE IN THE MERGED MODEL FROM BEING PROCESSED HERE (AND DESTROYED AS A RESULT)
                if (!_fcoMap.ContainsKey(otherReferencedBy)) {

                    MgaObject otherReferencedByParent = null;
                    GME.MGA.Meta.objtype_enum otherReferencedByParentObjTypeEnum;
                    otherReferencedBy.GetParent(out otherReferencedByParent, out otherReferencedByParentObjTypeEnum);

                    MgaObject newReferencedByParent = _currentMgaProject.get_ObjectByPath(otherReferencedByParent.AbsPath);
                    if (newReferencedByParent == null) {
                        gmeConsole.Error.WriteLine("Unable to make new reference in \"" + otherReferencedByParent.AbsPath + "\" to \"" + otherCurrentObject.AbsPath + "\": prospective parent path not found.");
                        _exitStatus |= Errors.PathError;
                        continue;
                    }
                    MgaObject newReferencedBy = newCurrentObject.Project.get_ObjectByPath(otherReferencedBy.AbsPath);
                    if (newReferencedByParent == null)
                    {
                        gmeConsole.Error.WriteLine("Unable to redirect reference in \"" + otherReferencedByParent.AbsPath + "\" to \"" + otherCurrentObject.AbsPath + "\": reference not found");
                        _exitStatus |= Errors.PathError;
                        continue;
                    }
                    GME.MGA.Meta.objtype_enum newReferencedByParentObjTypeEnum = newReferencedByParent.ObjType;

                    /*
                    IMgaReference newReferencedBy = null;
                    if (newReferencedByParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) {
                        newReferencedBy = (newReferencedByParent as MgaFolder).CreateRootObject(otherReferencedBy.Meta) as IMgaReference;
                    } else if (newReferencedByParentObjTypeEnum == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL) {
                        newReferencedBy = (newReferencedByParent as MgaModel).CreateChildObject(otherReferencedBy.MetaRole) as IMgaReference;
                    } else {
                        gmeConsole.Error.WriteLine("Unable to make new reference in \"" + newReferencedByParent.AbsPath + "\" to \"" + newCurrentObject.AbsPath + "\": prospective parent neither a folder nor a model.");
                        _exitStatus |= Errors.PathError;
                        continue;
                    }

                    newReferencedBy.Referred = newCurrentObject as MgaFCO;
                    // KMS this will be destroyed at the end
                    otherReferencedBy.DestroyObject();
                    */


                    ReferenceSwitcher.Switcher.MoveReferenceWithRefportConnections(newCurrentObject as MgaFCO, (MgaReference)newReferencedBy, (x, y, z) => {
                        Console.WriteLine(x + " ; " + y + " ; " + z);
                    });

                    //_fcoMap[otherReferencedBy] = newReferencedBy;
                }
            }

            // ATTRIBUTES
            MgaAttributes otherMgaAttributes = otherCurrentObject.Attributes;
            foreach (MgaAttribute otherMgaAttribute in otherMgaAttributes) {
                //IMgaAttribute newMgaAttribute = newCurrentObject.get_Attribute( otherMgaAttribute.Meta ); // THROWS 0x87650080 ERROR --- E_META_INVALIDATTR
                IMgaAttribute newMgaAttribute = newCurrentObject.Attributes.Cast<IMgaAttribute>().FirstOrDefault(x => x.Meta.Name == otherMgaAttribute.Meta.Name);
                if (newMgaAttribute.Value != otherMgaAttribute.Value || otherMgaAttribute.Status == (int)GME.MGA.attstatus_enum.ATTSTATUS_HERE) {
                    newMgaAttribute.Value = otherMgaAttribute.Value;
                }
            }

            // REGISTRY
            copyRegistry(newCurrentObject, otherCurrentObject);

            // RECURSE
            if (otherCurrentObject.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL) {
                return;
            }
            foreach (MgaObject otherChildMgaObject in otherCurrentObject.ChildObjects) {

                if (otherChildMgaObject.MetaBase.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION) {
                    continue;
                }

                IMgaFCO otherChildIMgaFCO = otherChildMgaObject as IMgaFCO;

                IMgaFCO newChildIMgaFCO = null;
                if (_fcoMap.ContainsKey(otherChildIMgaFCO)) {
                    newChildIMgaFCO = _fcoMap[otherChildIMgaFCO];
                } else {
                    IEnumerable< MgaFCO > newChildMgaFCOs = (newCurrentObject as MgaModel).ChildObjects.Cast<MgaFCO>().Where(x => x.Name == otherChildIMgaFCO.Name);
                    if (newChildMgaFCOs.Count() > 1) {
                        gmeConsole.Error.WriteLine("Error:  FCO of path \"" + newCurrentObject.AbsPath + "\" has more than one child named \"" + otherChildIMgaFCO.Name + "\" -- cannot discern objects, skipping");
                        _exitStatus |= Errors.DuplicateChildNameError;
                        continue;
                    } else if ( newChildMgaFCOs.Count() == 0 ) {
                        gmeConsole.Error.WriteLine("Error:  FCO of path \"" + newCurrentObject.AbsPath + "\" has no child named \"" + otherChildIMgaFCO.Name + "\", but corresponding object in file does.  This shouldn't happen, skipping");
                        _exitStatus |= Errors.MissingChildError;
                        continue;
                    }
                    newChildIMgaFCO = newChildMgaFCOs.First();
                    _fcoMap[otherChildIMgaFCO] = newChildIMgaFCO;
                }

                attributesAndRegistryCopy(newChildIMgaFCO, otherChildIMgaFCO);
            }

        }
Example #38
0
 public void copyRegistry(IMgaFCO newCurrentObject, IMgaFCO otherCurrentObject) {
     MgaRegNodes otherMgaRegNodes = otherCurrentObject.Registry;
     foreach (MgaRegNode otherMgaRegNode in otherMgaRegNodes) {
         MgaRegNode newMgaRegNode = newCurrentObject.get_RegistryNode(otherMgaRegNode.Path);
         copyRegistry(newMgaRegNode, otherMgaRegNode);
     }
 }
Example #39
0
        public void subTreeCopy(IMgaFCO newCurrentObject, IMgaFCO otherCurrentObject) {

            _fcoMap[otherCurrentObject] = newCurrentObject;

            // NAME
            newCurrentObject.Name = otherCurrentObject.Name;

            // CHILDREN
            if (otherCurrentObject.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL) {
                return;
            }

            foreach (MgaObject otherChildMgaObject in otherCurrentObject.ChildObjects) {

                // CONNECTIONS ARE PUT OFF UNTIL THE END, WHEN ALL NEEDED OBJECTS ARE CREATED
                if (otherChildMgaObject.MetaBase.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION) {
                    continue;
                }

                IMgaFCO otherChildIMgaFCO = otherChildMgaObject as IMgaFCO;

                // INSTANCE ARCHETYPE MAY NOT HAVE BEEN CREATED (I.E. COPIED OVER) YET.  POSTPONE INSTANCE CREATION UNTIL LATER.
                if (otherChildIMgaFCO.ArcheType != null) {
                    _instanceInfoList.Add(new InstanceInfo(otherChildIMgaFCO, newCurrentObject));
                    continue;
                }

                MgaFCO newChildMgaFCO = (newCurrentObject as MgaModel).CreateChildObject(otherChildIMgaFCO.MetaRole);

                if (newChildMgaFCO is IMgaReference) {
                    _fcoMap[otherChildIMgaFCO] = newChildMgaFCO;
                    newChildMgaFCO.Name = otherChildIMgaFCO.Name;
                    _referenceInfoList.Add(new ReferenceInfo(otherChildIMgaFCO as IMgaReference, newChildMgaFCO as IMgaReference));
                    continue;
                }

                subTreeCopy(newChildMgaFCO, otherChildIMgaFCO);
            }

        }
Example #40
0
        private static List<RuleFeedbackBase> GetExceptionRuleFeedBack(Exception ex, IMgaFCO context)
        {
            var result = new List<RuleFeedbackBase>();

            var feedback = new GenericRuleFeedback<Exception>()
            {
                AdditionalInfo = ex,
                FeedbackType = FeedbackTypes.Error,
                Message = string.Format("Context: {0} - Exception: {1} {2}",
                    context.Name,
                    ex.Message,
                    ex.StackTrace)
            };

            feedback.InvolvedObjectsByRole.Add(context as IMgaFCO);
            result.Add(feedback);

            return result;
        }
 public MasterInterpreterResult[] RunInTransactionOnOneConfig(
     IMgaModel context,
     IMgaFCO configuration,
     bool postToJobManager = false,
     bool keepTempModels = false)
 {
     MgaFCOs configurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
     configurations.Append(configuration as MgaFCO);
     return this.RunInTransactionOnMultipleConfigs(context, configurations, postToJobManager, keepTempModels);
 }
Example #42
0
        private IMgaFCO getCorrespondingIMgaFCO(IMgaFCO iMgaFCO) {

            IMgaFCO correspondingIMgaFCO = null;
            if (_fcoMap.ContainsKey(iMgaFCO)) {
                correspondingIMgaFCO = _fcoMap[iMgaFCO];
            }
            if (correspondingIMgaFCO == null) {
                correspondingIMgaFCO = _currentMgaProject.get_ObjectByPath(iMgaFCO.AbsPath) as IMgaFCO;
                if (correspondingIMgaFCO != null) {
                    _fcoMap[iMgaFCO] = correspondingIMgaFCO;
                }
            }

            return correspondingIMgaFCO;
        }
        [ComVisible(true)] // called by CPMDecorator
        public void SetSelected(IMgaFCO fco, bool selected)
        {
            try
            {
                // GMEConsole.Out.WriteLine(fco.Name + " selected");
                if (fco.ParentModel == null)
                {
                    return;
                }
                if (previouslySelectedParent != null && previouslySelectedParent != fco.ParentModel.ID)
                {
                    selectedFCOIDs = new HashSet<string>();
                }
                previouslySelectedParent = fco.ParentModel.ID;
                string topicGuid = null;
                MgaModel ancestor = fco.ParentModel;
                while (ancestor != null)
                {

                    if (ancestor.Meta.Name == "ComponentAssembly")
                    {
                        var assembly = CyPhyMLClasses.ComponentAssembly.Cast(ancestor);
                        if (designIdToCadAssemblyXml.ContainsKey(assembly.Guid.ToString()))
                        {
                            topicGuid = assembly.Guid.ToString();
                            break;
                        }
                    }
                    else if (ancestor.Meta.Name == "CADModel")
                    {
                        /* var cadmodel = CyPhyMLClasses.CADModel.Cast(ancestor);
                         if (assemblyExesStarted.Contains(cadmodel) || assemblyExesStarted.Contains(component.Guid.ToString()))
                         {
                         }*/

                    }
                    else if (ancestor.Meta.Name == "Component")
                    {
                        var component = CyPhyMLClasses.Component.Cast(ancestor);
                        if (syncedComponents.Count > 0 && ((topicGuid!=null&&syncedComponents.ContainsKey(topicGuid)) || syncedComponents.ContainsKey(component.Attributes.AVMID)))
                        {
                            topicGuid = component.Attributes.AVMID;
                        }
                        break;
                    }
                    else
                    {
                        return;
                    }
                    ancestor = ancestor.ParentModel;
                }
                if (topicGuid == null)
                {
                    return;
                }
                if (selected)
                {
                    selectedFCOIDs.Add(fco.ID);
                }
                else
                {
                    selectedFCOIDs.Remove(fco.ID);
                }
                selectedFCOIDs.RemoveWhere(id => addon.Project.GetFCOByID(id).Status != (int)objectstatus_enum.OBJECT_EXISTS);
                var edit = new Edit();
                edit.origin.Add(GMEOrigin);
                edit.editMode = Edit.EditMode.POST;
                edit.mode.Add(Edit.EditMode.POST);
                edit.actions.Add(new MetaLinkProtobuf.Action());
                edit.actions[0].actionMode = MetaLinkProtobuf.Action.ActionMode.SELECT;
                edit.actions[0].payload = new Payload();
                var selectedFCOs = selectedFCOIDs.Select(id => addon.Project.GetFCOByID(id));
                edit.actions[0].payload.components.AddRange(
                    selectedFCOs.Where(f => f.Meta.Name == "ComponentRef")
                        .Select(CyPhyMLClasses.ComponentRef.Cast)
                        .Select(component =>
                            new edu.vanderbilt.isis.meta.CADComponentType()
                            {
                                ComponentID = component.Attributes.InstanceGUID
                            }));
                edit.actions[0].payload.datums.AddRange(
                    selectedFCOs.Where(f => datumKinds.Contains(f.Meta.Name))
                        .Select(CyPhyMLClasses.CADDatum.Cast)
                        .Where(datum => datum.ParentContainer.Impl.MetaBase.Name == typeof(CyPhyML.CADModel).Name
                            && datum.ParentContainer.ParentContainer.Impl.MetaBase.Name == typeof(CyPhyML.Component).Name)
                        .Select(datum => new DatumType()
                        {
                            name = datum.Attributes.DatumName,
                            type = datumKindsMap[datum.Impl.MetaBase.Name],
                            componentId = CyPhyMLClasses.Component.Cast(datum.ParentContainer.ParentContainer.Impl).Attributes.AVMID
                        }));
                edit.topic.Add(edit.actions[0].payload.datums.Count > 0 ? ComponentUpdateTopic : CadAssemblyTopic);
                edit.topic.Add(topicGuid);
                bridgeClient.SendToMetaLinkBridge(edit);
            }
            catch (Exception e)
            {
                GMEConsole.Warning.WriteLine("An exception has been thrown during selection: " + e.Message);
            }
        }
        protected string GetFloodSignIcon(IMgaFCO fs)
        {
            string icon_map = fs.StrAttrByName["FloodIconMap"].Trim();
            double flood_level = fs.FloatAttrByName["FloodLevel"];

            // expect list of form <key string> : <value string>
            var splitResult = icon_map.Split(new string[] { System.Environment.NewLine, "\n" },
                System.StringSplitOptions.RemoveEmptyEntries);

            string iconStr = "";
            foreach (string line in splitResult.Reverse()) // go in decreasing order
            {
                var halves = line.Split(new Char[] { ':' }, 2);
                double level = Convert.ToDouble(halves[0].Trim());
                iconStr = halves[1].Trim();

                if (flood_level >= level )
                    return iconStr;
            }

            return iconStr; // if flood_level is smaller than them all
        }
        protected string GetParkingSignIcon(IMgaFCO ps)
        {
            string icon_map = ps.StrAttrByName["ParkingIconMap"].Trim();
            bool parking_val = ps.BoolAttrByName["Parking"];

            // expect list of form <key string> : <value string>
            var splitResult = icon_map.Split(new string[] { System.Environment.NewLine, "\n" },
                System.StringSplitOptions.RemoveEmptyEntries);

            foreach (string line in splitResult)
            {
                var halves = line.Split(new Char[] { ':' }, 2);
                var lhs_bool = Convert.ToBoolean(halves[0].Trim());

                if (parking_val == lhs_bool)
                {
                    return halves[1].Trim();
                }
            }

            return ps.RegistryValue["icon"]; // default icon
        }
Example #46
0
 public InstanceInfo(IMgaFCO otherInstance, IMgaFCO newInstanceParent) {
     _otherInstance = otherInstance;
     _newInstanceParent = newInstanceParent;
 }
        private MasterInterpreterResult RunAnalysisModelProcessors(
            IMgaModel context,
            IMgaFCO configuration,
            bool postToJobManager = false,
            bool keepTempModels = false)
        {
            if (context == null ||
                configuration == null)
            {
                throw new ArgumentNullException();
            }

            this.Logger.WriteDebug("Preparing analysis model processor");
            var result = new MasterInterpreterResult();
            result.Context = context;
            result.Configuration = configuration;
            result.Success = true;

            string contextName = string.Empty;
            string configurationName = string.Empty;

            AnalysisModelProcessor analysisModelProcessor = null;

            Exception exceptionToThrow = null;

            try
            {
                this.Logger.WriteDebug("Turning off addons for perfomance reasons: {0}", string.Join(", ", this.addonNames));
                this.TurnOffAddons(context);

                this.ExecuteInTransaction(context, () =>
                {
                    contextName = context.Name;
                    configurationName = configuration.Name;

                    this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                    {
                        Percent = 0,
                        Context = contextName,
                        Configuration = configuration.AbsPath,
                        Title = "Initializing"
                    });

                    // expand context for configuration
                    this.Logger.WriteDebug("Getting analysis model processor instance for {0} type", context.MetaBase.Name);
                    analysisModelProcessor = AnalysisModelProcessor.GetAnalysisModelProcessor(context);
                    this.Logger.WriteDebug("Got {0} for {1} {2}", analysisModelProcessor.GetType().Name, context.MetaBase.Name, context.AbsPath);

                    this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                    {
                        Percent = 25,
                        Context = contextName,
                        Configuration = configurationName,
                        Title = "Expanding"
                    });

                    if (configuration.MetaBase.Name == typeof(CyPhy.CWC).Name)
                    {
                        this.Logger.WriteDebug("{0} was specified as configuration. Start expanding it. {1}", configuration.MetaBase.Name, configuration.AbsPath);
                        analysisModelProcessor.Expand(CyPhyClasses.CWC.Cast(configuration));
                        this.Logger.WriteDebug("Expand finished for {0}", configuration.AbsPath);
                    }
                    else if (configuration.MetaBase.Name == typeof(CyPhy.ComponentAssembly).Name)
                    {
                        this.Logger.WriteDebug("{0} was specified as configuration. Start expanding it. {1}", configuration.MetaBase.Name, configuration.AbsPath);
                        analysisModelProcessor.Expand(CyPhyClasses.ComponentAssembly.Cast(configuration));
                        this.Logger.WriteDebug("Expand finished for {0}", configuration.AbsPath);
                    }
                    else
                    {
                        this.Logger.WriteDebug("{0} expand is not supported {1}", configuration.MetaBase.Name, configuration.AbsPath);
                        throw new AnalysisModelContextNotSupportedException("Configuration type is not supported. Use CWC or Component Assembly.");
                    }

                    // TODO: give progress update about exporters & their success

                    // design space might be saved multiple times

                    if (analysisModelProcessor.OriginalSystemUnderTest.AllReferred is CyPhy.DesignContainer)
                    {
                        this.Logger.WriteDebug("Calling design space exporter");
                        bool successDesignSpaceExport = analysisModelProcessor.SaveDesignSpace(this.ProjectManifest);

                        // FIXME: this would case the entire test bench to fail if it is a single configuration.
                        // result.Success = result.Success && successDesignSpaceExport;

                        if (successDesignSpaceExport)
                        {
                            this.Logger.WriteDebug("Design space exporter succeeded.");
                        }
                        else
                        {
                            this.Logger.WriteWarning("Design space exporter failed.");
                        }
                    }
                    else
                    {
                        this.Logger.WriteDebug("[SKIP] Calling design space exporter, since the test bench is defined over a design and not a design space.");
                    }

                    this.Logger.WriteDebug("Calling design exporter");
                    bool successDesignExport = analysisModelProcessor.SaveDesign(this.ProjectManifest);
                    // result.Success = result.Success && successDesignExport;

                    if (successDesignExport)
                    {
                        this.Logger.WriteDebug("Design exporter succeeded.");
                    }
                    else
                    {
                        this.Logger.WriteWarning("Design exporter failed.");
                    }

                    this.Logger.WriteDebug("Saving test bench definition");
                    bool successTestBench = analysisModelProcessor.SaveTestBench(this.ProjectManifest);
                    // result.Success = result.Success && successTestBench;

                    if (successTestBench)
                    {
                        this.Logger.WriteDebug("Saving test bench definition succeeded.");
                    }
                    else
                    {
                        this.Logger.WriteWarning("Saving test bench definition failed.");
                    }

                    this.Logger.WriteDebug("Saving test bench manifest");
                    bool successTestBenchManifest = analysisModelProcessor.SaveTestBenchManifest(this.ProjectManifest);
                    result.Success = result.Success && successTestBenchManifest;

                    if (successTestBenchManifest)
                    {
                        this.Logger.WriteDebug("Saving test bench manifest succeeded.");
                    }
                    else
                    {
                        this.Logger.WriteError("Saving test bench manifest failed.");
                    }

                    this.Logger.WriteDebug("Serializing Project manifest file with updates.");
                    this.ProjectManifest.Serialize();
                    this.Logger.WriteDebug("Project manifest was successfully saved.");
                });

                this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                {
                    Percent = 45,
                    Context = contextName,
                    Configuration = configurationName,
                    Title = "Model is ready for interpreters"
                });

                if (this.IsInteractive)
                {
                    this.Logger.WriteDebug("Execution is interactive, showing interpreter configuration forms.");
                    analysisModelProcessor.ShowInterpreterConfigs(this.interpreterConfigurations);
                }
                else
                {
                    analysisModelProcessor.ShowInterpreterConfigs(this.interpreterConfigurations, interactive: false);
                    this.Logger.WriteDebug("Execution is non interactive, not showing interpreter configuration forms. Using settings from files.");
                }

                analysisModelProcessor.InterpreterProgress += (object sender, InterpreterProgressEventArgs e) =>
                {
                    var interpreterName = e.Interpreter == null ? string.Empty : e.Interpreter.Name;
                    this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                    {
                        Percent = 50 + (e.Percent / 5), // we have 20 percent room on the main progress
                        Context = contextName,
                        Configuration = configurationName,
                        Title = string.Format("Running interpreters {0}% {1} success status: {2}", e.Percent, interpreterName, e.Success)
                    });
                };

                this.Logger.WriteDebug("Running interpreters. Keeping temp models: {0}", keepTempModels);

                bool isVerbose = this.Logger.GMEConsoleLoggingLevel == CyPhyGUIs.SmartLogger.MessageType_enum.Debug;

                analysisModelProcessor.RunInterpreters(keepTempModels == false, isVerbose);
                result.OutputDirectory = analysisModelProcessor.OutputDirectory;

                this.Logger.WriteDebug("Interpreters finished.");

                this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                {
                    Percent = 70,
                    Context = contextName,
                    Configuration = configurationName,
                    Title = "All interpreters successfully finished"
                });

                this.ExecuteInTransaction(context, () =>
                {
                    if (postToJobManager)
                    {
                        this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                        {
                            Percent = 80,
                            Context = contextName,
                            Configuration = configurationName,
                            Title = "Posting to Job Manager"
                        });

                        if (this.Manager == null)
                        {
                            this.Logger.WriteDebug("Job manager instance is null. Initializing one.");
                            this.Manager = new JobManagerDispatch();
                            this.Logger.WriteDebug("Job manager dispatch is ready to receive jobs");
                        }

                        this.Logger.WriteDebug("Posting to the job manager");
                        var postedToJobManager = analysisModelProcessor.PostToJobManager(this.Manager);
                        result.Success = result.Success && postedToJobManager;

                        if (postedToJobManager)
                        {
                            this.Logger.WriteInfo("Job posted to the job manager: {0}", context.Name);
                        }
                        else
                        {
                            this.Logger.WriteError("Job was not posted to the job manager: {0}", context.Name);
                        }

                        this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                        {
                            Percent = 89,
                            Context = contextName,
                            Configuration = configurationName,
                            Title = "Posted to Job Manager"
                        });
                    }
                    else
                    {
                        this.Logger.WriteDebug("Not posting to the job manager");

                        this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                        {
                            Percent = 89,
                            Context = contextName,
                            Configuration = configurationName,
                            Title = "Skip posting to Job Manager"
                        });
                    }
                });
            }
            catch (AnalysisModelInterpreterConfigurationFailedException ex)
            {
                this.Logger.WriteDebug(ex.ToString());
                result.Success = false;
                result.Message = ex.Message;
                result.Exception = ex.ToString();
                exceptionToThrow = ex;
            }
            catch (AnalysisModelInterpreterException ex)
            {
                this.Logger.WriteDebug(ex.ToString());
                result.Success = false;
                result.Message = ex.Message;
                result.Exception = ex.ToString();
            }
            catch (AnalysisModelExpandFailedException ex)
            {
                this.Logger.WriteDebug(ex.ToString());
                result.Success = false;
                result.Message = ex.Message;
                result.Exception = ex.ToString();
            }
            catch (Exception ex)
            {
                this.Logger.WriteDebug(ex.ToString());
                result.Success = false;
                result.Message = ex.Message;
                if (ex.InnerException != null)
                {
                    result.Message = string.Format("{0} ---> {1}", ex.Message, ex.InnerException.Message);
                }

                result.Exception = ex.ToString();
            }
            finally
            {
                // clean up if interpreter is canceled
                this.ExecuteInTransaction(context, () =>
                {
                    // destroy objects if keepTempModels == false
                    if (keepTempModels == false)
                    {
                        this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                        {
                            Percent = 90,
                            Context = contextName,
                            Configuration = configurationName,
                            Title = "Removing temporary models"
                        });

                        this.Logger.WriteDebug("Removing temporary models.");

                        analysisModelProcessor.DeleteTemporaryObjects();

                        this.Logger.WriteDebug("Temporary models are removed.");

                        this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                        {
                            Percent = 100,
                            Context = contextName,
                            Configuration = configurationName,
                            Title = "Removing temporary models"
                        });
                    }
                    else
                    {
                        this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs()
                        {
                            Percent = 100,
                            Context = contextName,
                            Configuration = configurationName,
                            Title = "Keeping temporary models"
                        });
                    }
                });

                this.Logger.WriteDebug("Turning addons back on: {0}", string.Join(", ", this.addonNames));
                this.TurnOnAddons(context);
            }

            if (exceptionToThrow != null)
            {
                this.Logger.WriteDebug(exceptionToThrow.ToString());
                throw exceptionToThrow;
            }

            return result;
        }
Example #48
0
        // RECORD ALL CONNECTIONS AND ALL OBJECTS THAT HAVE CONNECTIONS
        public void recordConnections(IMgaFCO otherCurrentObject) {

            if (otherCurrentObject.PartOfConns.Count != 0) {
                _hasConnectionList.Add(otherCurrentObject);
            }
            if (otherCurrentObject is IMgaReference)
            {
                IMgaReference otherReference = (IMgaReference)otherCurrentObject;
                if (otherReference.UsedByConns.Count > 0)
                {
                    _hasConnectionList.Add(otherReference);
                }
            }

            if (otherCurrentObject.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL) {
                return;
            }
            foreach (MgaObject otherChildMgaObject in otherCurrentObject.ChildObjects) {

                if (otherChildMgaObject.MetaBase.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION) {
                    _iMgaConnectionSet.Add(otherChildMgaObject as IMgaConnection);
                    continue;
                }

                recordConnections(otherChildMgaObject as IMgaFCO);
            }
        }
        protected string GetStreetSignIcon(IMgaFCO ss)
        {
            string icon_map = ss.StrAttrByName["StreetSignIconMap"].Trim();
            string street_sign = ss.StrAttrByName["StreetSignTypes"].Trim();

            // expect list of form <key string> : <value string>
            var splitResult = icon_map.Split(new string[] { System.Environment.NewLine, "\n" },
                System.StringSplitOptions.RemoveEmptyEntries);

            foreach (string line in splitResult)
            {
                string[] halves = line.Split(new Char[] { ':' }, 2);
                if (halves[0].Trim() == street_sign)
                    return halves[1].Trim();
            }

            return ss.RegistryValue["icon"]; // default icon
        }
        public List<IMgaFCO> InsertComponents(
            IMgaFCO designContainer,
            IMgaFCO componentRef,
            List<IMgaFCO> components,
            List<KeyValuePair<IMgaFCO, string>> messages)
        {
            Contract.Requires(designContainer as IMgaModel != null);
            Contract.Requires(componentRef as IMgaReference != null);
            Contract.Requires((componentRef as IMgaReference).Referred != null);
            Contract.Requires(components != null);

            List<IMgaFCO> result = new List<IMgaFCO>();

            IMgaModel container = designContainer as IMgaModel;
            IMgaReference compRef = componentRef as IMgaReference;

            var childComps = container.
                ChildFCOs.
                Cast<IMgaFCO>().
                Where(x => x.MetaBase.Name == "ComponentRef").
                Cast<IMgaReference>().
                Select(x => x.Referred).
                ToList();

            // get all connections which has the componentRef as an endpoint
            var childConnections = container.
                ChildFCOs.
                Cast<IMgaFCO>().
                Where(x => x is IMgaSimpleConnection).
                Cast<IMgaSimpleConnection>().
                ToList();


            // ith new component
            int iNewComponent = 0;

            foreach (var compToCreate in components)
            {
                if (childComps.Contains(compToCreate))
                {
                    // If the component already exists this function will not create it again
                    // skip
                    messages.Add(new KeyValuePair<IMgaFCO, string>(compToCreate, "Component already exists."));
                    continue;
                }

                // create reference
                var newRef = container.CreateReference(componentRef.MetaRole, compToCreate as MgaFCO);
                newRef.Name = compToCreate.Name;

                ////////

                //VehicleForge.VFSession session = null;
                //VFComponentExchange results = session.SendGetRequest<VFComponentExchange>("");
                //VFComponentExchange resultjson = Newtonsoft.Json.JsonConvert.DeserializeObject<VFComponentExchange>("");
                ////////


                result.Add(newRef);

                bool compatible = true;

                // create connections
                foreach (var connectionToCreate in childConnections)
                {
                    if (SafeMgaObjectCompare(connectionToCreate.SrcReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef) ||
                        SafeMgaObjectCompare(connectionToCreate.DstReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef))
                    {
                        try
                        {
                            var connRole = connectionToCreate.MetaRole;
                            var connSrc = connectionToCreate.Src;
                            var connDst = connectionToCreate.Dst;
                            var connSrcReference = connectionToCreate.SrcReferences.Cast<MgaFCO>().FirstOrDefault();
                            var connDstReference = connectionToCreate.DstReferences.Cast<MgaFCO>().FirstOrDefault();

                            // overwrite the new endpoints
                            if (SafeMgaObjectCompare(connectionToCreate.SrcReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef))
                            {
                                connSrcReference = newRef;

                                // Check for objects with same name and same type
                                var srcCandidates = compToCreate.ChildObjects.OfType<MgaFCO>().Where(x => 
                                    x.Name == connSrc.Name &&
                                    x.Meta.Name == connSrc.Meta.Name);

                                MgaFCO srcCandidate = srcCandidates.FirstOrDefault();

                                if (srcCandidates.Count() > 1)
                                {
                                    messages.Add(new KeyValuePair<IMgaFCO, string>(
                                        compToCreate,
                                        "Not Inserted. It has more than one matching object named: " + connSrc.Name));
                                    compatible = false;
                                }

                                if (srcCandidate == null)
                                {
                                    messages.Add(new KeyValuePair<IMgaFCO, string>(
                                        compToCreate,
                                        "Not Inserted. It does not have a port with name: " + connSrc.Name));
                                    compatible = false;
                                }

                                connSrc = srcCandidate;
                            }

                            if (SafeMgaObjectCompare(connectionToCreate.DstReferences.Cast<IMgaFCO>().FirstOrDefault(), compRef))
                            {
                                connDstReference = newRef;

                                //var dstCandidate = compToCreate.ObjectByPath[connDst.Name] as MgaFCO;

                                var dstCandidates = compToCreate.ChildObjects.OfType<MgaFCO>().Where(x => 
                                    x.Name == connDst.Name &&
                                    x.Meta.Name == connDst.Meta.Name);

                                MgaFCO dstCandidate = dstCandidates.FirstOrDefault();

                                if (dstCandidates.Count() > 1)
                                {
                                    messages.Add(new KeyValuePair<IMgaFCO, string>(
                                        compToCreate,
                                        "Not Inserted. It has more than one matching object named: " + connDst.Name));
                                    compatible = false;
                                }

                                if (dstCandidate == null)
                                {
                                    messages.Add(new KeyValuePair<IMgaFCO, string>(
                                        compToCreate,
                                        "Not Inserted. It does not have port with name: " + connDst.Name));
                                    compatible = false;
                                }

                                connDst = dstCandidate;
                            }

                            // check end points
                            if (connSrc != null &&
                                connDst != null)
                            {
                                var newConnection = container.CreateSimpleConnDisp(
                                    connRole,
                                    connSrc,
                                    connDst,
                                    connSrcReference,
                                    connDstReference);
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.TraceError(ex.ToString());
                            System.Diagnostics.Trace.TraceError("Probably some ports do not match.");
                            compatible = false;
                        }
                    }
                }

                if (compatible)
                {
                    iNewComponent = iNewComponent + 1;

                    foreach (IMgaPart part in newRef.Parts)
                    {
                        int x = 0;
                        int y = 0;
                        string icon;

                        componentRef.PartByMetaPart[part.Meta].GetGmeAttrs(out icon, out x, out y);

                        part.SetGmeAttrs(icon, x, y + 80 * iNewComponent);
                    }

                }
                else
                {
                    //messages.Add(new KeyValuePair<IMgaFCO, string>(compToCreate, "Component was skipped: " + compToCreate.Name));
                    result.Remove(newRef);
                    newRef.DestroyObject();
                }

            }

            foreach (var item in messages)
            {
                GMEConsole.Error.WriteLine("{0}: {1}", item.Key.ToMgaHyperLink(), item.Value);
            }

            GMEConsole.Info.WriteLine("{0} components were inserted. Detailed list as follows:", result.Count);

            foreach (var item in result)
            {
                GMEConsole.Info.WriteLine("- {0}", item.ToMgaHyperLink());
            }

            return result;
        }