public void CanHandleVoiceMessages()
        {
            var paramses = new HandlerParams(null, new Update
            {
                Message = new Message
                {
                    Voice = new Voice
                    {
                    }
                }
            }, null, "testbot");
            var attribute = new MessageAttribute(Enums.MessageFlag.HasVoice);

            Assert.True(attribute.CanHandleInternal(paramses));

            paramses = new HandlerParams(null, new Update()
            {
                Message = new Message()
                {
                    Animation = new Animation()
                }
            }, null, "testbot");

            Assert.False(attribute.CanHandleInternal(paramses));
        }
Ejemplo n.º 2
0
        public void Awake()
        {
            Type[] types = ETModel.Game.Hotfix.GetHotfixTypes();
            foreach (Type type in types)
            {
                object[] attrs = type.GetCustomAttributes(typeof(MessageAttribute), false);
                if (attrs.Length == 0)
                {
                    continue;
                }

                MessageAttribute messageAttribute = attrs[0] as MessageAttribute;
                if (messageAttribute == null)
                {
                    continue;
                }
                this.opcodeTypes.Add(messageAttribute.Opcode, type);
            }

            foreach (Type type in types)
            {
                object[] attrs = type.GetCustomAttributes(typeof(ProtoContractAttribute), false);
                if (attrs.Length == 0)
                {
                    continue;
                }

                PType.RegisterType(type.FullName, type);
            }
        }
Ejemplo n.º 3
0
        public void MessageDescriptor_can_be_created_from_MessageAttribute(MessageAttribute attribute)
        {
            var messageDescriptor = new MessageDescriptor(attribute);

            Assert.That(messageDescriptor.Name, Is.EqualTo(attribute.Name));
            Assert.That(messageDescriptor.Namespace, Is.EqualTo(attribute.Namespace));
        }
Ejemplo n.º 4
0
 public AnalyzedPacket(int len, byte[] msg, long time, MessageAttribute mark)
 {
     Length    = len;
     Message   = msg;
     Timestamp = time;
     RouteMark = mark;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates an AttributeSet instance for AttributeSet nodes specified in recipe with inner count as 1.
        /// </summary>
        /// <param name="attributeSetNode">The AttributeSet node specified in recipe with inner count as 1.</param>
        /// <param name="xpathNodeVal">The base xpath applied to all child attributes.</param>
        /// <param name="message">The message from which to extract information.</param>
        /// <returns>An AttributeSet instance for the AttributeSet node in recipe</returns>
        /// <exception cref="MessageParsingException">
        /// If XPath attribute of the Attribute node is not found.
        /// If Attribute node is mandatory and no corresponding node is found in message.
        /// If Type of Attribute node is not found or is empty.
        /// </exception>
        /// <exception cref="MessageValidationException">
        /// If MessageAttribute constructor throws exception.
        /// </exception>
        private static AttributeSet CreateAttributeSet(XmlNode attributeSetNode, string xpathNodeVal,
                                                       XmlDocument message)
        {
            //Get all child attribute nodes
            XmlNodeList attributeNodes = attributeSetNode.ChildNodes;

            IList <MessageAttribute> attributes = new List <MessageAttribute>();

            //Create the attributes for the attributeSet
            for (int i = 0; i < attributeNodes.Count; i++)
            {
                //Create MessageAttribute instance
                MessageAttribute createdAttribute = GetMessageAttribute(attributeNodes[i], message, xpathNodeVal);

                //Ignore attributes that were not mandatory and were not found
                if (createdAttribute != null)
                {
                    attributes.Add(createdAttribute);
                }
            }

            //Convert attributes list to array
            MessageAttribute[] attributesArr = new MessageAttribute[attributes.Count];
            attributes.CopyTo(attributesArr, 0);

            return(new AttributeSet(attributesArr));
        }
Ejemplo n.º 6
0
 public static string GetMessageKey(this MessageAttribute message, object value)
 => message?
 .Id?
 .ToString()?
 .Split('.')
 .Aggregate(value, (from, name) => Versioned.CallByName(from, name, CallType.Get))?
 .ToString();
        public override async Task <int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
                                                          CancellationToken cancellationToken = new CancellationToken())
        {
            var domainEntities = this.ChangeTracker
                                 .Entries <Entity>()
                                 .Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()).ToList();

            var domainEvents = domainEntities
                               .SelectMany(x => x.Entity.DomainEvents)
                               .ToList();

            domainEntities.ForEach(entity => entity.Entity.ClearDomainEvents());
            foreach (var domainEvent in domainEvents)
            {
                var message = MessageAttribute.Get(domainEvent.GetType());
                if (message == null)
                {
                    continue;
                }

                var eventBody = JsonConvert.SerializeObject(domainEvent, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                });
                Console.WriteLine($"\n------\nA domain event has been published!\n" +
                                  $"Event: {domainEvent.GetType().Name}\n" +
                                  $"TopicName: {message.Name}\n" +
                                  $"EventBody: {eventBody}\n");

                await Events.AddAsync(new Event(domainEvent.GetType().Name, eventBody, message.Name), cancellationToken);
            }

            return(await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken));
        }
        public void CanHandleMultiContent()
        {
            var paramses = new HandlerParams(null, new Update
            {
                Message = new Message
                {
                    Voice = new Voice
                    {
                    },
                    Game = new Game
                    {
                    }
                }
            }, null, "testbot");
            var attribute = new MessageAttribute(Enums.MessageFlag.HasVoice);

            Assert.True(attribute.CanHandleInternal(paramses));

            paramses = new HandlerParams(null, new Update()
            {
                Poll = new Poll
                {
                }
            }, null, "testbot");

            Assert.False(attribute.CanHandleInternal(paramses));
        }
Ejemplo n.º 9
0
        public void MessageDescriptor_can_be_created_from_MessageAttribute_with_no_namespace(string name)
        {
            var attribute         = new MessageAttribute(name);
            var messageDescriptor = new MessageDescriptor(attribute);

            Assert.That(messageDescriptor.Name, Is.EqualTo(attribute.Name));
            Assert.That(messageDescriptor.Namespace, Is.EqualTo(MessageDescriptor.NamespaceFallback));
        }
Ejemplo n.º 10
0
 public StoreRecord(string key, object[] items, long storeVersion, long streamVersion, MessageAttribute[] attributes)
 {
     Items = items;
     StoreVersion = storeVersion;
     StreamVersion = streamVersion;
     Key = key;
     Attributes = attributes;
 }
Ejemplo n.º 11
0
        public void MessageAttributeConstructorTest()
        {
            string           name   = string.Empty; // TODO: Initialize to an appropriate value
            byte             number = 0;            // TODO: Initialize to an appropriate value
            MessageAttribute target = new MessageAttribute(name, number);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Ejemplo n.º 12
0
 public new static MappedAddressAttribute FromGenericAttribute(MessageAttribute attr)
 {
     return(new MappedAddressAttribute
     {
         Type = attr.Type,
         AttributeLength = attr.AttributeLength,
         Value = attr.Value
     });
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Creates a variable number of AttributeSet instances for an AttributeSet node with inner count as *.
        /// </summary>
        /// <param name="attributeSetNode">The AttributeSet node specified in recipe with inner count as 1.</param>
        /// <param name="basePath">The base xpath applied to all child attributes.</param>
        /// <param name="message">The message from which to extract information.</param>
        /// <returns>A list of AttributeSet instances for the AttributeSet node in recipe</returns>
        /// <exception cref="MessageParsingException">
        /// If XPath attribute of Attribute node is missing.
        /// </exception>
        /// <exception cref="MessageValidationException">
        /// If MessageAttribute class throws exception at constructor.
        /// </exception>
        private static IList <AttributeSet> CreateAttributeSets(XmlNode attributeSetNode,
                                                                string basePath, XmlDocument message)
        {
            //Select all child Attribute nodes
            XmlNodeList attributeNodes = attributeSetNode.ChildNodes;

            //Get all the queries to be run. Also get the names of the MessageAttributes to create
            IList <string> xPathQueries = new List <string>();
            IList <string> names        = new List <string>();

            foreach (XmlNode attrNode in attributeNodes)
            {
                xPathQueries.Add(basePath + GetXmlAttributeValue(attrNode, "XPath", true, false));
                names.Add(GetXmlAttributeValue(attrNode, "Name", false, false));
            }

            //Get the query results
            IList <XmlNodeList> xPathResults = new List <XmlNodeList>();

            foreach (string query in xPathQueries)
            {
                xPathResults.Add(message.SelectNodes(query));
            }

            //Get least number of AttributeSets required
            int count = int.MaxValue;

            foreach (XmlNodeList nodeList in xPathResults)
            {
                count = Math.Min(nodeList.Count, count);
            }

            //Create the required number of AttributeSets
            IList <AttributeSet> ret = new List <AttributeSet>();

            for (int i = 0; i < count; i++)
            {
                MessageAttribute[] attributes = new MessageAttribute[attributeNodes.Count];
                for (int j = 0; j < attributeNodes.Count; j++)
                {
                    //Exceptions thrown by DataEntities must be caught and rethrown as MessageValidationException
                    try
                    {
                        attributes[j] = new MessageAttribute(names[j], xPathResults[i][j].InnerText, names[j]);
                    }
                    catch (Exception e)
                    {
                        throw new MessageValidationException("Invalid parameters for MessageAttribute constructor.", e);
                    }
                }

                ret.Add(new AttributeSet(attributes));
            }

            return(ret);
        }
Ejemplo n.º 14
0
        public void NumberTest()
        {
            string           name     = string.Empty;                       // TODO: Initialize to an appropriate value
            byte             number   = 0;                                  // TODO: Initialize to an appropriate value
            MessageAttribute target   = new MessageAttribute(name, number); // TODO: Initialize to an appropriate value
            byte             expected = 0;                                  // TODO: Initialize to an appropriate value
            byte             actual;

            target.Number = expected;
            actual        = target.Number;
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Ejemplo n.º 15
0
 private void ValidateAttribute(MessageAttribute messageAttribute, string[] route)
 {
     if (messageAttribute == null)
     {
         throw new Exception("MessageAttribute is missing!");
     }
     if (messageAttribute.IsBroadcast)
     {
         var broadcaseAttr = (BroadcastMessageAttribute)messageAttribute;
         if (broadcaseAttr.Target == BroadcastTarget.Application && !(route == null || route.Length == 0))
         {
             throw new Exception($"Usage of 'Route' and 'BroadcastTarget.Application' will introduce not logical result!");
         }
     }
 }
Ejemplo n.º 16
0
        public void Publish(IMessage message, string route)
        {
            MessageAttribute messageAttribute = GetMessageAttribute(message.GetType());

            ValidateAttribute(messageAttribute, route);


            if (messageAttribute.IsBroadcast)
            {
                broadcastMessageProcessor.Publish(_channel, message.GetType().FullName, messageAttribute.Durable, message, route);
            }
            else
            {
                directMessageProcessor.Publish(_channel, message.GetType().FullName, messageAttribute.Durable, message);
            }
        }
Ejemplo n.º 17
0
        public void ListenMessage <T>(Action <T> callback, string[] routes) where T : IMessage
        {
            MessageAttribute messageAttribute = GetMessageAttribute(typeof(T));

            ValidateAttribute(messageAttribute, routes);

            if (messageAttribute.IsBroadcast)
            {
                var broadcastAttribute = (BroadcastMessageAttribute)messageAttribute;
                broadcastMessageProcessor.ListenRabbitMessage(_channel, typeof(T).FullName, messageAttribute.Durable, callback, routes, broadcastAttribute.Target);
            }
            else
            {
                directMessageProcessor.ListenRabbitMessage(_channel, typeof(T).FullName, messageAttribute.Durable, callback);
            }
        }
        /// <summary>
        /// добавляет пользовательский атрибут с ссответствующим типом
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public SendMessageBatchRequestEntry SetMessageAttribute(string attributeName, byte[] value)
        {
            var attr = new MessageAttributeValue()
            {
                DataType = AttributeValueType.Binary, BinaryValue = value
            };

            if (MessageAttribute.ContainsKey(attributeName))
            {
                MessageAttribute[attributeName] = attr;
            }
            else
            {
                MessageAttribute.Add(attributeName, attr);
            }
            return(this);
        }
Ejemplo n.º 19
0
    static void Main()
    {
        Assembly assembly = Assembly.GetExecutingAssembly();

        Type[] types = assembly.GetTypes();

        foreach (Type type in types)
        {
            //MessageAttribute attr = (MessageAttribute)type.GetCustomAttribute(typeof(MessageAttribute));
            MessageAttribute attr = type.GetCustomAttribute <MessageAttribute>();

            if (attr != null)
            {
                Console.WriteLine("Classe " + type.FullName + ": " + attr.Value);
            }
        }
    }
        /// <summary>
        /// добавляет пользовательский атрибут с ссответствующим типом
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public SendMessageBatchRequestEntry SetMessageAttribute(string attributeName, int value)
        {
            var attr = new MessageAttributeValue()
            {
                DataType = AttributeValueType.Number, StringValue = value.ToString()
            };

            if (MessageAttribute.ContainsKey(attributeName))
            {
                MessageAttribute[attributeName] = attr;
            }
            else
            {
                MessageAttribute.Add(attributeName, attr);
            }
            return(this);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// добавляет пользовательский атрибут с ссответствующим типом
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public SendMessageRequest SetMessageAttribute(string attributeName, string value)
        {
            var attr = new MessageAttributeValue()
            {
                DataType = AttributeValueType.String, StringValue = value
            };

            if (MessageAttribute.ContainsKey(attributeName))
            {
                MessageAttribute[attributeName] = attr;
            }
            else
            {
                MessageAttribute.Add(attributeName, attr);
            }
            return(this);
        }
Ejemplo n.º 22
0
        private static void ValidateMessageAttributesOfComponent(MonoBehaviour behaviour)
        {
            var type = behaviour.GetType();
            MessageAttribute invalidAttribute;
            var message = string.Empty;
            var fields  = ReflectionUtils.GetCachedFields(type);

            foreach (var field in fields)
            {
                if (MessageAttribute.TryFindInvalidAttribute(behaviour, field, out invalidAttribute))
                {
                    message = string.Format("The attribute 'MessageAttribute' of the field {0} of the component {1} has the error -> '{2}'", field, type.Name, invalidAttribute.Message);
                    Debug.LogError(message, behaviour);
                    error_count++;
                }
            }
        }
Ejemplo n.º 23
0
        private Message GenerateMessageFromAttribute(MessageAttribute messageAttribute, ISchemaRepository schemaRepository)
        {
            if (messageAttribute?.PayloadType == null)
            {
                return(null);
            }

            var message = new Message
            {
                Payload     = _schemaGenerator.GenerateSchema(messageAttribute.PayloadType, schemaRepository),
                Name        = messageAttribute.Name ?? _options.SchemaIdSelector(messageAttribute.PayloadType),
                Title       = messageAttribute.Title,
                Summary     = messageAttribute.Summary,
                Description = messageAttribute.Description,
            };

            return(message);
        }
Ejemplo n.º 24
0
        public ServerProxy(Type proxy, IServiceManager serviceManager)
            : base(proxy)
        {
            ServiceAttribute sattr = proxy.GetCustomAttribute <ServiceAttribute>();

            if (sattr != null)
            {
                serviceType = sattr.ServiceType;
            }

            MessageAttribute mttr = proxy.GetCustomAttribute <MessageAttribute>();

            if (mttr != null)
            {
                messageType = mttr.MessageType;
            }

            this.serviceManager = serviceManager;
        }
Ejemplo n.º 25
0
        private static IMessage GenerateMessageFromAttribute(MessageAttribute messageAttribute, AsyncApiSchemaResolver schemaResolver, JsonSchemaGenerator jsonSchemaGenerator)
        {
            if (messageAttribute?.PayloadType == null)
            {
                return(null);
            }

            var message = new Message
            {
                Payload     = jsonSchemaGenerator.Generate(messageAttribute.PayloadType, schemaResolver),
                Title       = messageAttribute.Title,
                Summary     = messageAttribute.Summary,
                Description = messageAttribute.Description,
                Bindings    = messageAttribute.BindingsRef != null ? new MessageBindingsReference(messageAttribute.BindingsRef) : null,
            };

            message.Name = messageAttribute.Name ?? message.Payload.ActualSchema.Id;

            return(schemaResolver.GetMessageOrReference(message));
        }
        public void CanHandleLeftChatMember()
        {
            var handles = new HandlerParams(null, new Update()
            {
                Message = new Message()
                {
                    LeftChatMember =
                        new User()
                    {
                        Id        = 12345,
                        FirstName = "Fulan",
                        Username  = "******",
                        LastName  = "Bin Fulan"
                    }
                }
            }, null, "testbot");

            var attribute = new MessageAttribute(MessageFlag.HasLeftChatMember);

            Assert.True(attribute.CanHandleInternal(handles));
        }
Ejemplo n.º 27
0
        public MessageAttribute[] ReadAttributes(Stream stream)
        {
            using (var reader = new BitReader(stream))
            {
                var attributeCount = reader.Read7BitInt();
                if (attributeCount == 0)
                {
                    return(Empty);
                }

                var attributes = new MessageAttribute[attributeCount];

                for (var i = 0; i < attributeCount; i++)
                {
                    var key   = reader.ReadString();
                    var value = reader.ReadString();
                    attributes[i] = new MessageAttribute(key, value);
                }
                return(attributes);
            }
        }
        public void CanHandleCaptionMessages()
        {
            var paramses = new HandlerParams(null, new Update()
            {
                Message = new Message()
                {
                    Caption = "Blah",
                    Voice   = new Voice
                    {
                    }
                }
            }, null, "testbot");
            var attribute = new MessageAttribute(Enums.MessageFlag.HasCaption);

            Assert.True(attribute.CanHandleInternal(paramses));

            attribute = new MessageAttribute("Foo");
            Assert.False(attribute.CanHandleInternal(paramses));

            attribute = new MessageAttribute("/test");
            Assert.False(attribute.CanHandleInternal(paramses));
        }
Ejemplo n.º 29
0
        public void Load()
        {
            this.opcodeTypes.Clear();
            this.typeMessages.Clear();

            List <Type> types = Game.EventSystem.GetTypes();

            foreach (Type type in types)
            {
                object[] attrs = type.GetCustomAttributes(typeof(MessageAttribute), false);
                if (attrs.Length == 0)
                {
                    continue;
                }

                MessageAttribute messageAttribute = attrs[0] as MessageAttribute;
                if (messageAttribute == null)
                {
                    continue;
                }
                this.opcodeTypes.Add(messageAttribute.Opcode, type);
                this.typeMessages.Add(messageAttribute.Opcode, Activator.CreateInstance(type));
            }
        }
        GUIContent GetContent()
        {
            MessageAttribute target = attribute as MessageAttribute;

            return(new GUIContent(target.Message, ConvertTypeToIcon(target.IconType)));
        }
Ejemplo n.º 31
0
 public MessageResolverResultSet(MessageId id, Type type, MessageAttribute messageAttribute)
 {
     Id               = id;
     Type             = type;
     MessageAttribute = messageAttribute;
 }
        public MessageAttribute[] ReadAttributes(Stream stream)
        {
            using (var reader = new BitReader(stream))
            {
                var attributeCount = reader.Read7BitInt();
                if (attributeCount == 0) return Empty;

                var attributes = new MessageAttribute[attributeCount];

                for (var i = 0; i < attributeCount; i++)
                {
                    var key = reader.ReadString();
                    var value = reader.ReadString();
                    attributes[i] = new MessageAttribute(key, value);
                }
                return attributes;
            }
        }