Esempio n. 1
0
 /// <summary>
 /// Converts parameter object from Amqp request to a particular type to be used as input parameter to RPC method being invoked
 /// </summary>
 /// <param name="deserializationType">Type into which object parameters must be converted</param>
 /// <param name="parameters">Input received at AmqpRequest.body.params</param>
 /// <returns>Deserialized object which will be used as an input to Rpc Method</returns>
 public dynamic PeeloutAmqpWrapper(Type deserializationType, object parameters)
 {
     try
     {
         if (deserializationType == null)
         {
             return(null);
         }
         //Create Amqp serializer instance
         AmqpSerializer _serializer = new AmqpSerializer();
         //Create dynamic buffer
         ByteBuffer _paramsBuffer = new ByteBuffer(1024, true);
         //Write object to buffer
         _serializer.WriteObject(_paramsBuffer, parameters);
         //Get ReadObject methodinfo using reflection
         var _readObjectMethodInfo = typeof(AmqpSerializer).GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                     .Where(x => x.Name.Equals("ReadObject") && x.IsGenericMethod && x.GetGenericArguments().Length.Equals(1))
                                     .FirstOrDefault();
         if (_readObjectMethodInfo == null)
         {
             throw new MissingMethodException("ReadObject from AmqpSerializer");
         }
         //Mark methodinfo as generic
         var _readObjectGenericMethodInfo = _readObjectMethodInfo.MakeGenericMethod(deserializationType);
         //Invoke ReadObject to deserialize object
         return(_readObjectGenericMethodInfo.Invoke(_serializer, new[] { _paramsBuffer }));
     }
     catch (Exception ex)
     {
         Log.Error(ex, "Exception while deserializing request parameters", parameters);
     }
     return(null);
 }
Esempio n. 2
0
        public void AmqpSerializerCircularArraySelfRefTest()
        {
            GroupArray group = new GroupArray()
            {
                Name = "test-group"
            };

            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, group);
            var n = AmqpSerializer.Deserialize <GroupArray>(b);

            Assert.AreEqual(n.Name, group.Name);

            b.Reset();
            group.SubGroups = new GroupArray[] { new GroupArray()
                                                 {
                                                     Name = "sub-1"
                                                 } };
            AmqpSerializer.Serialize(b, group);
            n = AmqpSerializer.Deserialize <GroupArray>(b);
            Assert.AreEqual(n.Name, group.Name);
            Assert.AreEqual(1, group.SubGroups.Length);
            Assert.AreEqual(group.SubGroups[0].Name, n.SubGroups[0].Name);
        }
        public void AmqpCodecDescribedValueTest()
        {
            byte[] workBuffer = new byte[2048];

            Action <object, object, byte[]> runTest = (d, v, b) =>
            {
                var        dv = new DescribedValue(d, v);
                ByteBuffer buffer;
                AmqpSerializer.Serialize(buffer = new ByteBuffer(workBuffer, 0, 0, workBuffer.Length), dv);
                var dv2 = AmqpSerializer.Deserialize <DescribedValue>(buffer);

                Assert.AreEqual(dv.Descriptor, dv2.Descriptor);
                if (dv.Value == null)
                {
                    Assert.IsTrue(dv2.Value == null);
                }
                else if (dv.Value.GetType() == typeof(List))
                {
                    EnsureEqual((IList)dv.Value, (IList)dv2.Value);
                }
                else
                {
                    Assert.AreEqual(dv.Value, dv2.Value);
                }
            };

            runTest(0, "uri", workBuffer);
            runTest(long.MaxValue, (Symbol)"abcd", workBuffer);
            runTest("descriptor", new List()
            {
                0, "x"
            }, workBuffer);
            runTest((Symbol)"null", null, workBuffer);
        }
Esempio n. 4
0
        static T GetValue <T>(this AmqpValue value)
        {
            ByteBuffer buffer = value.ValueBuffer;

            if (buffer == null)
            {
                return((T)value.Value);
            }

            buffer.Seek(0);
            if (typeof(T) == typeof(ByteBuffer))
            {
                int offset  = GetBinaryOffset(buffer);
                int len     = buffer.Length - offset;
                var payload = new ByteBuffer(buffer.Buffer, buffer.Offset + offset, len, len);
                return((T)(object)payload);
            }
            else if (typeof(T) == typeof(byte[]))
            {
                int    offset  = GetBinaryOffset(buffer);
                int    len     = buffer.Length - offset;
                byte[] payload = new byte[len];
                Buffer.BlockCopy(buffer.Buffer, buffer.Offset + offset, payload, 0, payload.Length);
                return((T)(object)payload);
            }
            else
            {
                return(AmqpSerializer.Deserialize <T>(buffer));
            }
        }
Esempio n. 5
0
        public void AmqpSerializerCircularListSelfRefTest()
        {
            GroupList group = new GroupList()
            {
                Name = "test-group"
            };

            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, group);
            var n = AmqpSerializer.Deserialize <GroupList>(b);

            Assert.AreEqual(n.Name, group.Name);

            b.Reset();
            group.SubGroups = new List <GroupList>()
            {
                new GroupList()
                {
                    Name = "sub-1"
                }
            };
            AmqpSerializer.Serialize(b, group);
            n = AmqpSerializer.Deserialize <GroupList>(b);
            Assert.AreEqual(n.Name, group.Name);
            Assert.AreEqual(1, group.SubGroups.Count);
            Assert.AreEqual(group.SubGroups[0].Name, n.SubGroups[0].Name);
        }
        static void RunPrimitiveTypeTest <T>(T value)
        {
            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, value);
            T o = AmqpSerializer.Deserialize <T>(b);

            if (typeof(T) == typeof(DateTime))
            {
                DateTime now = DateTime.UtcNow;
                long     x   = Convert.ToInt64((now - (DateTime)(object)value).TotalMilliseconds);
                long     y   = Convert.ToInt64((now - (DateTime)(object)o).TotalMilliseconds);
                Assert.IsTrue(Math.Abs(x - y) < 2, "timestamp difference should be less than 2");
            }
            else if (typeof(T) == typeof(byte[]))
            {
                byte[] b1 = (byte[])(object)value;
                byte[] b2 = (byte[])(object)o;
                Assert.AreEqual(b1.Length, b2.Length, "Count is not equal.");
                for (int i = 0; i < b1.Length; ++i)
                {
                    Assert.AreEqual(b1[i], b2[i], string.Format("The {0}th byte is not equal ({1} != {2}).", i, b1[i], b2[i]));
                }
            }
            else
            {
                Assert.AreEqual(value, o, "value not equal after deserialize");
            }
        }
Esempio n. 7
0
        public static void Send()
        {
            Address    address    = new Address("amqp://*****:*****@localhost:5672");
            Connection connection = new Connection(address);
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "sender-link", "immobile");

            var serializer = new AmqpSerializer(new ContractResolver()
            {
                PrefixList = new[] { "Sender" }
            });

            try
            {
                for (int i = 0; i < 1000; i++)
                {
                    var cliente = new Cliente()
                    {
                        Crm = i.ToString(), Nome = "Fulano", Status = false
                    };
                    SendMessage(sender, "Cliente", cliente, serializer);
                    Console.WriteLine("Enviado o cliente: \n{0}", cliente.ToString());
                }
            }
            finally
            {
                sender.Close();
                session.Close();
                connection.Close();
            }
        }
Esempio n. 8
0
        public void AmqpSerializerCircularMapSelfRefTest()
        {
            GroupMap group = new GroupMap()
            {
                Name = "test-group"
            };

            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, group);
            var n = AmqpSerializer.Deserialize <GroupMap>(b);

            Assert.AreEqual(n.Name, group.Name);

            b.Reset();
            group.SubGroups = new Dictionary <int, GroupMap>()
            {
                { 10, new GroupMap()
                  {
                      Name = "sub-1"
                  } }
            };
            AmqpSerializer.Serialize(b, group);
            n = AmqpSerializer.Deserialize <GroupMap>(b);
            Assert.AreEqual(n.Name, group.Name);
            Assert.AreEqual(1, group.SubGroups.Count);
            Assert.AreEqual(group.SubGroups[10].Name, n.SubGroups[10].Name);
        }
Esempio n. 9
0
        public void AmqpSerializerCircularSelfRefTest()
        {
            TestNode node = new TestNode()
            {
                Id = 1
            };

            node.Next = new TestNode()
            {
                Id = 2
            };
            node.Previous = new TestNode()
            {
                Id = 0
            };

            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, node);
            var n = AmqpSerializer.Deserialize <TestNode>(b);

            Assert.AreEqual(n.Id, node.Id);
            Assert.AreEqual(n.Next.Id, node.Next.Id);
            Assert.AreEqual(n.Previous.Id, node.Previous.Id);
        }
Esempio n. 10
0
        public Recebimento(Session session, string name, string address, Cliente cliente)
        {
            this.session = session;
            this.name    = name;
            this.address = address;
            this.cliente = cliente;

            this.serializer = new AmqpSerializer(new ContractResolver()
            {
                PrefixList = new[] { "Mensageria.Domain.Entities" }
            });
        }
Esempio n. 11
0
 public static SerializableType CreateDescribedListType(
     AmqpSerializer serializer,
     Type type,
     SerializableType baseType,
     string descriptorName,
     ulong? descriptorCode,
     SerialiableMember[] members,
     Dictionary<Type, SerializableType> knownTypes,
     MethodAccessor[] serializationCallbacks)
 {
     return new DescribedListType(serializer, type, baseType, descriptorName,
         descriptorCode, members, knownTypes, serializationCallbacks);
 }
Esempio n. 12
0
        static void NegativeTest(object value, string error)
        {
            var buffer = new ByteBuffer(1024, true);

            try
            {
                AmqpSerializer.Serialize(buffer, value);
                Assert.IsTrue(false, "SerializationException not thrown");
            }
            catch (SerializationException e)
            {
                Assert.IsTrue(e.Message.Contains(error));
            }
        }
        public void AmqpCodecList0Test()
        {
            byte[]     list0Bin   = new byte[] { 0x45 };
            byte[]     workBuffer = new byte[128];
            ByteBuffer buffer     = new ByteBuffer(workBuffer, 0, 0, workBuffer.Length);

            List list0 = new List();

            AmqpSerializer.Serialize(buffer, list0);
            EnsureEqual(list0Bin, 0, list0Bin.Length, buffer.Buffer, buffer.Offset, buffer.Length);

            IList list0v = AmqpSerializer.Deserialize <List>(buffer);

            Assert.IsTrue(list0v.Count == 0, "The list should contain 0 items.");
        }
        static void RunArrayTest <T>(byte[] workBuffer, Func <int, T> generator, int count)
        {
            ByteBuffer buffer = new ByteBuffer(workBuffer, 0, 0, workBuffer.Length);

            T[] array = new T[count];
            for (int i = 0; i < count; i++)
            {
                array[i] = generator(i);
            }
            AmqpSerializer.Serialize(buffer, array);

            var array2 = AmqpSerializer.Deserialize <T[]>(buffer);

            Assert.AreEqual(array.Length, array2.Length);
        }
        static void NegativeTest(object value, string error)
        {
            var buffer = new ByteBuffer(1024, true);

            try
            {
                AmqpSerializer.Serialize(buffer, value);
                Assert.IsTrue(false, "SerializationException not thrown");
            }
            catch (SerializationException e)
            {
                System.Diagnostics.Trace.WriteLine("Caught exception " + e.Message);
                Assert.IsTrue(e.Message.Contains(error));
            }
        }
Esempio n. 16
0
        public void AmqpSerializerMapEncodingTest()
        {
            var product = new Product()
            {
                Name = "Computer", Price = 499.98, Weight = 30
            };
            var buffer = new ByteBuffer(1024, true);

            AmqpSerializer.Serialize(buffer, product);

            var product2 = AmqpSerializer.Deserialize <Product>(buffer);

            Assert.AreEqual(product.Name, product2.Name);
            Assert.AreEqual(product.Price, product2.Price);
            Assert.AreEqual(product.Weight, product2.Weight);
        }
Esempio n. 17
0
        private void SendMessage(SenderLink sender, string subject, object value, AmqpSerializer serializer)
        {
            this.message = new Message()
            {
                BodySection = new AmqpValue <object>(value, serializer)
            };

            this.message.ApplicationProperties = new ApplicationProperties();
            this.message.ApplicationProperties["Message.Type.FullName"] = typeof(Cliente).FullName;
            this.message.Properties = new Properties()
            {
                MessageId = Guid.NewGuid().ToString()
            };
            this.message.Properties = new Properties()
            {
                Subject = subject
            };

            sender.Send(this.message);
        }
Esempio n. 18
0
        public void AmqpSerializerCircularMultipleTest()
        {
            Type1 t1 = new Type1()
            {
                Id = 1
            };

            t1.Next = new Type2()
            {
                Name = "2", Next = new Type3()
            };

            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, t1);
            var t = AmqpSerializer.Deserialize <Type1>(b);

            Assert.AreEqual(t1.Id, t.Id);
            Assert.AreEqual(t1.Next.Name, t.Next.Name);
        }
Esempio n. 19
0
        public void AmqpSerializerCustomResolverTest()
        {
            var serializer = new AmqpSerializer(new PocoContractResolver()
            {
                PrefixList = new[] { "Serialization.Poco" }
            });

            Circle circle = new Circle()
            {
                Id = Guid.NewGuid(), Radius = 3.5
            };
            ByteBuffer buffer = new ByteBuffer(1024, true);

            serializer.WriteObject(buffer, circle);

            Shape shape = serializer.ReadObject <Shape>(buffer);

            Assert.AreEqual(typeof(Circle), shape.GetType());
            Assert.AreEqual(circle.Id, ((Circle)shape).Id);
            Assert.AreEqual(circle.Radius, ((Circle)shape).Radius);
        }
        static void RunSingleValueTest <T>(byte[] workBuffer, T value, byte[] result, string message)
        {
            ByteBuffer buffer;

            AmqpSerializer.Serialize(buffer = new ByteBuffer(workBuffer, 0, 0, workBuffer.Length), value);
            EnsureEqual(result, 0, result.Length, buffer.Buffer, buffer.Offset, buffer.Length);
            T decodeValue = AmqpSerializer.Deserialize <T>(new ByteBuffer(result, 0, result.Length, result.Length));

            if (typeof(T) == typeof(byte[]))
            {
                byte[] b1 = (byte[])(object)value;
                byte[] b2 = (byte[])(object)decodeValue;
                EnsureEqual(b1, 0, b1.Length, b2, 0, b2.Length);
            }
            else
            {
                Assert.IsTrue(value.Equals(decodeValue), message);
            }

            System.Diagnostics.Trace.WriteLine(typeof(T).Name + " test passed");
        }
        public void AmqpCodecSingleValueTest()
        {
            byte[] workBuffer = new byte[2048];

            RunSingleValueTest(workBuffer, boolTrue, boolTrueBin, "Boolean value is not true.");
            RunSingleValueTest(workBuffer, boolFalse, boolFalseBin, "Boolean value is not false.");
            RunSingleValueTest(workBuffer, ubyteValue, ubyteValueBin, "UByte value is not equal.");
            RunSingleValueTest(workBuffer, ushortValue, ushortValueBin, "UShort value is not equal.");
            RunSingleValueTest(workBuffer, uint0Value, uint0ValueBin, "UInt0 value is not equal.");
            RunSingleValueTest(workBuffer, uintSmallValue, uintSmallValueBin, "UIntSmall value is not equal.");
            RunSingleValueTest(workBuffer, uintValue, uintValueBin, "UInt value is not equal.");
            RunSingleValueTest(workBuffer, ulong0Value, ulong0ValueBin, "ULong0 value is not equal.");
            RunSingleValueTest(workBuffer, ulongSmallValue, ulongSmallValueBin, "ULongSmall value is not equal.");
            RunSingleValueTest(workBuffer, ulongValue, ulongValueBin, "ULong value is not equal.");
            RunSingleValueTest(workBuffer, byteValue, byteValueBin, "Byte value is not equal.");
            RunSingleValueTest(workBuffer, shortValue, shortValueBin, "Short value is not equal.");
            RunSingleValueTest(workBuffer, intSmallValue, intSmallValueBin, "Int small value is not equal.");
            RunSingleValueTest(workBuffer, intValue, intValueBin, "Int value is not equal.");
            RunSingleValueTest(workBuffer, longSmallValue, longSmallValueBin, "Long small value is not equal.");
            RunSingleValueTest(workBuffer, longValue, longValueBin, "Long value is not equal.");
            RunSingleValueTest(workBuffer, floatValue, floatValueBin, "Float value is not equal.");
            RunSingleValueTest(workBuffer, doubleValue, doubleValueBin, "Double value is not equal.");
            RunSingleValueTest(workBuffer, charValue, charValueBin, "Char value is not equal.");
            RunSingleValueTest(workBuffer, dtValue, dtValueBin, "Timestamp value is not equal.");
            RunSingleValueTest(workBuffer, uuidValue, uuidValueBin, "Uuid value is not equal.");
            RunSingleValueTest(workBuffer, bin8Value, bin8ValueBin, "Binary8 value is not equal.");
            RunSingleValueTest(workBuffer, bin32Value, bin32ValueBin, "Binary32 value is not equal.");
            RunSingleValueTest(workBuffer, (Symbol)strValue, sym8ValueBin, "Symbol8 string value is not equal.");
            RunSingleValueTest(workBuffer, strValue, str8Utf8ValueBin, "UTF8 string8 string value is not equal.");

            // symbol 32
            Symbol symbol32v = AmqpSerializer.Deserialize <Symbol>(new ByteBuffer(sym32ValueBin, 0, sym32ValueBin.Length, sym32ValueBin.Length));

            Assert.IsTrue((string)symbol32v == strValue, "Symbol32 string value is not equal.");

            // string 32 UTF8
            string str32Utf8 = AmqpSerializer.Deserialize <string>(new ByteBuffer(str32Utf8ValueBin, 0, str32Utf8ValueBin.Length, str32Utf8ValueBin.Length));

            Assert.IsTrue(str32Utf8 == strValue, "UTF8 string32 string value is not equal.");
        }
Esempio n. 22
0
        public void AmqpSerializerCustomTypeArrayTest()
        {
            Person[] value = new Person[]
            {
                new Student("Tom")
                {
                    Age = 13
                },
                new Teacher("Bob")
                {
                    Sallary = 1234
                },
                null,
                new Student("Al")
                {
                    Age = 12
                },
            };

            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, value);
            Person[] o = AmqpSerializer.Deserialize <Person[]>(b);
            Assert.AreEqual(value.Length, o.Length);
            for (int i = 0; i < value.Length; i++)
            {
                if (value[i] == null)
                {
                    Assert.IsTrue(o[i] == null);
                }
                else
                {
                    Assert.AreEqual(value[i].GetType(), o[i].GetType());
                    Assert.AreEqual(value[i].Name, o[i].Name);
                    Assert.AreEqual(value[i].Age + 1, o[i].Age);
                }
            }
        }
Esempio n. 23
0
        static void SendMessage(SenderLink sender, string subject, object value, AmqpSerializer serializer)
        {
            var message = new Message()
            {
                BodySection = new AmqpValue <object>(value, serializer)
            };

            // Adicionando algumas propriedades da mensagem
            message.ApplicationProperties = new ApplicationProperties();
            message.ApplicationProperties["Message.Type.FullName"] = typeof(Cliente).FullName;

            // Adicionando o MessageId
            message.Properties = new Properties()
            {
                MessageId = Guid.NewGuid().ToString()
            };
            message.Properties = new Properties()
            {
                Subject = subject
            };

            sender.Send(message);
        }
Esempio n. 24
0
        public void AmqpSerializerMessageCustomResolverTest()
        {
            var serializer = new AmqpSerializer(new PocoContractResolver()
            {
                PrefixList = new[] { "Serialization.Poco" }
            });

            Rectangle rect = new Rectangle()
            {
                Id = Guid.NewGuid(), Width = 8, Height = 6
            };
            Message message = new Message()
            {
                BodySection = new AmqpValue <Shape>(rect, serializer)
            };
            ByteBuffer buffer = message.Encode();

            Shape shape = message.GetBody <Shape>(serializer);

            Assert.AreEqual(typeof(Rectangle), shape.GetType());
            Assert.AreEqual(rect.Id, ((Rectangle)shape).Id);
            Assert.AreEqual(rect.Width, ((Rectangle)shape).Width);
            Assert.AreEqual(rect.Height, ((Rectangle)shape).Height);
        }
Esempio n. 25
0
        public void AmqpSerializerCircularProvidesTest()
        {
            Provides1 p1 = new Provides1()
            {
                Value = 2, Id = Guid.NewGuid()
            };
            Provides2 p2 = p1.Next = new Provides2()
            {
                Value = 8, Name = "p2"
            };

            ByteBuffer b = new ByteBuffer(512, true);

            AmqpSerializer.Serialize(b, p1);

            var serializer = new AmqpSerializer();
            var t          = serializer.ReadObject <ProvidesBase>(b);
            var p          = t as Provides1;

            Assert.IsTrue(p != null);
            Assert.AreEqual(7, p2.Value);
            Assert.AreEqual(p2.Value, p.Next.Value);
            Assert.AreEqual(p1.Value + 1, p.Value);
        }
Esempio n. 26
0
        /// <summary>
        /// Gets an object of type T from the message body using the
        /// provided serializer.
        /// </summary>
        /// <typeparam name="T">The object type.</typeparam>
        /// <param name="message">The message from which the body is deserialized.</param>
        /// <param name="serializer">The serializer to deserialize the object.</param>
        /// <returns>An object of type T.</returns>
        public static T GetBody <T>(this Message message, AmqpSerializer serializer)
        {
            if (message.BodySection != null)
            {
                if (message.BodySection.Descriptor.Code == 0x0000000000000077UL /*Codec.AmqpValue.Code*/)
                {
                    return(((AmqpValue)message.BodySection).GetValue <T>(serializer));
                }
                else if (message.BodySection.Descriptor.Code == 0x0000000000000075UL /*Codec.Data.Code*/)
                {
                    Data data = (Data)message.BodySection;
                    if (typeof(T) == typeof(byte[]))
                    {
                        return((T)(object)data.Binary);
                    }
                    else if (typeof(T) == typeof(ByteBuffer))
                    {
                        return((T)(object)data.Buffer);
                    }
                }
            }

            return((T)message.Body);
        }
Esempio n. 27
0
 public static SerializableType CreateGenericListType(
     AmqpSerializer serializer,
     Type type,
     Type itemType,
     MethodAccessor addAccessor)
 {
     return new GenericListType(serializer, type, itemType, addAccessor);
 }
Esempio n. 28
0
 public GenericListType(AmqpSerializer serializer, Type type, Type itemType, MethodAccessor addAccessor)
     : base(serializer, type)
 {
     this.itemType = serializer.GetType(itemType);
     this.addMethodAccessor = addAccessor;
 }
Esempio n. 29
0
 public static SerializableType CreateGenericMapType(
     AmqpSerializer serializer,
     Type type,
     MemberAccessor keyAccessor,
     MemberAccessor valueAccessor,
     MethodAccessor addAccessor)
 {
     return new GenericMapType(serializer, type, keyAccessor, valueAccessor, addAccessor);
 }
        public void AmqpCodecMapTest()
        {
            byte[]     workBuffer = new byte[4096];
            ByteBuffer buffer     = new ByteBuffer(workBuffer, 0, 0, workBuffer.Length);
            string     strBig     = new string('A', 512);

            Map map = new Map();

            map.Add(new Symbol("boolTrue"), boolTrue);
            map.Add(new Symbol("boolFalse"), boolFalse);
            map.Add(new Symbol("ubyte"), ubyteValue);
            map.Add(new Symbol("ushort"), ushortValue);
            map.Add(new Symbol("uint"), uintValue);
            map.Add(new Symbol("ulong"), ulongValue);
            map.Add(new Symbol("byte"), byteValue);
            map.Add(new Symbol("short"), shortValue);
            map.Add(new Symbol("int"), intValue);
            map.Add(new Symbol("long"), longValue);
            map.Add(new Symbol("null"), null);
            map.Add(new Symbol("float"), floatValue);
            map.Add(new Symbol("double"), doubleValue);
            map.Add(new Symbol("char"), charValue);
            map.Add(new Symbol("datetime"), dtValue);
            map.Add(new Symbol("uuid"), uuidValue);
            map.Add(new Symbol("binaryNull"), null);
            map.Add(new Symbol("binary8"), bin8ValueBin);
            map.Add(new Symbol("binary32"), bin32ValueBin);
            map.Add(new Symbol("symbolNull"), (Symbol)null);
            map.Add(new Symbol("symbol8"), new Symbol(strValue));
            map.Add(new Symbol("symbol32"), new Symbol(strBig));
            map.Add(new Symbol("string8"), strValue);
            map.Add(new Symbol("string32"), strBig);
            map.Add(new Symbol("described1"), described1);

            AmqpSerializer.Serialize(buffer, map);

            // make sure the size written is correct (it has to be Map32)
            // the first byte is FormatCode.Map32
            int mapSize = (workBuffer[1] << 24) | (workBuffer[2] << 16) | (workBuffer[3] << 8) | workBuffer[4];

            Assert.AreEqual(buffer.Length - 5, mapSize);

            Map decMap = AmqpSerializer.Deserialize <Map>(buffer);

            Assert.IsTrue(decMap[new Symbol("boolTrue")].Equals(true), "Boolean true expected.");
            Assert.IsTrue(decMap[new Symbol("boolFalse")].Equals(false), "Boolean false expected.");
            Assert.IsTrue(decMap[new Symbol("ubyte")].Equals(ubyteValue), "UByte value not equal.");
            Assert.IsTrue(decMap[new Symbol("ushort")].Equals(ushortValue), "UShort value not equal.");
            Assert.IsTrue(decMap[new Symbol("uint")].Equals(uintValue), "UInt value not equal.");
            Assert.IsTrue(decMap[new Symbol("ulong")].Equals(ulongValue), "ULong value not equal.");
            Assert.IsTrue(decMap[new Symbol("byte")].Equals(byteValue), "Byte value not equal.");
            Assert.IsTrue(decMap[new Symbol("short")].Equals(shortValue), "Short value not equal.");
            Assert.IsTrue(decMap[new Symbol("int")].Equals(intValue), "Int value not equal.");
            Assert.IsTrue(decMap[new Symbol("long")].Equals(longValue), "Long value not equal.");
            Assert.IsTrue(decMap[new Symbol("null")] == null, "Null object expected.");
            Assert.IsTrue(decMap[new Symbol("float")].Equals(floatValue), "Float value not equal.");
            Assert.IsTrue(decMap[new Symbol("double")].Equals(doubleValue), "Double value not equal.");
            Assert.IsTrue(decMap[new Symbol("char")].Equals(charValue), "Char value not equal.");
            Assert.IsTrue(decMap[new Symbol("datetime")].Equals(dtValue), "TimeStamp value not equal.");
            Assert.IsTrue(decMap[new Symbol("uuid")].Equals(uuidValue), "Uuid value not equal.");
            Assert.IsTrue(decMap[new Symbol("binaryNull")] == null, "Null binary expected.");
            byte[] bin8 = (byte[])decMap[new Symbol("binary8")];
            EnsureEqual(bin8, 0, bin8.Length, bin8ValueBin, 0, bin8ValueBin.Length);
            byte[] bin32 = (byte[])decMap[new Symbol("binary32")];
            EnsureEqual(bin32, 0, bin32.Length, bin32ValueBin, 0, bin32ValueBin.Length);

            Assert.IsTrue(decMap[new Symbol("symbolNull")] == null, "Null symbol expected.");
            Symbol symDecode = (Symbol)decMap[new Symbol("symbol8")];

            Assert.IsTrue(symDecode.Equals((Symbol)strValue), "AmqpSymbol value not equal.");
            symDecode = (Symbol)decMap[new Symbol("symbol32")];
            Assert.IsTrue(symDecode.Equals((Symbol)strBig), "AmqpSymbol value (big) not equal.");

            string strDecode = (string)decMap[new Symbol("string8")];

            Assert.IsTrue(strDecode.Equals(strValue), "string value not equal.");
            strDecode = (string)decMap[new Symbol("string32")];
            Assert.IsTrue(strDecode.Equals(strBig), "string value (big) not equal.");

            DescribedValue described = (DescribedValue)decMap[new Symbol("described1")];

            Assert.IsTrue(described.Descriptor.Equals(described1.Descriptor), "Described value 1 descriptor is different");
            Assert.IsTrue(described.Value.Equals(described1.Value), "Described value 1 value is different");
        }
Esempio n. 31
0
 public AmqpDescribedType(AmqpSerializer serializer, Type type)
     : base(serializer, type)
 {
 }
Esempio n. 32
0
 public DescribedListType(
     AmqpSerializer serializer,
     Type type,
     SerializableType baseType,
     string descriptorName,
     ulong? descriptorCode,
     SerialiableMember[] members,
     Dictionary<Type, SerializableType> knownTypes,
     MethodAccessor onDesrialized)
     : base(serializer, type, baseType, descriptorName, descriptorCode, members, knownTypes, onDesrialized)
 {
 }
        public void AmqpSerializerListEncodingTest()
        {
            Action <Person, Person> personValidator = (p1, p2) =>
            {
                Assert.IsTrue(p2 != null);
                Assert.AreEqual(21, p2.Age, "Age should be increased by OnDeserialized");
                Assert.AreEqual(p1.GetType().Name, p2.GetType().Name);
                Assert.AreEqual(p1.DateOfBirth.Value, p2.DateOfBirth.Value);
                Assert.AreEqual(p1.Properties.Count, p2.Properties.Count);
                foreach (var k in p1.Properties.Keys)
                {
                    Assert.AreEqual(p1.Properties[k], p2.Properties[k]);
                }
            };

            Action <List <int>, List <int> > gradesValidator = (l1, l2) =>
            {
                if (l1 == null || l2 == null)
                {
                    Assert.IsTrue(l1 == null && l2 == null);
                    return;
                }

                Assert.AreEqual(l1.Count, l2.Count);
                for (int i = 0; i < l1.Count; ++i)
                {
                    Assert.AreEqual(l1[i], l2[i]);
                }
            };

            // Create an object to be serialized
            Person p = new Student("Tom")
            {
                Address = new StreetAddress()
                {
                    FullAddress = new string('B', 1024)
                },
                Grades = new List <int>()
                {
                    1, 2, 3, 4, 5
                }
            };

            p.Age         = 20;
            p.DateOfBirth = new DateTime(1980, 5, 12, 10, 2, 45, DateTimeKind.Utc);
            p.Properties.Add("height", 6.1);
            p.Properties.Add("male", true);
            p.Properties.Add("nick-name", "big foot");

            byte[]     workBuffer = new byte[4096];
            ByteBuffer buffer     = new ByteBuffer(workBuffer, 0, 0, workBuffer.Length);

            AmqpSerializer.Serialize(buffer, p);
            Assert.AreEqual(2, p.Version);

            // Deserialize and verify
            Person p3 = AmqpSerializer.Deserialize <Person>(buffer);

            Assert.AreEqual(2, p.Version);
            personValidator(p, p3);
            Assert.AreEqual(((Student)p).Address.FullAddress, ((Student)p3).Address.FullAddress);
            gradesValidator(((Student)p).Grades, ((Student)p3).Grades);

            // Inter-op: it should be an AMQP described list as other clients see it
            buffer.Seek(0);
            DescribedValue dl1 = AmqpSerializer.Deserialize <DescribedValue>(buffer);

            Assert.AreEqual(dl1.Descriptor, 0x0000123400000001UL);
            List lv = dl1.Value as List;

            Assert.IsTrue(lv != null);
            Assert.AreEqual(p.Name, lv[0]);
            Assert.AreEqual(p.Age, lv[1]);
            Assert.AreEqual(p.DateOfBirth.Value, lv[2]);
            Assert.IsTrue(lv[3] is DescribedValue, "Address is decribed type");
            Assert.AreEqual(((DescribedValue)lv[3]).Descriptor, 0x0000123400000003UL);
            Assert.AreEqual(((List)((DescribedValue)lv[3]).Value)[0], ((Student)p).Address.FullAddress);
            Assert.IsTrue(lv[4] is Map, "Properties should be map");
            Assert.AreEqual(((Map)lv[4])["height"], p.Properties["height"]);
            Assert.AreEqual(((Map)lv[4])["male"], p.Properties["male"]);
            Assert.AreEqual(((Map)lv[4])["nick-name"], p.Properties["nick-name"]);
            Assert.IsTrue(lv[5] is List);

            // Non-default serializer
            AmqpSerializer serializer = new AmqpSerializer();
            ByteBuffer     bf1        = new ByteBuffer(1024, true);

            serializer.WriteObject(bf1, p);

            Person p4 = serializer.ReadObject <Person>(bf1);

            personValidator(p, p4);

            // Extensible: more items in the payload should not break
            DescribedValue dl2 = new DescribedValue(
                new Symbol("test.amqp:teacher"),
                new List()
            {
                "Jerry", 40, null, 50000, lv[4], null, null, "unknown-string", true, new Symbol("unknown-symbol")
            });
            ByteBuffer bf2 = new ByteBuffer(1024, true);

            serializer.WriteObject(bf2, dl2);
            serializer.WriteObject(bf2, 100ul);

            Person p5 = serializer.ReadObject <Person>(bf2);

            Assert.IsTrue(p5 is Teacher);
            Assert.IsTrue(p5.DateOfBirth == null);                       // nullable should work
            Assert.AreEqual(100ul, serializer.ReadObject <object>(bf2)); // unknowns should be skipped
            Assert.AreEqual(0, bf2.Length);

            // teacher
            Teacher teacher = new Teacher("Han");

            teacher.Age     = 30;
            teacher.Sallary = 60000;
            teacher.Classes = new Dictionary <int, string>()
            {
                { 101, "CS" }, { 102, "Math" }, { 205, "Project" }
            };

            ByteBuffer bf3 = new ByteBuffer(1024, true);

            serializer.WriteObject(bf3, teacher);

            Person p6 = serializer.ReadObject <Person>(bf3);

            Assert.IsTrue(p6 is Teacher);
            Assert.AreEqual(teacher.Age + 1, p6.Age);
            Assert.AreEqual(teacher.Sallary * 2, ((Teacher)p6).Sallary);
            Assert.AreEqual(teacher.Id, ((Teacher)p6).Id);
            Assert.AreEqual(teacher.Classes[101], ((Teacher)p6).Classes[101]);
            Assert.AreEqual(teacher.Classes[102], ((Teacher)p6).Classes[102]);
            Assert.AreEqual(teacher.Classes[205], ((Teacher)p6).Classes[205]);
        }
Esempio n. 34
0
 public static SerializableType CreateDescribedSimpleMapType(
     AmqpSerializer serializer,
     Type type,
     SerializableType baseType,
     SerialiableMember[] members,
     MethodAccessor[] serializationCallbacks)
 {
     return new DescribedSimpleMapType(serializer, type, baseType, members, serializationCallbacks);
 }
Esempio n. 35
0
 public AmqpSerializableType(AmqpSerializer serializer, Type type)
     : base(serializer, type)
 {
 }
Esempio n. 36
0
 protected CollectionType(AmqpSerializer serializer, Type type)
     : base(serializer, type)
 {
 }
Esempio n. 37
0
 protected SerializableType(AmqpSerializer serializer, Type type)
 {
     this.serializer = serializer;
     this.type = type;
     this.hasDefaultCtor = type.GetConstructor(Type.EmptyTypes) != null;
 }
Esempio n. 38
0
 protected DescribedCompoundType(
     AmqpSerializer serializer,
     Type type,
     SerializableType baseType,
     string descriptorName,
     ulong? descriptorCode,
     SerialiableMember[] members,
     Dictionary<Type, SerializableType> knownTypes,
     MethodAccessor[] serializationCallbacks)
     : base(serializer, type)
 {
     this.baseType = (DescribedCompoundType)baseType;
     this.descriptorName = descriptorName;
     this.descriptorCode = descriptorCode;
     this.members = members;
     this.serializationCallbacks = serializationCallbacks;
     this.knownTypes = GetKnownTypes(knownTypes);
 }
Esempio n. 39
0
 public static SerializableType CreateAmqpSerializableType(AmqpSerializer serializer, Type type)
 {
     return new AmqpSerializableType(serializer, type);
 }
Esempio n. 40
0
        public void AmqpSerializerSimpleListEncodingTest()
        {
            // serializer test
            {
                var add = new ListAddOperation()
                {
                    Version = 2, Name = "add", Param1 = 4, Param2 = 2
                };
                var buffer = new ByteBuffer(1024, true);
                AmqpSerializer.Serialize(buffer, add);

                var add2 = AmqpSerializer.Deserialize <ListAddOperation>(buffer);
                Assert.AreEqual(add2.Name, add.Name);
                Assert.AreEqual(add2.Version, add.Version);
                Assert.AreEqual(add2.Param1, add.Param1);
                Assert.AreEqual(add2.Param2, add.Param2);
            }

            // serializer - amqp
            {
                var sqrt = new ListSquareRootOperation()
                {
                    Version = 3, Name = "sqrt", Param = 64
                };
                var buffer = new ByteBuffer(1024, true);
                AmqpSerializer.Serialize(buffer, sqrt);

                var list = Encoder.ReadObject(buffer) as List;
                Assert.IsTrue(list != null);
                Assert.AreEqual(sqrt.Version, list[0]);
                Assert.AreEqual(sqrt.Name, list[1]);
                Assert.AreEqual(sqrt.Param, list[2]);
            }

            // amqp - serializer
            {
                var list = new List()
                {
                    4, "multi-op", "Do add first and then SQRT",
                    new Map()
                    {
                        { "Param1", 100 }, { "Param2", 200 }
                    },
                    new Map()
                    {
                        { "Param", 81L }
                    }
                };

                var buffer = new ByteBuffer(1024, true);
                Encoder.WriteObject(buffer, list);

                var multi = AmqpSerializer.Deserialize <ListMultiOperation>(buffer);
                Assert.AreEqual(multi.Version, list[0]);
                Assert.AreEqual(multi.Name, list[1]);
                Assert.AreEqual(multi.Instruction, list[2]);

                var map1 = (Map)list[3];
                Assert.AreEqual(multi.Add.Param1, map1["Param1"]);
                Assert.AreEqual(multi.Add.Param2, map1["Param2"]);

                var map2 = (Map)list[4];
                Assert.AreEqual(multi.SquareRoot.Param, map2["Param"]);
            }
        }
Esempio n. 41
0
 protected AmqpExtendedType(AmqpSerializer serializer, Type type)
     : base(serializer, type)
 {
 }
        public void AmqpSerializerSimpleMapEncodingTest()
        {
            // serializer test
            {
                var add = new AddOperation()
                {
                    Version = 2, Name = "add", Param1 = 4, Param2 = 2
                };
                var buffer = new ByteBuffer(1024, true);
                AmqpSerializer.Serialize(buffer, add);

                var add2 = AmqpSerializer.Deserialize <AddOperation>(buffer);
                Assert.AreEqual(add2.Name, add.Name);
                Assert.AreEqual(add2.Version, add.Version);
                Assert.AreEqual(add2.Param1, add.Param1);
                Assert.AreEqual(add2.Param2, add.Param2);
            }

            // serializer - amqp
            {
                var sqrt = new SquareRootOperation()
                {
                    Version = 3, Name = "sqrt", Param = 64
                };
                var buffer = new ByteBuffer(1024, true);
                AmqpSerializer.Serialize(buffer, sqrt);

                var map = Encoder.ReadObject(buffer) as Map;
                Assert.IsTrue(map != null);
                Assert.AreEqual(sqrt.Version, map["Version"]);
                Assert.AreEqual(sqrt.Name, map["Name"]);
                Assert.AreEqual(sqrt.Param, map["Param"]);
            }

            // amqp - serializer
            {
                var map = new Map()
                {
                    { "Version", 4 },
                    { "Name", "multi-op" },
                    { "Instruction", "Do add first and then SQRT" },
                    { "Add", new Map()
                      {
                          { "Param1", 100 }, { "Param2", 200 }
                      } },
                    { "SquareRoot", new Map()
                      {
                          { "Param", 81L }
                      } },
                };

                var buffer = new ByteBuffer(1024, true);
                Encoder.WriteObject(buffer, map);

                var multi = AmqpSerializer.Deserialize <MultiOperation>(buffer);
                Assert.AreEqual(multi.Version, map["Version"]);
                Assert.AreEqual(multi.Name, map["Name"]);
                Assert.AreEqual(multi.Instruction, map["Instruction"]);

                var map1 = (Map)map["Add"];
                Assert.AreEqual(multi.Add.Param1, map1["Param1"]);
                Assert.AreEqual(multi.Add.Param2, map1["Param2"]);

                var map2 = (Map)map["SquareRoot"];
                Assert.AreEqual(multi.SquareRoot.Param, map2["Param"]);
            }
        }
Esempio n. 43
0
 public DescribedSimpleMapType(
     AmqpSerializer serializer,
     Type type,
     SerializableType baseType,
     SerialiableMember[] members,
     MethodAccessor[] serializationCallbacks)
     : base(serializer, type, baseType, null, null, members, null, serializationCallbacks)
 {
     this.membersMap = new Dictionary<string, SerialiableMember>();
     foreach (SerialiableMember member in members)
     {
         this.membersMap.Add(member.Name, member);
     }
 }
        public void AmqpSerializerMapEncodingTest()
        {
            // serializer test
            {
                var specification = new ComputerSpecification()
                {
                    Cores = 2, RamSize = 4, Description = "netbook"
                };
                var product = new Product()
                {
                    Name = "Computer", Price = 499.98, Weight = 30, Specification = specification, Category = Category.Electronic
                };

                var buffer = new ByteBuffer(1024, true);
                AmqpSerializer.Serialize(buffer, product);
                Assert.AreEqual(product.Properties["OnSerializing"], "true");
                Assert.AreEqual(product.Properties["OnSerialized"], "true");

                var product2 = AmqpSerializer.Deserialize <Product>(buffer);
                Assert.AreEqual(product2.Properties["OnDeserializing"], "true");
                Assert.AreEqual(product2.Properties["OnDeserialized"], "true");
                Assert.AreEqual(product.Name, product2.Name);
                Assert.AreEqual(product.Price, product2.Price);
                Assert.AreEqual(product.Weight, product2.Weight);
                Assert.AreEqual(product.Category, product2.Category);

                var specification2 = product2.Specification as ComputerSpecification;
                Assert.IsTrue(specification2 != null);
                Assert.AreEqual(specification.Cores, specification2.Cores);
                Assert.AreEqual(specification.RamSize, specification2.RamSize);
                Assert.AreEqual(specification.Description, specification2.Description);
            }

            // serializer - amqp
            {
                var specification = new CarSpecification()
                {
                    Engine = "V6", HorsePower = 239, Description = "SUV"
                };
                var product = new Product()
                {
                    Name = "Car", Price = 34998, Weight = 5500, Specification = specification
                };
                var buffer = new ByteBuffer(1024, true);
                AmqpSerializer.Serialize(buffer, product);

                var value = Encoder.ReadObject(buffer) as DescribedValue;
                Assert.IsTrue(value != null);
                Assert.AreEqual(new Symbol("test.amqp:product"), value.Descriptor);

                var map = value.Value as Map;
                Assert.IsTrue(map != null);
                Assert.AreEqual(product.Name, map[new Symbol("Name")]);
                Assert.AreEqual(product.Price, map[new Symbol("Price")]);
                Assert.AreEqual(product.Weight, map[new Symbol("Weight")]);

                var specValue = map[new Symbol("Specification")] as DescribedValue;
                Assert.IsTrue(specValue != null);
                Assert.AreEqual(new Symbol("test.amqp:automotive-specification"), specValue.Descriptor);

                var specMap = specValue.Value as Map;
                Assert.IsTrue(specMap != null);
                Assert.AreEqual(specification.Engine, specMap[new Symbol("Engine")]);
                Assert.AreEqual(specification.HorsePower, specMap[new Symbol("HorsePower")]);
                Assert.AreEqual(specification.Description, specMap[new Symbol("Description")]);
            }

            // amqp - serializer
            {
                // keys MUST be symbols
                // the value types MUST match the field/property types in the class
                var specification = new DescribedValue(
                    new Symbol("test.amqp:automotive-specification"),
                    new Map()
                {
                    { new Symbol("Engine"), "V8" },
                    { new Symbol("HorsePower"), 222 },
                    { new Symbol("Description"), "AWD SUV" },
                });
                var product = new DescribedValue(
                    new Symbol("test.amqp:product"),
                    new Map()
                {
                    { new Symbol("Name"), "Car" },
                    { new Symbol("Price"), 41200.0 },
                    { new Symbol("Weight"), 5600L },
                    { new Symbol("Specification"), specification },
                    { new Symbol("Category"), (sbyte)Category.Automotive }
                });

                var buffer = new ByteBuffer(1024, true);
                Encoder.WriteObject(buffer, product);

                var product2 = AmqpSerializer.Deserialize <Product>(buffer);
                Assert.AreEqual("Car", product2.Name);
                Assert.AreEqual(41200.0, product2.Price);
                Assert.AreEqual(5600L, product2.Weight);
                Assert.AreEqual(Category.Automotive, product2.Category);

                var specification2 = product2.Specification as CarSpecification;
                Assert.IsTrue(specification2 != null);
                Assert.AreEqual("V8", specification2.Engine);
                Assert.AreEqual(222, specification2.HorsePower);
                Assert.AreEqual("AWD SUV", specification2.Description);
            }
        }
Esempio n. 45
0
 public GenericMapType(AmqpSerializer serializer, Type type, MemberAccessor keyAccessor,
     MemberAccessor valueAccessor, MethodAccessor addAccessor)
     : base(serializer, type)
 {
     this.keyType = this.serializer.GetType(keyAccessor.Type);
     this.valueType = this.serializer.GetType(valueAccessor.Type);
     this.keyAccessor = keyAccessor;
     this.valueAccessor = valueAccessor;
     this.addMethodAccessor = addAccessor;
 }
Esempio n. 46
0
 public DescribedSimpleListType(
     AmqpSerializer serializer,
     Type type,
     SerializableType baseType,
     SerialiableMember[] members,
     MethodAccessor[] serializationCallbacks)
     : base(serializer, type, baseType, null, null, members, null, serializationCallbacks)
 {
 }
Esempio n. 47
0
 public DescribedMapType(
     AmqpSerializer serializer,
     Type type,
     SerializableType baseType,
     string descriptorName,
     ulong? descriptorCode,
     SerialiableMember[] members,
     Dictionary<Type, SerializableType> knownTypes,
     MethodAccessor[] serializationCallbacks)
     : base(serializer, type, baseType, descriptorName, descriptorCode, members, knownTypes, serializationCallbacks)
 {
     this.membersMap = new Dictionary<string, SerialiableMember>();
     foreach(SerialiableMember member in members)
     {
         this.membersMap.Add(member.Name, member);
     }
 }