Ejemplo n.º 1
0
        /// <summary>
        /// Register an instance receptor living in a membrane type.
        /// </summary>
        public void Register <M>(IReceptor receptor)
            where M : IMembrane, new()
        {
            IMembrane membrane = RegisterMembrane <M>();

            Register(membrane, receptor);
        }
Ejemplo n.º 2
0
        public void ProcessInstanceFrom <M>(IMembrane fromMembrane, IReceptor fromReceptor, ISemanticType obj, bool processOnCallerThread = false)
            where M : IMembrane, new()
        {
            IMembrane m = RegisterMembrane <M>();

            ProcessInstanceWithInvoke(m, null, obj, processOnCallerThread, fromMembrane, fromReceptor);
        }
Ejemplo n.º 3
0
 public void RegisterQualifier <T>(IReceptor receptor, Func <ISemanticQualifier, bool> qualifier) where T : ISemanticQualifier
 {
     qualifiers.Add(new SemanticQualifier()
     {
         SemanticType = typeof(T), Receptor = receptor, Qualifier = qualifier
     });
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Returns true if there is an enabled target from the specified receptor with the specified protocol.
        /// </summary>
        protected bool TargetReceptorExistsFor(IReceptor from, ISemanticTypeStruct protocol, bool isRoot)
        {
            bool ret = false;

            // Some bullet proofing that was revealed in unit testing.
            if (from != null)
            {
                List <IReceptorConnection> targets = new List <IReceptorConnection>();
                if (MasterReceptorConnectionList.TryGetValue(from, out targets))
                {
                    // This annoying piece of code assumes that a receptor will have only one connection between "from" to "to".
                    // In the case of the semantic database, a "from" receptor can have multiple connections with the same semantic database receptor.
                    // In other words, the returned list consists of [n] identical instances, where [n] is the number of different protocols from "from" to the target receptor.
                    // To fix this problem, we get only the distinct instances.
                    targets = targets.Distinct().ToList();
                    // We're only interested in enabled receptors, and we ignore ourselves.
                    ret = targets.Any(r => r.Receptor != from &&
                                      r.Receptor.Instance.Enabled &&
                                      (!r.RootOnly || isRoot) &&                                // root protocol or we don't care if it's not the root.
                                      r.Receptor.Instance.GetEnabledReceiveProtocols().Select(rp => rp.Protocol).Contains(protocol.DeclTypeName));
                }

                if (!ret)
                {
                    // check protocol map for receivers that are not the issuing receptor, ignoring ourselves.
                    ret = protocolReceptorMap.Any(kvp => (kvp.Key == protocol.DeclTypeName) &&
                                                  kvp.Value.Any(r => (r.Receptor != from) &&
                                                                (!r.RootOnly || isRoot) &&       // root protocol or we don't care if it's not the root.
                                                                (r.Receptor.Instance.Enabled))); // .ContainsKey(protocol.DeclTypeName);
                }
            }

            return(ret);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get the protocols that this receptor is receiving, updating the protocolReceptorMap, adding this
        /// receptor to the specified protocols.
        /// </summary>
        protected void GatherProtocolReceivers(IReceptor r)
        {
            // For each protocol...
            r.Instance.GetReceiveProtocols().ForEach(rq =>
            {
                // If it's a wildcard receptor, we handle it differently because "*" is a magic protocol.
                if (rq.Protocol == "*")
                {
                    // This is a global receiver.  Attach it to all current carrier receptors, but don't create an instance in the CarrierReceptorMap.
                    protocolReceptorMap.ForEach(kvp => kvp.Value.Add(new ReceptorConnection(r)));
                    globalReceptors.Add(r);
                }
                else
                {
                    // Get the list of receiving receptors for the protocol, or, if it doesn't exist, create it.
                    List <IReceptorConnection> receivingReceptors;

                    if (!protocolReceptorMap.TryGetValue(rq.Protocol, out receivingReceptors))
                    {
                        receivingReceptors = new List <IReceptorConnection>();
                        protocolReceptorMap[rq.Protocol] = receivingReceptors;
                        // Append all current global receptors to this protocol - receptor map.
                        globalReceptors.ForEach(gr => receivingReceptors.Add(new ReceptorConnection(gr)));
                    }

                    // Associate the receptor with the protocol it receives.
                    protocolReceptorMap[rq.Protocol].Add(new ReceptorConnection(r));
                }
            });
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Serialize user configurable attributes.  These are properties of a receptor instance with the UserConfigurablePropertyAttribute attribute.
        /// </summary>
        protected void SerializeReceptorUserConfigurableProperties(XmlNode rNode, IReceptor r)
        {
            bool    createdCollectionNode = false;
            XmlNode uiConfigs             = null;

            r.Instance.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ForEach(prop =>
            {
                if (prop.GetCustomAttribute(typeof(UserConfigurablePropertyAttribute)) != null)
                {
                    object obj = prop.GetValue(r.Instance);
                    string val = String.Empty;
                    obj.IfNotNull(o =>
                    {
                        if (!createdCollectionNode)
                        {
                            // Add collection node.
                            uiConfigs = rNode.OwnerDocument.CreateElement("ixm", "UserConfigs", "TypeSystemExplorer.Models, TypeSystemExplorer");
                            rNode.AppendChild(uiConfigs);
                            createdCollectionNode = true;
                        }

                        // Don't serialize null value properties.
                        val            = o.ToString();
                        XmlNode uiNode = uiConfigs.OwnerDocument.CreateElement("ixm", "UserConfig", "TypeSystemExplorer.Models, TypeSystemExplorer");
                        AddAttribute(uiNode, "Name", prop.Name);
                        AddAttribute(uiNode, "Value", val);
                        uiConfigs.AppendChild(uiNode);
                    });
                }
            });
        }
Ejemplo n.º 7
0
        public void RemoveTypeNotify <TMembrane, TSource>(IReceptor receptor)
            where TMembrane : IMembrane
            where TSource : ISemanticType
        {
            Type        tsource   = typeof(TSource);
            Type        treceptor = receptor.GetType();
            IMembrane   membrane  = membranes[typeof(TMembrane)];
            List <Type> targets   = GetReceptors(membrane, tsource);

            // Remove from type list for this membrane this receptor, by its type.
            foreach (Type ttarget in targets)
            {
                typeNotifiers[tsource].Remove(ttarget);
            }

            // Remove from instance list.
            List <IReceptor> instanceReceptors = GetStatefulReceptors(membrane, tsource);

            foreach (IReceptor ireceptor in instanceReceptors)
            {
                // Remove only this instance receptor from its membrane.
                if (ireceptor == receptor)
                {
                    instanceNotifiers[tsource].Remove(receptor);
                }
            }
        }
Ejemplo n.º 8
0
        public byte[][] envia(IReceptor receptor, string mensagem)
        {
            var _chavePrivada = this.dados.DeriveKeyMaterial(CngKey.Import(receptor.chaveIndividual, CngKeyBlobFormat.EccPublicBlob));

            //...
            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key = _chavePrivada;
                //iv = aes.IV;

                // Encrypt the message
                using (MemoryStream ciphertext = new MemoryStream())
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] plaintextMessage = Encoding.UTF8.GetBytes(mensagem);
                        cs.Write(plaintextMessage, 0, plaintextMessage.Length);
                        cs.Close();
                        //encryptedMessage = ciphertext.ToArray();
                        return(new byte[][] {
                            aes.IV,
                            ciphertext.ToArray()
                        });
                    }
            }
        }
Ejemplo n.º 9
0
        public void InstantiateReceptor(string typeName)
        {
            var       agent    = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(at => at.IsClass && at.IsPublic && at.Name == typeName);
            IReceptor receptor = (IReceptor)Activator.CreateInstance(agent);

            sp.Register <HopeMembrane>(receptor);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This method executes the main context steering algorithm and is called within <see cref="Context.Evaluate"/>
        /// in order to set/modify objective values for the associated <see cref="Context.Problem"/>. It pre-caches
        /// multiple references for quick access in the three called steering methods, projects vector data as specified
        /// with <see cref="VectorProjection"/> and finally obtain/write objective values based on the set <see
        /// cref="ValueMapping"/> and <see cref="ValueWriting"/>.
        /// <para/>
        /// For each existing instance in <see cref="PerceptBehaviour{T}.Percepts"/>, the <see cref="ResultDirection"/>
        /// and <see cref="ResultMagnitude"/> are used for obtaining the objective values so that they need to be set
        /// through the implementation of <see cref="StartSteering"/>, <see cref="PerceptSteering"/> and <see
        /// cref="ReceptorSteering"/> in derived <see cref="SteeringBehaviour"/> classes.
        /// <para/>
        /// The final objective value which is written for one corresponding receptor is a sum which is obtained by
        /// weighting the angle between the <see cref="ResultDirection"/> and receptor direction, considering the <see
        /// cref="ResultMagnitude"/> and, optionally, the <see cref="SteeringPercept.Significance"/>.
        /// </summary>
        /// <exception cref="NullReferenceException">
        /// If the inherited <see cref="MoveBehaviour.Context"/> or its associated <see cref="Context.Problem"/>
        /// respectively <see cref="Context{TValue, TStructure}.Sensor"/> are <c>null</c>.
        /// </exception>
        public override void Behave()
        {
            if (TargetObjective < 0 || TargetObjective >= Context.Problem.ObjectiveCount)
            {
                return;
            }

            // Pre-caching (for derived behaviours)
            objective = Context.Problem.GetObjective(TargetObjective);
            sensor    = Context.Sensor;

            // Project self vectors if necessary
            self.Project(VectorProjection);

            for (int i = 0; i < Percepts.Count; i++)
            {
                if (!Percepts[i].Active)
                {
                    continue;
                }

                // Copy (for derived behaviours)
                percept.Copy(Percepts[i]);

                // Project percept vectors if necessary
                percept.Project(VectorProjection);

                // Inject custom steering code at the beginning
                if (!StartSteering())
                {
                    continue;
                }

                // Inject custom steering code per percept
                if (forEachPercept)
                {
                    PerceptSteering();
                }

                for (int j = 0; j < sensor.ReceptorCount; j++)
                {
                    // Pre-caching (for derived behaviours)
                    receptor  = sensor[j];
                    structure = receptor.Structure;

                    // Inject custom steering code per receptor
                    if (forEachReceptor)
                    {
                        ReceptorSteering();
                    }

                    // Compute and write objective value
                    float value = (UseSignificance ? percept.Significance : 1f) *
                                  MagnitudeMultiplier * structure.Magnitude * ResultMagnitude *
                                  MapBySensitivity(ValueMapping, structure, ResultDirection, SensitivityOffset);
                    WriteValue(ValueWriting, TargetObjective, receptor.ID, value);
                }
            }
        }
Ejemplo n.º 11
0
 public ProcessEventArgs(IMembrane fromMembrane, IReceptor fromReceptor, IMembrane toMembrane, IReceptor toReceptor, ISemanticType st)
 {
     FromMembrane = fromMembrane;
     FromReceptor = fromReceptor;
     ToMembrane   = toMembrane;
     ToReceptor   = toReceptor;
     SemanticType = st;
 }
Ejemplo n.º 12
0
        public void InstantiateReceptor(string name)
        {
            Type      t    = assy.GetTypes().Single(at => at.Name == name);
            IReceptor inst = (IReceptor)Activator.CreateInstance(t);

            // sp.Register(membrane, inst);
            sp.Register <App.HopeMembrane>(inst);
        }
Ejemplo n.º 13
0
        public void ProcessInstanceFrom <M, T>(IMembrane fromMembrane, IReceptor fromReceptor, bool processOnCallerThread = false)
            where M : IMembrane, new()
            where T : ISemanticType, new()
        {
            T inst = new T();

            ProcessInstanceFrom <M, T>(fromMembrane, fromReceptor, inst, processOnCallerThread);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Process an instance in a given membrane type.
        /// </summary>
        public void ProcessInstanceFrom <M, T>(IMembrane fromMembrane, IReceptor fromReceptor, T obj, bool processOnCallerThread = false)
            where M : IMembrane, new()
            where T : ISemanticType
        {
            Type      mtype    = typeof(M);
            IMembrane membrane = RegisterMembrane <M>();

            ProcessInstanceFrom(fromMembrane, fromReceptor, membrane, obj, processOnCallerThread);
        }
Ejemplo n.º 15
0
 public void Store(IReceptor receptor)
 {
     var name = receptor.GetType().Name;
     if (name.IndexOf("Receptor") > 0)
     {
         name = name.Substring(0, name.Length - 8);
     }
     Store(name, receptor);
 }
Ejemplo n.º 16
0
        // ===========================================================

        // For processing events, where we want to know the caller membrane and ST.
        // We could create these as overloads, but appending "From" to the method name makes it
        // clearer that this the intent of the caller is to provide as much information as possible
        // about the publishing of the ST onto to pub-sub bus.

        /// <summary>
        /// Process a semantic type, allowing the caller to specify an initializer before processing the instance.
        /// </summary>
        public void ProcessInstanceFrom <M, T>(IMembrane fromMembrane, IReceptor fromReceptor, Action <T> initializer, bool processOnCallerThread = false)
            where M : IMembrane, new()
            where T : ISemanticType, new()
        {
            T inst = new T();

            initializer.IfNotNull(i => i(inst));
            ProcessInstanceFrom <M, T>(fromMembrane, fromReceptor, inst, processOnCallerThread);
        }
Ejemplo n.º 17
0
        public ProcStates ProcessInstanceFrom <M, T>(IMembrane fromMembrane, IReceptor fromReceptor, Action <T> initializer, int msTimeout)
            where M : IMembrane, new()
            where T : ISemanticType, new()
        {
            T inst = new T();

            initializer.IfNotNull(i => i(inst));
            return(ProcessInstanceFrom <M, T>(fromMembrane, fromReceptor, inst, msTimeout));
        }
Ejemplo n.º 18
0
        public ProcStates ProcessInstanceFrom <M, T>(IMembrane fromMembrane, IReceptor fromReceptor, T obj, int msTimeout)
            where M : IMembrane, new()
            where T : ISemanticType
        {
            Type      mtype    = typeof(M);
            IMembrane membrane = RegisterMembrane <M>();

            return(ProcessInstanceFrom(fromMembrane, fromReceptor, membrane, obj, msTimeout));
        }
Ejemplo n.º 19
0
        public void Unregister(IMembrane membrane, IReceptor receptor)
        {
            if (receptor is IDisposable)
            {
                ((IDisposable)receptor).Dispose();
            }

            statefulReceptors.Remove(receptor);
            membraneReceptorInstances[membrane].Remove(receptor);
        }
Ejemplo n.º 20
0
        public virtual void Subject(IReceptor receptor)
        {
            var name = nameof(receptor);

            if (name.IndexOf("Receptor") > 0)
            {
                name = name.Substring(0, name.Length - 8);
            }
            Subject(name, receptor);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Add the receptor, without generating add events.
 /// </summary>
 protected void InternalAdd(IReceptor receptor)
 {
     // TODO: If receptors was List<IReceptor>, we wouldn't need this cast.
     receptors.Add(receptor as Receptor);
     registeredReceptorMap[receptor] = true;
     // The receptor instance is now using this receptor system!
     receptor.Instance.ReceptorSystem = this;
     // Process any queued carriers that may now become active.
     ReloadProtocolReceptorMap();
     ProcessQueuedCarriers();
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Remove the receptor without generating remove events or terminating the receptor.
        /// </summary>
        protected void InternalRemove(IReceptor receptor)
        {
            receptors.Remove(receptor as Receptor);
            registeredReceptorMap.Remove(receptor);

            protocolReceptorMap.ForEach(kvp =>
            {
                IReceptorConnection conn = kvp.Value.SingleOrDefault(rc => rc.Receptor == receptor);
                conn.IfNotNull(c => kvp.Value.Remove(c));
            });
        }
Ejemplo n.º 23
0
        protected void InstanceNotify(IReceptor receptor, Type tsource)
        {
            List <IReceptor> targets;

            if (!instanceNotifiers.TryGetValue(tsource, out targets))
            {
                targets = new List <IReceptor>();
                instanceNotifiers[tsource] = targets;
            }

            targets.Add(receptor);
        }
Ejemplo n.º 24
0
 public void Unstore(string name, IReceptor receptor)
 {
     IEnumerable<IReceptor> receps;
     if (Dictionary.ContainsKey(name))
     {
         receps = Dictionary[name];
         receps = receps.Where(m => !m.Equals(receptor));
         Dictionary.AddOrUpdate(name, receps, (key, pre) => {
             return receps;
         });
     }
 }
Ejemplo n.º 25
0
        // TODO: This code needs to be optimized.
        /// <summary>
        /// Returns the target receptors that will receive the carrier protocol, qualified by the receptor's optional condition on the signal.
        /// </summary>
        protected List <IReceptor> GetTargetReceptorsFor(IReceptor from, ICarrier carrier)
        {
            List <IReceptor>    targets;
            ISemanticTypeStruct protocol = carrier.Protocol;

            // When the try fails, it sets targets to null.
            if (!MasterReceptorConnectionList.TryGetValue(from, out targets))
            {
                targets = new List <IReceptor>();
            }

            // Only enabled receptors and receptors that are not the source of the carrier.
            List <IReceptor> filteredTargets = targets.Where(r => r != from && r.Enabled && r.Instance.GetReceiveProtocols().Select(rq => rq.Protocol).Contains(protocol.DeclTypeName)).ToList();

            // Will have a count of 0 if the receptor is the system receptor, ie, carrier animations or other protocols.
            // TODO: This seems kludgy, is there a better way of working with this?
            // Also, if the emitting receptor doesn't declare its protocol, this count will be 0, leading to potentially strange results.
            // For example, comment out the persistence receptors "IDReturn" and run the feed reader example.  You'll see that TWO items
            // are returned as matching "RSSFeed" table name and for reasons unknown at the moment, protocolReceptorMap has two entries that qualify.
            if (filteredTargets.Count == 0)
            {
                // When the try fails, it sets targets to null.
                if (protocolReceptorMap.TryGetValue(protocol.DeclTypeName, out targets))
                {
                    filteredTargets = targets.Where(r => r.Enabled && (r != from)).ToList();
                }
            }

            // Lastly, filter the list by qualified receptors that are not the source of the carrier.
            List <IReceptor> newTargets = new List <IReceptor>();

            filteredTargets.Where(r => r != from && r.Enabled).ForEach(t =>
            {
                // Get the list of receive actions and filters for the specific protocol.
                var receiveList = t.Instance.GetReceiveProtocols().Where(rp => rp.Protocol == protocol.DeclTypeName);
                receiveList.ForEach(r =>
                {
                    // If qualified, add to the final target list.
                    if (r.Qualifier(carrier.Signal))
                    {
                        newTargets.Add(t);
                    }
                });
            });

            // filteredTargets = filteredTargets.Where(t => t.Instance.GetReceiveProtocols().Any(rp => (rp.Protocol == protocol.DeclTypeName) && rp.Qualifier(carrier.Signal))).ToList();

            // Get the targets of the single receive protocol that matches the DeclTypeName and whose qualifier returns true.
            // filteredTargets = filteredTargets.Where(t => t.Instance.GetReceiveProtocols().Single(rp => rp.Protocol == protocol.DeclTypeName).Qualifier(carrier.Signal)).ToList();

            return(newTargets);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Removes a receptor from the system.  Before being removed, the receptor's Terminate()
        /// method is called so that it can do whatever cleanup is required.
        /// </summary>
        /// <param name="receptor"></param>
        public void Remove(IReceptor receptor)
        {
            receptor.Instance.Terminate();
            // TODO: If our collections were IReceptor, then we wouldn't need the "as".
            receptors.Remove(receptor as Receptor);
            registeredReceptorMap.Remove(receptor);
            protocolReceptorMap.ForEach(kvp => kvp.Value.Remove(receptor as Receptor));
            ReceptorRemoved.Fire(this, new ReceptorEventArgs(receptor));

            // TODO: Refactor out of this code.
            // TODO: Add a "RemovedReceptor" event.
            Say("Receptor " + receptor.Name + " removed.");
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Return true if the receptor-semantic type pair does not have any qualifiers,
        /// or if it does, that at least one qualifier returns true.
        /// </summary>
        protected bool IsQualified(Dictionary <SemanticQualifier, bool> qstate, IReceptor receptor, ISemanticType obj)
        {
            bool ret = true;
            // Only stateful receptors can have qualifiers, since the qualifier tests against a receptor state.
            var checkReceptors = qualifiers.Where(q => q.Receptor == receptor && q.SemanticType == obj.GetType());

            if (checkReceptors.Count() > 0)
            {
                ret = checkReceptors.Any(q => qstate[q]);
            }

            return(ret);
        }
Ejemplo n.º 28
0
 public void Store(string name, IReceptor receptor)
 {
     if (Dictionary.ContainsKey(name))
     {
         var iqueue = Dictionary[name];
         iqueue.Enqueue(receptor);
     }
     else
     {
         IQueue <IReceptor> queue = new PriorityQueue <IReceptor>();
         queue.Enqueue(receptor);
         Dictionary.TryAdd(name, queue);
     }
 }
Ejemplo n.º 29
0
 public void Store(string name, IReceptor receptor)
 {
     if (Dictionary.ContainsKey(name))
     {
         var iqueue = Dictionary[name];
         iqueue.Append(receptor);
     }
     else
     {
         IEnumerable<IReceptor> queue = new List<IReceptor>();
         queue.Append(receptor);
         Dictionary.TryAdd(name, queue);
     }
 }
Ejemplo n.º 30
0
 public void Unstore(string name, IReceptor receptor)
 {
     if (Dictionary.ContainsKey(name))
     {
         IQueue <IReceptor> iq;
         Dictionary.TryGetValue(name, out iq);
         if (iq == null)
         {
             return;
         }
         var iqclone = iq.Clone();
         var it      = iqclone.Dequeue();
         do
         {
             iqclone.Enqueue(it);
             it = iqclone.Dequeue();
         }while (iqclone.Count > 0);
     }
 }
Ejemplo n.º 31
0
		/// <summary>
		/// Removes a receptor from the system.  Before being removed, the receptor's Terminate() 
		/// method is called so that it can do whatever cleanup is required.
		/// </summary>
		/// <param name="receptor"></param>
		public void Remove(IReceptor receptor)
		{
			receptor.Instance.Terminate();
			// TODO: If our collections were IReceptor, then we wouldn't need the "as".
			receptors.Remove(receptor as Receptor);
			registeredReceptorMap.Remove(receptor);

			protocolReceptorMap.ForEach(kvp =>
			{
				IReceptorConnection conn = kvp.Value.SingleOrDefault(rc => rc.Receptor == receptor);
				conn.IfNotNull(c => kvp.Value.Remove(c));
			});

			ReceptorRemoved.Fire(this, new ReceptorEventArgs(receptor));

			// TODO: Refactor out of this code.
			// TODO: Add a "RemovedReceptor" event.
			Say("Receptor " + receptor.Name + " removed.");
		}
Ejemplo n.º 32
0
		public ReceptorEventArgs(IReceptor receptor)
		{
			Receptor = receptor;
		}
Ejemplo n.º 33
0
		static void InitializeSemantics(IReceptor form)
		{
			// SemProc = new SemanticProcessor();
			// SemProc.Register<SurfaceMembrane, FeedReaderReceptor>();
			// SemProc.Register<LoggerMembrane, LoggingReceptor>();
		}
Ejemplo n.º 34
0
		// TODO: Maintain a flat list to avoid this recursion.
		/// <summary>
		/// Recurse through membranes to find the membrane containing the desired receptor.
		/// </summary>
		public Membrane GetMembraneContaining(IReceptor searchFor)
		{
			Membrane ret = null;

			if (Receptors.Contains((Receptor)searchFor))
			{
				ret = this;
			}
			else
			{
				foreach (Membrane childMembrane in Membranes)
				{
					ret = childMembrane.GetMembraneContaining(searchFor);

					if (ret != null)
					{
						break;
					}
				}
			}

			return ret;
		}
Ejemplo n.º 35
0
		// TODO: This code needs to be optimized.
		/// <summary>
		/// Returns the target receptors that will receive the carrier protocol, qualified by the receptor's optional condition on the signal.
		/// </summary>
		protected List<IReceptorConnection> GetTargetReceptorsFor(IReceptor from, ICarrier carrier, bool isRoot)
		{
			// Lastly, filter the list by qualified receptors that are not the source of the carrier.
			List<IReceptorConnection> newTargets = new List<IReceptorConnection>();

			// From can be null if we're changing the layout during the time when carriers are being processed,
			// specifically, when a receptor is moved into or out of a membrane or the receptor is taken off the surface.
			if (from != null)
			{
				List<IReceptorConnection> targets;
				ISemanticTypeStruct protocol = carrier.Protocol;

				// This annoying piece of code assumes that a receptor will have only one connection between "from" to "to".
				// In the case of the semantic database, a "from" receptor can have multiple connections with the same semantic database receptor.
				// In other words, the returned list consists of [n] identical instances, where [n] is the number of different protocols from "from" to the target receptor.
				if (!MasterReceptorConnectionList.TryGetValue(from, out targets))
				{
					// When the try fails, it sets targets to null.
					targets = new List<IReceptorConnection>();
				}

				// To fix the aformentioned problem, we get only the distinct instances.
				targets = targets.Distinct().ToList();

				// Only enabled receptors and receptors that are not the source of the carrier and our not ourselves.
				List<IReceptorConnection> filteredTargets = targets.Where(r => 
					(!r.RootOnly || isRoot) && 
					r.Receptor != from && 
					r.Receptor.Instance.Enabled && 
					r.PermeabilityProtocol == protocol.DeclTypeName).ToList(); // &&
					// r.Receptor.Instance.GetEnabledReceiveProtocols().Select(rq => rq.Protocol).Contains(protocol.DeclTypeName)).ToList();

				// Will have a count of 0 if the receptor is the system receptor, ie, carrier animations or other protocols.
				// TODO: This seems kludgy, is there a better way of working with this?
				// Also, if the emitting receptor doesn't declare its protocol, this count will be 0, leading to potentially strange results.
				// For example, comment out the persistence receptors "IDReturn" and run the feed reader example.  You'll see that TWO items
				// are returned as matching "RSSFeed" table name and for reasons unknown at the moment, protocolReceptorMap has two entries that qualify.
				if (filteredTargets.Count == 0)
				{
					// When the try fails, it sets targets to null.
					if (protocolReceptorMap.TryGetValue(protocol.DeclTypeName, out targets))
					{
						filteredTargets = targets.Where(r => r.Receptor.Instance.Enabled && (r.Receptor != from) && true).ToList();
						// Remove disabled receive protocols.
						filteredTargets = filteredTargets.Where(r => r.Receptor.Instance.GetReceiveProtocols().Exists(p => p.Protocol == protocol.DeclTypeName && p.Enabled)).ToList();
					}
				}

				filteredTargets.Where(r => r.Receptor != from && r.Receptor.Instance.Enabled).ForEach(t =>
					{
						// The PermeableProtocol may be a higher level protocol than the receiver receives, so we need to find the receivers that have sub-protocols of the current protocol enabled.
						List<ISemanticTypeStruct> protocols = protocol.FlattenedSemanticTypes();
						protocols.ForEach(se =>
							{
								string prot = se.DeclTypeName;
								// Get the list of receive actions and filters for the specific protocol.
								var receiveList = t.Receptor.Instance.GetEnabledReceiveProtocols().Where(rp => rp.Protocol == prot);
								receiveList.ForEach(r =>
									{
										// If qualified, add to the final target list.
										// REF: 03282015
										// TODO: It looks like we're already doing a qualifier check in BaseReceptor.  Probably we can remove THAT check!
										if (r.Qualifier(carrier.Signal))
										{
											newTargets.Add(t);
										}
									});
							});
					});

				// filteredTargets = filteredTargets.Where(t => t.Instance.GetReceiveProtocols().Any(rp => (rp.Protocol == protocol.DeclTypeName) && rp.Qualifier(carrier.Signal))).ToList();

				// Get the targets of the single receive protocol that matches the DeclTypeName and whose qualifier returns true.
				// filteredTargets = filteredTargets.Where(t => t.Instance.GetReceiveProtocols().Single(rp => rp.Protocol == protocol.DeclTypeName).Qualifier(carrier.Signal)).ToList();
			}
			else
			{
				// TODO: Should we log this error so we can further inspect the effects that it may have on processing carriers?
			}

			return newTargets;
		}
Ejemplo n.º 36
0
		/// <summary>
		/// TODO: Remove this to outside this class.
		/// </summary>
		/// <param name="r"></param>
		protected void AnnounceReceptor(IReceptor r)
		{
			Say("Receptor " + r.Name + " online.");
		}
Ejemplo n.º 37
0
		/// <summary>
		/// Get the protocols that this receptor is receiving, updating the protocolReceptorMap, adding this
		/// receptor to the specified protocols.
		/// </summary>
		protected void GatherProtocolReceivers(IReceptor r)
		{
			// For each protocol...
			r.Instance.GetReceiveProtocols().ForEach(rq =>
				{
					// If it's a wildcard receptor, we handle it differently because "*" is a magic protocol.
					if (rq.Protocol == "*")
					{
						// This is a global receiver.  Attach it to all current carrier receptors, but don't create an instance in the CarrierReceptorMap.
						protocolReceptorMap.ForEach(kvp => kvp.Value.Add(new ReceptorConnection(r)));
						globalReceptors.Add(r);
					}
					else
					{
						// Get the list of receiving receptors for the protocol, or, if it doesn't exist, create it.
						List<IReceptorConnection> receivingReceptors;

						if (!protocolReceptorMap.TryGetValue(rq.Protocol, out receivingReceptors))
						{
							receivingReceptors = new List<IReceptorConnection>();
							protocolReceptorMap[rq.Protocol] = receivingReceptors;
							// Append all current global receptors to this protocol - receptor map.
							globalReceptors.ForEach(gr => receivingReceptors.Add(new ReceptorConnection(gr)));
						}

						// Associate the receptor with the protocol it receives.
						protocolReceptorMap[rq.Protocol].Add(new ReceptorConnection(r));
					}
				});
		}
Ejemplo n.º 38
0
		/// <summary>
		/// Returns true if there is an enabled target from the specified receptor with the specified protocol.
		/// </summary>
		protected bool TargetReceptorExistsFor(IReceptor from, ISemanticTypeStruct protocol, bool isRoot)
		{
			bool ret = false;

			// Some bullet proofing that was revealed in unit testing.
			if (from != null)
			{
				List<IReceptorConnection> targets = new List<IReceptorConnection>();
				if (MasterReceptorConnectionList.TryGetValue(from, out targets))
				{
					// This annoying piece of code assumes that a receptor will have only one connection between "from" to "to".
					// In the case of the semantic database, a "from" receptor can have multiple connections with the same semantic database receptor.
					// In other words, the returned list consists of [n] identical instances, where [n] is the number of different protocols from "from" to the target receptor.
					// To fix this problem, we get only the distinct instances.
					targets = targets.Distinct().ToList();
					// We're only interested in enabled receptors, and we ignore ourselves.
					ret = targets.Any(r => r.Receptor != from && 
						r.Receptor.Instance.Enabled && 
						r.PermeabilityProtocol == protocol.DeclTypeName &&
						(!r.RootOnly || isRoot)); // &&			// root protocol or we don't care if it's not the root.
						// r.Receptor.Instance.GetEnabledReceiveProtocols().Select(rp => rp.Protocol).Contains(protocol.DeclTypeName));
				}

				if (!ret)
				{
					// check protocol map for receivers that are not the issuing receptor, ignoring ourselves.
					ret = protocolReceptorMap.Any(kvp => (kvp.Key == protocol.DeclTypeName) && 
						kvp.Value.Any(r => (r.Receptor != from) &&
							r.PermeabilityProtocol == protocol.DeclTypeName &&
							(!r.RootOnly || isRoot) &&			// root protocol or we don't care if it's not the root.
							(r.Receptor.Instance.Enabled))); // .ContainsKey(protocol.DeclTypeName);
				}
			}

			return ret;
		}
Ejemplo n.º 39
0
		/// <summary>
		/// Remove the receptor without generating remove events or terminating the receptor.
		/// </summary>
		protected void InternalRemove(IReceptor receptor)
		{
			receptors.Remove(receptor as Receptor);
			registeredReceptorMap.Remove(receptor);

			protocolReceptorMap.ForEach(kvp =>
				{
					IReceptorConnection conn = kvp.Value.SingleOrDefault(rc => rc.Receptor == receptor);
					conn.IfNotNull(c=>kvp.Value.Remove(c));
				});
		}
Ejemplo n.º 40
0
		/// <summary>
		/// Add the receptor, without generating add events.
		/// </summary>
		protected void InternalAdd(IReceptor receptor)
		{
			// TODO: If receptors was List<IReceptor>, we wouldn't need this cast.
			receptors.Add(receptor as Receptor);
			registeredReceptorMap[receptor] = true;
			// The receptor instance is now using this receptor system!
			receptor.Instance.ReceptorSystem = this;
			// Process any queued carriers that may now become active.
			ReloadProtocolReceptorMap();
			ProcessQueuedCarriers(true);
		}
Ejemplo n.º 41
0
		public void MoveReceptorTo(IReceptor receptor, ReceptorsContainer target)
		{
			InternalRemove(receptor);
			target.InternalAdd(receptor);
		}
Ejemplo n.º 42
0
		/// <summary>
		/// Moves the receptor in this membrane to the specified target membrane.
		/// </summary>
		public void MoveReceptorToMembrane(IReceptor receptor, IMembrane targetMembrane)
		{
			receptorSystem.MoveReceptorTo(receptor, ((Membrane)targetMembrane).receptorSystem);
			UpdatePermeability();
			((Membrane)targetMembrane).UpdatePermeability();
		}
Ejemplo n.º 43
0
		public void Remove(IReceptor receptor)
		{
			receptorSystem.Remove(receptor);
		}
Ejemplo n.º 44
0
		public ReceptorConnection(IReceptor receptor)
		{
			Receptor = receptor;
		}
Ejemplo n.º 45
0
		public ReceptorConnection(IReceptor receptor, bool rootOnly, string permeabilityProtocol)
		{
			Receptor = receptor;
			RootOnly = rootOnly;
			PermeabilityProtocol = permeabilityProtocol;
		}