Esempio n. 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);
            }
        }
Esempio n. 2
0
        // Modify a component in design sync mode, and see that exactly one resync message sent
        void TestAssemblySync_ModifyComponent()
        {
            SetupTest();

            SendInterest(CyPhyMetaLinkAddon.IdCounter.ToString());
            WaitToReceiveMessage();

            RunCyPhyMLSync(
                (project, propagate, interpreter) =>
            {
                MgaFCO assembly;
                MgaFCO connectorToDelete;

                project.BeginTransactionInNewTerr();
                try
                {
                    assembly = GetTestAssembly(project);
                    MgaReference componentRef = (MgaReference)assembly.ChildObjects.Cast <MgaFCO>().Where(fco => fco.Name.Contains("Mass__Mass_Steel")).First();
                    connectorToDelete         = ((MgaModel)componentRef.Referred).ChildFCOs.Cast <MgaFCO>().Where(fco => fco.Name == "PIN").First();
                }
                finally
                {
                    project.AbortTransaction();
                }
                interpreter.StartAssemblySync(project, assembly, 128);
                Application.DoEvents();
                project.BeginTransactionInNewTerr();
                try
                {
                    connectorToDelete.DestroyObject();
                }
                finally
                {
                    project.CommitTransaction();
                }
                Application.DoEvents();
                Thread.Sleep(1000);     // XXX don't race with propagate's send message thread
                WaitForAllMetaLinkMessages();

                Xunit.Assert.Equal(1,
                                   this.receivedMessages.Where(
                                       msg => msg.actions.Any(a => a.actionMode == edu.vanderbilt.isis.meta.Action.ActionMode.CLEAR)).Count());
                Xunit.Assert.Equal(1,
                                   this.receivedMessages.Where(
                                       msg => msg.actions.Any(a => a.actionMode == edu.vanderbilt.isis.meta.Action.ActionMode.CREATE_CYPHY_DESIGN)).Count());
            }
                );
        }
Esempio n. 3
0
        public static void SetReferred(
            MgaReference Impl,
            ISIS.GME.Common.Interfaces.FCO value)
        {
            Contract.Requires(Impl != null);
            Contract.Requires(Impl is MgaReference);

            try
            {
                if (value != null)
                {
                    (Impl as MgaReference).Referred = value.Impl as MgaFCO;
                }
                else
                {
                    (Impl as MgaReference).Referred = null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Referred value could not be set.", ex);
            }
        }
Esempio n. 4
0
        /// <summary>
        ///
        /// </summary>
        /// <returns>True if dependency cannot be determined.</returns>
        private bool UpdateDependency(MgaModel testBenchSuite)
        {
            this.Logger.WriteDebug("Updating test bench dependencies ...");

            HashSet <MgaFCO> toProcess = new HashSet <MgaFCO>(new MgaObjectEqualityComparor <MgaFCO>());

            // Find all FCOs with no outgoing connections
            foreach (MgaFCO fco in testBenchSuite.ChildFCOs.Cast <MgaFCO>().Where(fco => fco.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_CONNECTION))
            {
                if (fco.PartOfConns.Cast <MgaConnPoint>().Where(connpoint => connpoint.ConnRole == "src" && connpoint.References.Count == 0).Count() == 0)
                {
                    if (fco.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_REFERENCE)
                    {
                        MgaReference reference = (MgaReference)fco;
                        if (reference.UsedByConns.Cast <MgaConnPoint>().Where(connpoint => connpoint.ConnRole == "src").Count() == 0)
                        {
                            toProcess.Add(fco);
                        }
                    }
                    else
                    {
                        toProcess.Add(fco);
                    }
                }
            }

            var DependencyGraph = new Dictionary <MgaFCO, List <MgaFCO> >(new MgaObjectEqualityComparor <MgaFCO>());

            HashSet <MgaFCO> tempMarked = new HashSet <MgaFCO>(new MgaObjectEqualityComparor <MgaFCO>());
            Dictionary <MgaFCO, List <MgaFCO> > resident = new Dictionary <MgaFCO, List <MgaFCO> >(new MgaObjectEqualityComparor <MgaFCO>());

            dfs_visit Visit = null;

            Visit = delegate(MgaFCO fco, ref List <MgaFCO> out_)
            {
                if (tempMarked.Contains(fco))
                {
                    throw new CycleException("Cycle involving " + fco.Name);
                }
                List <MgaFCO> previousOut;
                if (!resident.TryGetValue(fco, out previousOut))
                {
                    //GMEConsole.Out.WriteLine("" + fco.Name);
                    tempMarked.Add(fco);
                    IEnumerable <MgaConnPoint> connections = fco.PartOfConns.Cast <MgaConnPoint>().Where(cp => cp.ConnRole != "src");
                    if (fco.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_REFERENCE)
                    {
                        MgaReference reference = (MgaReference)fco;
                        connections = connections.Concat(reference.UsedByConns.Cast <MgaConnPoint>().Where(cp => cp.ConnRole != "src" && cp.References[1] == reference));
                    }
                    foreach (MgaConnPoint connpoint in connections)
                    {
                        MgaSimpleConnection conn = (MgaSimpleConnection)connpoint.Owner;
                        MgaFCO other             = conn.Src;
                        if (conn.SrcReferences.Count > 0)
                        {
                            other = (connpoint.Owner as MgaSimpleConnection).SrcReferences[1];
                        }
                        // GMEConsole.Out.WriteLine("&nbsp; " + other.Name);
                        Visit(other, ref out_);
                        List <MgaFCO> dependents;
                        if (DependencyGraph.TryGetValue(fco, out dependents) == false)
                        {
                            dependents = DependencyGraph[fco] = new List <MgaFCO>();
                        }
                        if (other.Meta.Name == typeof(CyPhy.TestBenchRef).Name)
                        {
                            dependents.Add(other);
                        }
                    }
                    tempMarked.Remove(fco);
                    out_.Add(fco);
                    resident.Add(fco, out_);
                }
                else
                {
                    if (previousOut != out_)
                    {
                        foreach (MgaFCO fco2 in out_)
                        {
                            resident[fco2] = previousOut;
                        }
                        previousOut.AddRange(out_);
                        out_ = previousOut;
                    }
                }
            };

            if (toProcess.Count == 0)
            {
                this.Logger.WriteError("Cycle in TestBench dependencies detected");
                return(true);
            }
            while (toProcess.Count > 0)
            {
                var before = toProcess.Count;

                List <MgaFCO> out_ = new List <MgaFCO>();
                MgaFCO        fco  = toProcess.First();
                try
                {
                    Visit(fco, ref out_);
                }
                catch (CycleException ex)
                {
                    this.Logger.WriteError(ex.Message);
                    this.Logger.WriteError(ex.ToString());
                    return(true);
                }

                foreach (MgaFCO fco2 in out_)
                {
                    toProcess.Remove(fco2);
                }

                var after = toProcess.Count;
                if (after >= before)
                {
                    string msg = "Determining dependency is not progressing.";
                    this.Logger.WriteError(msg);
                    return(true);
                }
            }

            this.DependencyGraph = DependencyGraph.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Distinct().ToList());
            foreach (KeyValuePair <MgaFCO, List <MgaFCO> > fcos in DependencyGraph)
            {
                this.Logger.WriteDebug("Dependency chain {0}: {1}", fcos.Key.Name, string.Join(" ", fcos.Value.Select(x => x.Name)));
            }

            return(false);
        }
Esempio n. 5
0
        void TestAssemblySyncDiscardComponent()
        {
            SetupTest();

            RunCyPhyMLSync(
                (project, propagate, interpreter) =>
            {
                MgaFCO testAssembly;
                MgaFCO testAssemblyHierarchy_2;
                MgaFCO componentInstance;
                string componentInstanceGuid;
                string testHierarchy_1RefId;
                string testAssemblyRefId;
                project.BeginTransactionInNewTerr();
                try
                {
                    var filter   = project.CreateFilter();
                    filter.Kind  = "ComponentAssembly";
                    testAssembly = project.AllFCOs(filter).Cast <MgaFCO>()
                                   .Where(fco => fco.GetGuidDisp() == new Guid(testAssemblyId).ToString("B")).First();
                    testAssemblyHierarchy_2 = project.AllFCOs(filter).Cast <MgaFCO>()
                                              .Where(fco => fco.GetGuidDisp() == new Guid(testAssemblyHierarchy_2Id).ToString("B")).First();
                    //hullAndHookHookGuid = (string)((MgaModel)project.RootFolder.ObjectByPath[hullAndHookHookPath]).GetAttributeByNameDisp("AVMID");
                    componentInstance               = testAssembly.ChildObjects.Cast <MgaFCO>().Where(f => f.Name.Contains("Damper")).First();
                    componentInstanceGuid           = componentInstance.GetStrAttrByNameDisp("InstanceGUID");
                    MgaReference testHierarchy_1Ref = testAssemblyHierarchy_2.ChildObjects.Cast <MgaFCO>().OfType <MgaReference>().First();
                    testHierarchy_1RefId            = new Guid(testHierarchy_1Ref.GetGuidDisp()).ToString("B");
                    MgaReference testAssemblyRef    = ((MgaModel)testHierarchy_1Ref.Referred).ChildObjects.Cast <MgaFCO>().OfType <MgaReference>().First();
                    testAssemblyRefId               = new Guid(testAssemblyRef.GetGuidDisp()).ToString("B");
                }
                finally
                {
                    project.AbortTransaction();
                }
                interpreter.StartAssemblySync(project, testAssemblyHierarchy_2, 128);
                Application.DoEvents();
                // wait for metalink bridge to record addon's interest in assembly
                while (true)
                {
                    string line;
                    if (metalinkOutput.TryTake(out line, 5000) == false)
                    {
                        throw new TimeoutException("Timed out waiting for metalink bridge to log 'interest recorded'");
                    }
                    if (line.Contains("interest recorded"))
                    {
                        break;
                    }
                }
                var msg = new Edit();
                msg.mode.Add(Edit.EditMode.POST);
                msg.origin.Add(origin);
                msg.topic.Add((CyPhyMetaLinkAddon.IdCounter - 1).ToString());
                var action        = new edu.vanderbilt.isis.meta.Action();
                action.actionMode = edu.vanderbilt.isis.meta.Action.ActionMode.REMOVE_CYPHY_DESIGN_COMPONENT;
                action.subjectID  = testAssemblyHierarchy_2Id;
                action.payload    = new Payload();
                action.payload.components.Add(new CADComponentType()
                {
                    //ComponentID = hookInstanceGuid,
                    ComponentID = testHierarchy_1RefId
                                  + testAssemblyRefId
                                  + componentInstanceGuid
                });
                msg.actions.Add(action);

                SendToMetaLinkBridgeAndWaitForAddonToReceive(msg);
                WaitForAllMetaLinkMessages();
                Application.DoEvents();

                project.BeginTransactionInNewTerr();
                try
                {
                    Xunit.Assert.Equal((int)objectstatus_enum.OBJECT_DELETED, componentInstance.Status);
                }
                finally
                {
                    project.AbortTransaction();
                }
            }
                );
        }
Esempio n. 6
0
        public void Initialize(
            MgaProject project,
            MgaMetaPart meta,
            MgaFCO obj)
        {
            // only store temporarily, they might be unavailable later
            myobj     = obj;
            mymetaobj = null;
            FCOKind   = myobj?.Meta?.Name;
            MetaKind  = meta.Name;

            // obtain the metaobject
            GetMetaFCO(meta, out mymetaobj);

            if (obj != null)
            {
                // concrete object
                name = myobj.Name;
                if (myobj.Meta.Name == "Task")
                {
                    // task
                    // get progid check whether it is already in the cache
                    TaskProgId = myobj.StrAttrByName["COMName"];
                    if (interpreters.Keys.Contains(TaskProgId) == false)
                    {
                        // create an instance
                        ComComponent task = new ComComponent(TaskProgId);
                        interpreters.Add(TaskProgId, task);
                    }
                    // save parameters
                    Parameters = myobj.StrAttrByName["Parameters"];
                    h          = IconHeight;
                    w          = IconWidth;
                }
                else if (myobj.Meta.Name == "WorkflowRef")
                {
                    // Workflow reference get the tasks
                    // TODO: get those in the right order
                    workflow.Clear();
                    MgaReference   wfRef     = myobj as MgaReference;
                    Queue <string> items     = new Queue <string>();
                    List <MgaAtom> tasks     = new List <MgaAtom>();
                    List <MgaFCO>  processed = new List <MgaFCO>();

                    if (wfRef.Referred != null)
                    {
                        HashSet <string> taskKinds = new HashSet <string>()
                        {
                            "ExecutionTask",
                            "Task"
                        };
                        tasks.AddRange(wfRef.Referred.ChildObjects.OfType <MgaAtom>().Where(atom => taskKinds.Contains(atom.Meta.Name)));

                        MgaAtom StartTask = null;

                        StartTask = tasks.
                                    Where(x => x.ExSrcFcos().Count() == 0).
                                    FirstOrDefault();

                        if (StartTask != null)
                        {
                            this.EnqueueTask(StartTask as MgaFCO);
                            processed.Add(StartTask as MgaFCO);

                            MgaFCO NextTask = StartTask.ExDstFcos().FirstOrDefault();

                            // avoid loops
                            while (NextTask != null &&
                                   processed.Contains(NextTask) == false)
                            {
                                processed.Add(NextTask as MgaFCO);
                                this.EnqueueTask(NextTask);
                                NextTask = NextTask.ExDstFcos().FirstOrDefault();
                            }
                        }
                    }
                    h = IconHeight;
                    if (workflow.Count > 0)
                    {
                        w = IconWidth * workflow.Count +
                            TaskPadding * (workflow.Count - 1);
                    }
                    else
                    {
                        w = IconWidth;
                    }
                }
                else if (myobj.Meta.Name == "MetricConstraint")
                {
                    h = 40;
                    w = 40;
                    MetricConstraint_TargetType = myobj.GetStrAttrByNameDisp("TargetType");
                }
            }
            else
            {
                // not a concreter object (maybe in part browser?)
                name = mymetaobj.DisplayedName;
                h    = IconHeight;
                w    = IconWidth;
                if (MetaKind == "MetricConstraint")
                {
                    h = 40;
                    w = 40;
                }
            }

            // to handle color and labelColor settings in GME
            if (!GetColorPreference(out color, "color"))
            {
                color = Color.Black;
            }
            if (!GetColorPreference(out labelColor, "nameColor"))
            {
                labelColor = Color.Black;
            }

            // null them for sure
            // myobj = null;
            mymetaobj = null;
        }
Esempio n. 7
0
        /// <summary>
        /// Utility function to switch a reference to a model copy or instance. Reference should be deleted after this call.
        /// </summary>
        /// <remarks>In case copy is requested and the target element is a derived type (i.e. subtype or instance) inheritance chain will be cut. To make further elaboration possible.</remarks>
        /// <param name="parentModel">Parent model of the reference</param>
        /// <param name="reference">Reference to switch to a model</param>
        /// <param name="createInstance">If true creates an instance otherwise makes a copy of the target object. See remarks.</param>
        /// <returns>Model which was created instead of the reference.</returns>
        protected MgaModel SwitchReferenceToModel(MgaModel parentModel, MgaReference reference, bool createInstance)
        {
            this.LogDebug("Switching reference to model", reference);

            if (reference.Referred == null)
            {
                // failed to elaborate
                this.Logger.WriteFailed("Reference is null. {0} {1} [{2}]", reference.ID, reference.Name, reference.MetaBase.Name);
                return(null);
            }

            var referred = reference.Referred;

            // FIXME: this could fail, e.g. if componentref refers to a test component and we are in a CA
            GME.MGA.Meta.MgaMetaRole role = null;

            foreach (GME.MGA.Meta.MgaMetaRole roleItem in (parentModel.Meta as GME.MGA.Meta.MgaMetaModel)
                     .Roles)
            {
                if (roleItem.Kind.MetaRef == referred.MetaBase.MetaRef)
                {
                    role = roleItem;
                    break;
                }
            }

            if (role == null)
            {
                throw new ElaboratorException(string.Format("Role was not found for {0} [{1}] in {2} [{3}]", referred.Name, referred.MetaBase.Name, parentModel.Name, parentModel.MetaBase.Name));
            }

            MgaFCO copiedObj = null;

            Func <MgaFCO, MgaFCO, MgaFCO> getOriginalChildObject = null;

            if (createInstance)
            {
                this.LogDebug("Creating instance from", referred);

                MgaFCO originalReferred = null;
                if (UnrollConnectors)
                {
                    originalReferred = referred;
                    MgaFCO referredCopy;
                    if (ComponentCopyMap.TryGetValue(referred, out referredCopy))
                    {
                    }
                    else
                    {
                        // FIXME update traceability
                        referredCopy = referred.ParentFolder.CopyFCODisp(referred);
                        ComponentCopyMap[referred] = referredCopy;
                    }
                    referred = referredCopy;
                }

                copiedObj = parentModel.DeriveChildObject(referred, role, true);

                Func <IMgaFCO, int> getRelID = (fco) => {
                    if (fco.DerivedFrom != null && fco.IsPrimaryDerived == false)
                    {
                        // workaround GME bug fixed 2/27/2017
                        const int RELID_BASE_MAX = 0x07FFFFFF; // Mga.idl
                        return((~RELID_BASE_MAX & fco.RelID) | (RELID_BASE_MAX & fco.DerivedFrom.RelID));
                    }
                    return(fco.RelID);
                };
                Func <MgaFCO, string> getFCORelIds = fco =>
                {
                    string   ret    = "/#" + getRelID(fco);
                    MgaModel parent = fco.ParentModel;
                    while (parent != null)
                    {
                        ret    = "/#" + getRelID(parent) + ret;
                        parent = parent.ParentModel;
                    }
                    return(ret);
                };

                getOriginalChildObject = new Func <MgaFCO, MgaFCO, MgaFCO>((parent, copied) =>
                {
                    if (UnrollConnectors == false)
                    {
                        return(copied.DerivedFrom);
                    }
                    string relPath = getFCORelIds(copied.DerivedFrom).Substring(getFCORelIds(referred).Length);
                    var ret        = (MgaFCO)originalReferred.GetObjectByPathDisp(relPath);
                    if (ret == null)
                    {
                        ret = originalReferred;
                        // GME bug workaround continued
                        foreach (var relID in relPath.Substring(2).Split(new[] { "/#" }, StringSplitOptions.None))
                        {
                            ret = ret.ChildObjects.Cast <MgaFCO>().Where(f => getRelID(f).ToString() == relID).First();
                        }
                        if (ret == null)
                        {
                            throw new ArgumentNullException();
                        }
                    }
                    return(ret);
                });

                var guid = reference.StrAttrByName[AttributeNameInstanceGuid];
                if (string.IsNullOrWhiteSpace(guid))
                {
                    reference.set_StrAttrByName(AttributeNameInstanceGuid, reference.GetGuidDisp());
                    guid = reference.StrAttrByName[AttributeNameInstanceGuid];
                    this.LogDebug("InstanceGUID was empty for reference, assigned new : " + guid, reference);
                }

                // parent model should contain the concatenated InstanceGUID
                string guidConcat = parentModel.RegistryValue[RegistryNameInstanceGuidChain] + guid;

                copiedObj.RegistryValue[RegistryNameInstanceGuidChain]  = guidConcat;
                copiedObj.RegistryValue[RegistryNameOriginalReferredID] = reference.Referred.ID;

                this.LogDebug(string.Format("Overwriting InstanceGUID to {0}", guidConcat), referred);

                copiedObj.StrAttrByName[AttributeNameInstanceGuid] = guidConcat;

                copiedObj.RegistryValue[RegistryNameGmeIDChain] = parentModel.RegistryValue[RegistryNameGmeIDChain] + "," + reference.ID + "," + referred.ID;
            }
            else
            {
                this.LogDebug("Creating copy from", referred);

                copiedObj = parentModel.CopyFCODisp(referred, role);

                if (copiedObj.ArcheType != null)
                {
                    // instance or subtype
                    this.LogDebug("Cutting inheritance for copied object", copiedObj);
                    copiedObj.DetachFromArcheType();
                }

                getOriginalChildObject = new Func <MgaFCO, MgaFCO, MgaFCO>((parent, copied) =>
                {
                    // only chance to find objects are based on relids, which might not be unique
                    return(parent.ChildObjectByRelID[copied.RelID] as MgaFCO);
                });

                copiedObj.RegistryValue[RegistryNameGmeIDChain] = parentModel.RegistryValue[RegistryNameGmeIDChain] + "," + reference.ID + "," + referred.ID;

                if (reference.MetaBase.MetaRef == this.Factory.ComponentRefMeta)
                {
                    var guid = reference.StrAttrByName[AttributeNameInstanceGuid];

                    copiedObj.RegistryValue[RegistryNameInstanceGuidChain]  = parentModel.RegistryValue[RegistryNameInstanceGuidChain] + guid;
                    copiedObj.RegistryValue[RegistryNameOriginalReferredID] = reference.Referred.ID;

                    // push current instance GUID down to all component assembly elements
                    MgaFilter filter = copiedObj.Project.CreateFilter();
                    filter.ObjType = GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL.ToString();
                    // filter.Kind = "ComponentAssembly";

                    foreach (MgaFCO obj in (copiedObj as MgaModel).GetDescendantFCOs(filter))
                    {
                        if (obj.MetaBase.MetaRef == this.Factory.ComponentAssemblyMeta)
                        {
                            obj.RegistryValue[RegistryNameInstanceGuidChain] = copiedObj.RegistryValue[RegistryNameInstanceGuidChain];

                            obj.RegistryValue[RegistryNameGmeIDChain] = copiedObj.RegistryValue[RegistryNameGmeIDChain];
                        }
                    }
                }
            }

            copiedObj.Name = reference.Name;
            if (reference.Meta.MetaRef == this.Factory.ComponentRefMeta && copiedObj.Meta.MetaRef == this.Factory.ComponentAssemblyMeta)
            {
                // TODO what should happen here
                // var managedGuid = reference.StrAttrByName["ManagedGUID"]; ComponentRef does not have ManagedGUID
                var managedGuid = reference.StrAttrByName["InstanceGUID"];
                if (string.IsNullOrEmpty(managedGuid) == false)
                {
                    //    copiedObj.StrAttrByName["ManagedGUID"] = managedGuid;
                }
            }

            foreach (MgaPart part in reference.Parts)
            {
                int    x;
                int    y;
                string icon;
                part.GetGmeAttrs(out icon, out x, out y);

                try
                {
                    copiedObj.Part[part.MetaAspect].SetGmeAttrs(icon, x, y);
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    // It's okay. This means that Reference is visible in this aspect, but copiedObj isn't
                }
            }

            // add / update to traceability
            string baseId = null;

            if (this.Traceability.TryGetValue(reference.ID, out baseId))
            {
                //// if it is already in the traceability it is a temporary object.
                //// we need our final object in the mapping

                this.Traceability.Remove(reference.ID);
                this.Traceability.Add(copiedObj.ID, baseId);
            }
            else
            {
                this.Traceability.Add(copiedObj.ID, referred.ID);
            }

            // safe connection information for switching connections later.
            Dictionary <MgaFCO, MgaFCO> original2Copied = new Dictionary <MgaFCO, MgaFCO>();

            original2Copied.Add(referred, copiedObj);

            MgaFCOs objects = null;

            if (createInstance)
            {
                objects = (copiedObj as MgaModel).GetDescendantFCOs(copiedObj.Project.CreateFilter());
            }
            else
            {
                objects = (copiedObj as MgaModel).ChildFCOs;
            }

            foreach (MgaFCO copied in objects)
            {
                if (copied == copiedObj)
                {
                    continue;
                }

                var original = getOriginalChildObject(referred, copied);
                original2Copied.Add(original, copied);

                if (this.Traceability.TryGetValue(original.ID, out baseId))
                {
                    // if it is already in the traceability it is a temporary object.
                    // we need our final object in the mapping
                    this.Traceability.Remove(original.ID);
                    this.Traceability.Add(copied.ID, baseId);
                }
                else
                {
                    this.Traceability.Add(copied.ID, original.ID);
                }

                if (!createInstance && copied.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_MODEL)
                {
                    this.AddRecursivelyTraceability(copied, original);
                }
            }

            // switch connections to refport children
            foreach (MgaConnPoint connPoint in reference.UsedByConns)
            {
                var connection = connPoint.Owner as IMgaSimpleConnection;

                if (connPoint.ConnRole == "src" &&
                    connection.SrcReferences.Count > 0 &&
                    connection.SrcReferences[1] == reference)
                {
                    // what if this is instance
                    var newEndPoint = original2Copied[connection.Src];

                    if (newEndPoint == null)
                    {
                        throw new Exception("null connection endpoint");
                    }

                    // create an empty array for the connection references
                    MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType);
                    connection.SetSrc(emptyArray, newEndPoint);
                }

                if (connPoint.ConnRole == "dst" &&
                    connection.DstReferences.Count > 0 &&
                    connection.DstReferences[1] == reference)
                {
                    // what if this is instance
                    var newEndPoint = original2Copied[connection.Dst];

                    if (newEndPoint == null)
                    {
                        throw new Exception("null connection endpoint");
                    }

                    // create an empty array for the connection references
                    MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType);
                    connection.SetDst(emptyArray, newEndPoint);
                }
            }

            // switch connections to original reference object itself
            foreach (MgaConnPoint connPoint in reference.PartOfConns)
            {
                var connection = connPoint.Owner as IMgaSimpleConnection;

                if (connPoint.ConnRole == "src")
                {
                    // create an empty array for the connection references
                    MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType);
                    try
                    {
                        connection.SetSrc(emptyArray, copiedObj);
                    }
                    catch (COMException ex)
                    {
                        if (ex.Message.Contains("Illegal connection") &&
                            ex.Message.Contains("meta violation"))
                        {
                            var refID = reference.ID;
                            while (Traceability.ContainsKey(refID))
                            {
                                refID = Traceability[refID];
                            }

                            Logger.WriteWarning("<a href=\"mga:{0}\">{1}</a>'s referred type ({2}) isn't a legal SRC target for {3} connections. Skipping re-creation of this connection.",
                                                refID,
                                                reference.Name,
                                                reference.Referred.MetaBase.Name,
                                                connection.MetaBase.Name);
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
                else if (connPoint.ConnRole == "dst")
                {
                    // create an empty array for the connection references
                    MgaFCOs emptyArray = (MgaFCOs)Activator.CreateInstance(Elaborator.MgaFCOsType);
                    try
                    {
                        connection.SetDst(emptyArray, copiedObj);
                    }
                    catch (COMException ex)
                    {
                        if (ex.Message.Contains("Illegal connection") &&
                            ex.Message.Contains("meta violation"))
                        {
                            var refID = reference.ID;
                            while (Traceability.ContainsKey(refID))
                            {
                                refID = Traceability[refID];
                            }

                            Logger.WriteWarning("<a href=\"mga:{0}\">{1}</a>'s referred type ({2}) isn't a legal DST target for {3} connections. Skipping re-creation of this connection.",
                                                refID,
                                                reference.Name,
                                                reference.Referred.MetaBase.Name,
                                                connection.MetaBase.Name);
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
            }

            return(copiedObj as MgaModel);
        }
Esempio n. 8
0
 public static ISIS.GME.Common.Interfaces.FCO CastReferred(
     MgaReference mgaReference,
     Dictionary <int, Type> metaRefTypes)
 {
     return(CastReferred(mgaReference, metaRefTypes, "<unknown>"));
 }
Esempio n. 9
0
 private static string[] GetSourcePath(MgaReference refe, MgaFCO port)
 {
     MgaConnPoint sources;
     if (refe != null)
     {
         sources = port.PartOfConns.Cast<MgaConnPoint>().Where(cp => cp.References != null && cp.References.Count > 0 && cp.References[1].ID == refe.ID && cp.ConnRole == "dst").FirstOrDefault();
     }
     else
     {
         sources = port.PartOfConns.Cast<MgaConnPoint>().Where(cp => (cp.References == null || cp.References.Count == 0) && cp.ConnRole == "dst").FirstOrDefault();
     }
     if (sources == null)
     {
         return null;
     }
     var source = (MgaSimpleConnection)sources.Owner;
     string parentName;
     if (source.SrcReferences != null && source.SrcReferences.Count > 0)
     {
         parentName = source.SrcReferences[1].Name;
     }
     else
     {
         parentName = source.Src.ParentModel.Name;
     }
     var sourcePath = new string[] { parentName, source.Src.Name };
     return sourcePath;
 }
Esempio n. 10
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            if (currentobj == null)
            {
                GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName);
                return;
            }
            else if (currentobj.Meta.Name != "TestBench")
            {
                GMEConsole.Error.WriteLine("Please open a TestBench to run {0}.", ComponentName);
                return;
            }

            GMEConsole.Info.WriteLine("Running {0} on TestBench '{1}'", ComponentName, currentobj.Name);

            // get root folder
            IMgaFolder rootFolder = project.RootFolder;

            this.currentobj = ISIS.GME.Dsml.CyPhyML.Classes.TestBench.Cast(currentobj);
            this.sut        = this.currentobj.Children.TopLevelSystemUnderTestCollection.First();

            MgaReference workflowRef = ((MgaModel)currentobj).ChildFCOs.Cast <MgaFCO>().Where(fco => fco.Meta.Name == "WorkflowRef").FirstOrDefault() as MgaReference;
            MgaFCO       spiceTask   = null;

            if (workflowRef != null && workflowRef.Referred != null)
            {
                foreach (var task in ((MgaModel)workflowRef.Referred).ChildFCOs.Cast <MgaFCO>().Where(fco => fco.Meta.Name == "Task"))
                {
                    if (task.GetStrAttrByNameDisp("COMName").Equals("MGA.Interpreter.CyPhy2Schematic", StringComparison.InvariantCultureIgnoreCase))
                    {
                        spiceTask = task;
                    }
                }
            }
            if (spiceTask != null)
            {
                DoSpiceFidelitySelection(currentobj);
                return;
            }

            // create a filter for components
            MgaFilter filter = project.CreateFilter();

            filter.Kind = "Component";

            // get all components
            var components = project.AllFCOs(filter).OfType <IMgaModel>().Cast <IMgaModel>().ToList();

            // store components that may have an option (e.g. MM1, MM2)
            List <IMgaModel> componentsToShow = new List <IMgaModel>();

            // iterate through all components
            // select only those which has more than one modelica model in it
            foreach (var component in components)
            {
                var modelicaModels = component.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "ModelicaModel");
                if (modelicaModels.Count() > 1)
                {
                    componentsToShow.Add(component);
                }
            }

            using (FidelitySelectorForm fsf = new FidelitySelectorForm())
            {
                // show the form for the user
                foreach (var component in componentsToShow)
                {
                    if (fsf.componentItems.FirstOrDefault(
                            x => x.Classification == component.StrAttrByName["Classifications"]) == null)
                    {
                        fsf.componentItems.Add(new ComponentItem(component));
                    }
                }

                // get the current fidelity settings from the Testbench registry
                fsf.FidelitySettings = currentobj.RegistryValue["FidelitySettings"];

                fsf.PopulateDgv();
                fsf.ShowDialog();

                foreach (string msg in fsf.consoleMessages)
                {
                    GMEConsole.Info.WriteLine(msg);
                }

                // Check where the new fidelity settings should be applied:
                if (fsf.rbThisTestbench.Checked)
                {
                    // Write the updated fidelity settings back to the Testbench registry
                    currentobj.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;
                }
                else if (fsf.rbThisFolder.Checked)
                {
                    // Get all testbenches in the same folder as currentobj
                    var thisTestingFolder = currentobj.ParentFolder;
                    var siblingTBs        =
                        thisTestingFolder.ChildFCOs.Cast <IMgaFCO>().Where(x => x.Meta.Name == "TestBench").ToList();

                    GMEConsole.Info.WriteLine(
                        "Applying these FidelitySettings to all TestBenches in folder '{0}':", thisTestingFolder.Name);

                    // Go through each one and set the fidelity settings
                    foreach (MgaFCO testbench in siblingTBs)
                    {
                        testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;

                        GMEConsole.Info.WriteLine("=> {0}", testbench.Name);
                    }
                }
                else if (fsf.rbThisProject.Checked)
                {
                    // Get all testbenches in the entire project
                    MgaFilter testbenchFilter = project.CreateFilter();
                    testbenchFilter.Kind = "TestBench";

                    // get all testbenches
                    var testbenches = project.AllFCOs(testbenchFilter).OfType <IMgaModel>().Cast <IMgaModel>().ToList();

                    GMEConsole.Info.WriteLine(
                        "Applying these FidelitySettings to all TestBenches in project '{0}':", project.Name);

                    // Go through each one and set the fidelity settings
                    foreach (MgaFCO testbench in testbenches)
                    {
                        testbench.RegistryValue["FidelitySettings"] = fsf.FidelitySettings;

                        GMEConsole.Info.WriteLine("=> {0}", testbench.Name);
                    }
                }
            }


            GMEConsole.Info.WriteLine("{0} finished.", ComponentName);
        }