private static object EncoderTest(MessageSerializer target, IExtensible msg)
 {
     byte[] buf1 = target.Serialize(msg);
     byte[] buf2 = target.Serialize(target.Deserialize(buf1));
     Assert.IsNotNull(buf1);
     Assert.IsNotNull(buf2);
     Assert.AreEqual(buf1.Length, buf2.Length);
     Assert.IsTrue(buf1.SequenceEqual(buf2));
     return msg;
 }
        /// <summary>
        /// Stores the attribute in an extension.
        /// </summary>
        /// <param name="extensible">The object that is being extended.</param>
        /// <param name="attribute">The attribute to store.</param>
        /// <returns>This method always returns true.</returns>
        public bool StoreAttribute(IExtensible extensible, IExtensionAttribute attribute)
        {
            TestExtension extension;

            extension = extensible.Extensions.FirstOrDefault((e) => e.Name == TestExtension.ExtensionName) as TestExtension;
            if (extension == null)
            {
                extension = new TestExtension();
                extensible.Extensions.Add(extension);
            }

            extension.AddAttribute(attribute);

            return true;
        }
        /// <summary>
        /// Stores the element in an extension.
        /// </summary>
        /// <param name="extensible">The object that is being extended.</param>
        /// <param name="element">The element to store.</param>
        /// <returns>This method always returns true.</returns>
        public bool StoreElement(IExtensible extensible, ElementInfo element)
        {
            TestExtension extension;

            extension = extensible.Extensions.FirstOrDefault((e) => e.Name == TestExtension.ExtensionName) as TestExtension;
            if (extension == null)
            {
                extension = new TestExtension();
                extensible.Extensions.Add(extension);
            }

            extension.AddChild(element);

            return true;
        }
        /// <summary>
        /// Stores the attribute in an extension.
        /// </summary>
        /// <param name="extensible">The object that is being extended.</param>
        /// <param name="attribute">The attribute to store.</param>
        /// <returns>This method always returns true.</returns>
        public bool StoreAttribute(IExtensible extensible, IExtensionAttribute attribute)
        {
            GenericExtension extension;

            extension = extensible.Extensions.FirstOrDefault((e) => e.Name == GenericExtensionHandler.ExtensionName) as GenericExtension;
            if (extension == null)
            {
                extension = new GenericExtension(GenericExtensionHandler.ExtensionName);
                extensible.Extensions.Add(extension);
            }

            extension.AddAttribute(attribute);

            return true;
        }
        /// <summary>
        /// Stores the element in an extension.
        /// </summary>
        /// <param name="extensible">The object that is being extended.</param>
        /// <param name="element">The element to store.</param>
        /// <returns>This method always returns true.</returns>
        public bool StoreElement(IExtensible extensible, ElementInfo element)
        {
            GenericExtension extension;

            extension = extensible.Extensions.FirstOrDefault((e) => e.Name == GenericExtensionHandler.ExtensionName) as GenericExtension;
            if (extension == null)
            {
                extension = new GenericExtension(GenericExtensionHandler.ExtensionName);
                extensible.Extensions.Add(extension);
            }

            Utilities.SetParent(element.Element, extensible as XliffElement);
            extension.AddChild(element);

            return true;
        }
Example #6
0
        public static byte[] ToBytes(this IExtensible msg, int msgid)
        {
            int length = sizeof(short) + 2 + msg.GetExtensionObject(true).GetLength();
            var buffer = PooledByteBufferAllocator.Default.Buffer(length + sizeof(int)).WithOrder(ByteOrder.LittleEndian);

            buffer.WriteInt(length);
            buffer.WriteShort(msgid);

            MemoryStream stream = new MemoryStream(buffer.Array, buffer.WriterIndex + buffer.ArrayOffset, msg.GetExtensionObject(true).GetLength());

            Serializer.NonGeneric.Serialize(stream, msg);
            stream.Flush();
            buffer.SetWriterIndex(sizeof(int) + length);

            var ret = buffer.ReadBytes(buffer.ReadableBytes).ToArray();

            buffer.Release();
            return(ret);
        }
Example #7
0
        internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (tag <= 0)
            {
                throw new ArgumentOutOfRangeException("tag");
            }
            IExtension extn = instance.GetExtensionObject(createIfMissing: false);

            if (extn != null)
            {
                Stream      stream = extn.BeginQuery();
                object      value  = null;
                ProtoReader reader = null;
                try
                {
                    SerializationContext context = new SerializationContext();
                    reader = ProtoReader.Create(stream, model, context, -1);
                    while (model.TryDeserializeAuxiliaryType(reader, format, tag, type, ref value, skipOtherFields: true, asListItem: false, autoCreate: false, insideList: false) && value != null)
                    {
                        if (!singleton)
                        {
                            yield return(value);

                            value = null;
                        }
                    }
                    if (singleton && value != null)
                    {
                        yield return(value);
                    }
                }
                finally
                {
                    ProtoReader.Recycle(reader);
                    extn.EndQuery(stream);
                }
            }
        }
        /// <summary>
        /// All this does is call GetExtendedValuesTyped with the correct type for "instance";
        /// this ensures that we don't get issues with subclasses declaring conflicting types -
        /// the caller must respect the fields defined for the type they pass in.
        /// </summary>
        internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (tag <= 0)
            {
                throw new ArgumentOutOfRangeException("tag");
            }
            IExtension extn = instance.GetExtensionObject(false);

            if (extn == null)
            {
                yield break;
            }

            Stream      stream = extn.BeginQuery();
            object      value  = null;
            ProtoReader reader = null;

            try {
                SerializationContext ctx = new SerializationContext();
                reader = ProtoReader.Create(stream, model, ctx, ProtoReader.TO_EOF);
                while (model.TryDeserializeAuxiliaryType(reader, format, tag, type, ref value, true, false, false, false) && value != null)
                {
                    if (!singleton)
                    {
                        yield return(value);

                        value = null; // fresh item each time
                    }
                }
                if (singleton && value != null)
                {
                    yield return(value);
                }
            } finally {
                ProtoReader.Recycle(reader);
                extn.EndQuery(stream);
            }
        }
Example #9
0
        private void RecvMsgLoop()
        {
            byte[] head = new byte[8];
            while (true)
            {
                try {
                    // 读出消息头部8字节(4字节类型+4字节长度)
                    int remainLen = 8;
                    while (remainLen > 0)
                    {
                        remainLen -= _stream.Read(head, 8 - remainLen, remainLen);
                    }

                    int msgLen  = (head[0] << 24) + (head[1] << 16) + (head[2] << 8) + head[3];
                    int msgType = (head[4] << 24) + (head[5] << 16) + (head[6] << 8) + head[7];

                    IExtensible protoData = null;
                    if (msgLen > 0)
                    {
                        byte[] data = new byte[msgLen];
                        remainLen = msgLen;
                        while (remainLen > 0)
                        {
                            remainLen -= _stream.Read(data, msgLen - remainLen, remainLen);
                            //Console.WriteLine("remainLen = " + remainLen + " : " + (DateTime.Now.Ticks/TimeSpan.TicksPerMillisecond-startTimeStamp));
                        }

                        protoData = Deserialize(msgType, data, 0, msgLen);
                    }

                    _recvMsgQueue.Enqueue(new ProtoMessage(msgType, protoData));
                } catch (System.Exception ex) {
                    Debug.LogError("RecvThread error!!!");
                    Debug.LogError(ex.ToString());
                    Debug.LogError(ex.StackTrace);

                    _recvMsgQueue.Enqueue(new ProtoMessage(Constants.CORPC_MSG_TYPE_DISCONNECT, null));

                    return;
                }
            }
        }
    public void Send(uint protocolId, IExtensible body)
    {
        MemoryStream bodyStream;
        int          bodyLength;

        if (body != null)
        {
            //序列化包体
            bodyStream = new MemoryStream();
            Serializer.Serialize(bodyStream, body);
            bodyLength = (int)bodyStream.Length;
        }
        else
        {
            bodyLength = 0;
            bodyStream = null;
        }
        byte[] buffer = bodyStream.ToArray();
        Send(protocolId, buffer);
    }
Example #11
0
 public void Send(string requestType, IExtensible msg)
 {
     if (this != _gameBattle)
     {
         return;
     }
     msgStream.SetLength(0);
     Serializer.Serialize(msgStream, msg);
     if (_gameBattle.IsConnect())
     {
         try
         {
             mSocket.Send(msgStream.ToArray());
         }
         catch (Exception e)
         {
             DebugUtils.LogError(e.ToString());
         }
     }
 }
Example #12
0
        internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format,
                                               object value)
        {
#if FEAT_IKVM
            throw new NotSupportedException();
#else
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // TODO
            //model.CheckTagNotInUse(tag);

            // obtain the extension object and prepare to write
            IExtension extn = instance.GetExtensionObject(true);
            if (extn == null)
            {
                throw new InvalidOperationException("No extension object available; appended data would be lost.");
            }
            bool   commit = false;
            Stream stream = extn.BeginAppend();
            try
            {
                using (ProtoWriter writer = new ProtoWriter(stream, model, null))
                {
                    model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false);
                    writer.Close();
                }
                commit = true;
            }
            finally
            {
                extn.EndAppend(stream, commit);
            }
#endif
        }
Example #13
0
    // ProtoBuf 发送数据
    public static void Send(IExtensible msg)
    {
        // 状态判断
        if (socket == null || !socket.Connected)
        {
            return;
        }

        if (isConnecting || isClosing)
        {
            return;
        }

        // 数据编码
        byte[] nameBytes = ProtoMsgBase.EncodeName(msg);
        byte[] bodyBytes = ProtoMsgBase.Encode(msg);
        int    len       = nameBytes.Length + bodyBytes.Length;

        byte[] sendBytes = new byte[2 + len];
        // 组装长度
        sendBytes[0] = (byte)(len % 256);
        sendBytes[1] = (byte)(len / 256);
        // 组装名字
        Array.Copy(nameBytes, 0, sendBytes, 2, nameBytes.Length);
        // 组装消息体
        Array.Copy(bodyBytes, 0, sendBytes, 2 + nameBytes.Length, bodyBytes.Length);
        // 写入队列
        ByteArray ba    = new ByteArray(sendBytes);
        int       count = 0;   // WriteQueue的长度

        lock (writeQueue) {
            writeQueue.Enqueue(ba);
            count = writeQueue.Count;
        }
        // send
        if (count == 1)
        {
            socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallback, socket);
        }
    }
Example #14
0
        public override bool validate(string v)
        {
            ProtoData    pd = ProtoData.ms_protoDatas[m_tableName];
            Type         t  = pd.Type;
            PropertyInfo pi = t.GetProperty("id_raw");

            // 如果是第一次使用该外键,建立查找字典
            if (null == pd.m_dataDic)
            {
                var dic = new Dictionary <int, IExtensible>();
                for (int i = 0; i < pd.Count; i++)
                {
                    IExtensible o  = pd[i];
                    int         id = int.Parse((string)pi.GetValue(o, null));
                    // 主键重复
                    try
                    {
                        dic.Add(id, o);
                    }
                    catch (ArgumentException)
                    {
                        if ("CutsceneConfig" != m_tableName)
                        {
                            Console.WriteLine("  " + m_tableName + "表包含重复的ID:" + id);
                        }
                    }
                }
                pd.m_dataDic = dic;
            }

            try
            {
                int vid = int.Parse(v);
                return(pd.m_dataDic.ContainsKey(vid));
            }
            catch (Exception)
            {
                return(false);
            }
        }
        internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value)
        {
            model ??= TypeModel.DefaultModel;
            if (instance is null) ThrowHelper.ThrowArgumentNullException(nameof(instance));
            if (value is null) ThrowHelper.ThrowArgumentNullException(nameof(value));

            // TODO
            //model.CheckTagNotInUse(tag);

            // obtain the extension object and prepare to write
            IExtension extn = instance.GetExtensionObject(true);
            if (extn is null) ThrowHelper.ThrowInvalidOperationException("No extension object available; appended data would be lost.");
            bool commit = false;
            Stream stream = extn.BeginAppend();
            try
            {
                var state = ProtoWriter.State.Create(stream, model, null);
                try
                {
                    model.TrySerializeAuxiliaryType(ref state, null, format, tag, value, false, null, isRoot: false);
                    state.Close();
                }
                catch
                {
                    state.Abandon();
                    throw;
                }
                finally
                {
                    state.Dispose();
                }

                commit = true;
            }
            finally
            {
                extn.EndAppend(stream, commit);
            }
        }
Example #16
0
        static byte[] GetExtensionBytes(IExtensible obj)
        {
            Assert.IsNotNull(obj, "null extensible");
            IExtension extn = obj.GetExtensionObject(false);

            Assert.IsNotNull(extn, "no extension object");
            Stream s = extn.BeginQuery();

            try
            {
                using (MemoryStream ms = new MemoryStream()) {
                    int b; // really lazy clone...
                    while ((b = s.ReadByte()) >= 0)
                    {
                        ms.WriteByte((byte)b);
                    }
                    return(ms.ToArray());
                }
            } finally {
                extn.EndQuery(s);
            }
        }
Example #17
0
        static void debugString(IExtensible msg, Type type, StringBuilder log)
        {
            MethodInfo method = typeof(MessageTable).GetMethod("GetExtensions");

            if (method != null)
            {
                Dictionary <int, Type> extensions = method.Invoke(null, new object[] { type }) as Dictionary <int, Type>;
                foreach (KeyValuePair <int, Type> pair in extensions)
                {
                    object _msg    = null;
                    bool   succeed = Extensible.TryGetValue(serializer_, pair.Value, msg,
                                                            pair.Key, DataFormat.Default, true, out _msg);
                    if (succeed)
                    {
                        var json = JObject.FromObject(_msg);
                        log.Append(prettyJsonString(json));

                        debugString((IExtensible)_msg, pair.Value, log);
                    }
                }
            }
        }
Example #18
0
        void DumpOptionsFieldRecursive(FieldDescriptorProto field, IExtensible options, Dictionary <string, string> optionsKv, string path)
        {
            string key = string.IsNullOrEmpty(path) ? $"({field.name})" : $"{path}.{field.name}";

            if (IsNamedType(field.type) && !string.IsNullOrEmpty(field.type_name))
            {
                var fieldData = protobufTypeMap[field.type_name].Source;

                if (fieldData is EnumDescriptorProto enumProto)
                {
                    if (Extensible.TryGetValue(options, field.number, out int idx))
                    {
                        var value = enumProto.value.Find(x => x.number == idx);

                        optionsKv.Add(key, value.name);
                    }
                }
                else if (fieldData is DescriptorProto messageProto)
                {
                    ExtensionPlaceholder extension = Extensible.GetValue <ExtensionPlaceholder>(options, field.number);

                    if (extension != null)
                    {
                        foreach (var subField in messageProto.field)
                        {
                            DumpOptionsFieldRecursive(subField, extension, optionsKv, key);
                        }
                    }
                }
            }
            else
            {
                if (ExtractType(options, field, out var value))
                {
                    optionsKv.Add(key, value);
                }
            }
        }
Example #19
0
        private void SendMessage(int messageType, int messageId, IExtensible message)
        {
            var messageName = message.GetType().FullName;
            var nameSize    = messageName.Length;

            byte[] messageByteArray;
            using (var stream = new MemoryStream())
            {
                Serializer.NonGeneric.Serialize(stream, message);
                messageByteArray = stream.ToArray();
            }
            var messageSize      = messageByteArray.Length;
            var output           = new ArraySegmentOutput();
            var messageNameBytes = Encoding.UTF8.GetBytes(messageName);

            output.WriteInt(messageId);
            output.WriteByte(messageType);
            output.WriteByte(nameSize);
            output.WriteInt(messageSize);
            output.WriteBytes(messageNameBytes, 0, messageNameBytes.Length);
            output.WriteBytes(messageByteArray, 0, messageByteArray.Length);
            bcpSession.Send(output.Buffers);
        }
Example #20
0
        public static NetMsgData UnpackNetMsg(byte[] msgData)
        {
            MemoryStream ms = null;

            using (ms = new MemoryStream(msgData))
            {
                BinaryReader reader  = new BinaryReader(ms);
                ushort       msgLen  = reader.ReadUInt16();
                ushort       protoId = reader.ReadUInt16();

                if (msgLen <= msgData.Length - 4)
                {
                    IExtensible protoData = CreateProtoBuf.GetProtoData((ProtoDefine)protoId, reader.ReadBytes(msgLen));
                    return(NetMsgData.GetMsgData((ProtoDefine)protoId, protoData, msgLen));
                }
                else
                {
                    Debug.LogError("协议长度错误");
                }
            }

            return(null);
        }
Example #21
0
        /// <summary>
        /// 发送单机数据
        /// </summary>
        /// <param name="cmd">单机类型</param>
        /// <param name="body">发送实体类</param>
        public static bool SendProtobufCmd(SendMode mode, Cmd cmd, IExtensible body)
        {
            //if (!LoggedIn)
            //    return false;
            try {
                switch (mode)
                {
                case SendMode.TCP:
                    network.Instance.send_protobuf_cmd((int)Stype.Logic, (int)cmd, body);
                    break;

                case SendMode.UDP:
                    network.Instance.udp_send_protobuf_cmd((int)Stype.Logic, (int)cmd, body);
                    break;
                }
            }
            catch (Exception)
            {
                Start();
                return(false);
            }
            return(true);
        }
Example #22
0
        /// <summary>

        /// Queries an extensible object for an additional (unexpected) data-field for the instance.

        /// The value returned (in "value") is the composed value after merging any duplicated content;

        /// if the value is "repeated" (a list), then use GetValues instead.

        /// </summary>

        /// <param name="type">The data-type of the field.</param>

        /// <param name="model">The model to use for configuration.</param>

        /// <param name="value">The effective value of the field, or the default value if not found.</param>

        /// <param name="instance">The extensible object to obtain the value from.</param>

        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>

        /// <param name="format">The data-format to use when decoding the value.</param>

        /// <param name="allowDefinedTag">Allow tags that are present as part of the definition; for example, to query unknown enum values.</param>

        /// <returns>True if data for the field was present, false otherwise.</returns>

        public static bool TryGetValue(TypeModel model, System.Type type, IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out object value)

        {
            value = null;

            bool set = false;

            foreach (object val in ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, true, allowDefinedTag))

            {
                // expecting at most one yield...

                // but don't break; need to read entire stream

                value = val;

                set = true;
            }



            return(set);
        }
Example #23
0
        /// <summary>

        /// Queries an extensible object for an additional (unexpected) data-field for the instance.

        /// The value returned (in "value") is the composed value after merging any duplicated content;

        /// if the value is "repeated" (a list), then use GetValues instead.

        /// </summary>

        /// <typeparam name="TValue">The data-type of the field.</typeparam>

        /// <param name="value">The effective value of the field, or the default value if not found.</param>

        /// <param name="instance">The extensible object to obtain the value from.</param>

        /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>

        /// <param name="format">The data-format to use when decoding the value.</param>

        /// <param name="allowDefinedTag">Allow tags that are present as part of the definition; for example, to query unknown enum values.</param>

        /// <returns>True if data for the field was present, false otherwise.</returns>

        public static bool TryGetValue <TValue>(IExtensible instance, int tag, DataFormat format, bool allowDefinedTag, out TValue value)

        {
            value = default(TValue);

            bool set = false;

            foreach (TValue val in ExtensibleUtil.GetExtendedValues <TValue>(instance, tag, format, true, allowDefinedTag))

            {
                // expecting at most one yield...

                // but don't break; need to read entire stream

                value = val;

                set = true;
            }



            return(set);
        }
Example #24
0
        // Token: 0x06003291 RID: 12945 RVA: 0x001273D8 File Offset: 0x001257D8
        internal static IEnumerable <TValue> GetExtendedValues <TValue>(IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag)
        {
            IEnumerator enumerator = ExtensibleUtil.GetExtendedValues(RuntimeTypeModel.Default, typeof(TValue), instance, tag, format, singleton, allowDefinedTag).GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    object obj   = enumerator.Current;
                    TValue value = (TValue)((object)obj);
                    yield return(value);
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
            yield break;
        }
Example #25
0
        /// <summary>
        /// Stores an attribute in an extension. If no appropriate extension handler was found, a general purpose
        /// one will be created.
        /// </summary>
        /// <param name="extensible">The object that contains the extensions.</param>
        /// <returns>A result indicating whether the attribute was stored.</returns>
        private SetAttributeResult StoreAttributeExtension(IExtensible extensible)
        {
            SetAttributeResult result;

            result = SetAttributeResult.InvalidAttribute;
            if (this.settings.IncludeExtensions)
            {
                if (this.reader.Prefix == NamespacePrefixes.XmlNamespace)
                {
                    result = SetAttributeResult.ReservedName;
                }
                else if ((extensible != null) && extensible.SupportsAttributeExtensions)
                {
                    ExtensionNameInfo info;
                    IExtensionHandler handler;

                    info = new ExtensionNameInfo(this.reader.Prefix, this.reader.NamespaceURI, this.reader.LocalName);
                    if (this.handlers.Value.TryGetValue(this.reader.NamespaceURI, out handler) ||
                        this.handlers.Value.TryGetValue(XliffReader.DefaultHandlerKey, out handler))
                    {
                        IExtensionAttribute attribute;

                        attribute = handler.CreateAttribute(info, this.reader.Value);
                        if (handler.StoreAttribute(extensible, attribute))
                        {
                            result = SetAttributeResult.Success;
                        }
                    }
                    else
                    {
                        Debug.Assert(false, "Default handler was not found.");
                    }
                }
            }

            return(result);
        }
Example #26
0
        /// <summary>
        /// Copies any extension data stored for the instance to the underlying stream
        /// </summary>
        public static void AppendExtensionData(IExtensible instance, ProtoWriter writer, ref State state)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }
            // we expect the writer to be raw here; the extension data will have the
            // header detail, so we'll copy it implicitly
            if (writer.WireType != WireType.None)
            {
                throw CreateException(writer);
            }

            IExtension extn = instance.GetExtensionObject(false);

            if (extn != null)
            {
                // unusually we *don't* want "using" here; the "finally" does that, with
                // the extension object being responsible for disposal etc
                Stream source = extn.BeginQuery();
                try
                {
                    if (ProtoReader.TryConsumeSegmentRespectingPosition(source, out var data, ProtoReader.TO_EOF))
                    {
                        writer.ImplWriteBytes(ref state, data.Array, data.Offset, data.Count);
                        writer.Advance(data.Count);
                    }
                    else
                    {
                        writer.ImplCopyRawFromStream(ref state, source);
                    }
                }
Example #27
0
        /// <summary>
        /// Copies the current field into the instance as extension data
        /// </summary>
        public void AppendExtensionData(IExtensible instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            IExtension extn   = instance.GetExtensionObject(true);
            bool       commit = false;
            // unusually we *don't* want "using" here; the "finally" does that, with
            // the extension object being responsible for disposal etc
            Stream dest = extn.BeginAppend();

            try
            {
                //TODO: replace this with stream-based, buffered raw copying
                using (ProtoWriter writer = new ProtoWriter(dest, model))
                {
                    AppendExtensionField(writer);
                    writer.Close();
                }
                commit = true;
            }
            finally { extn.EndAppend(dest, commit); }
        }
 /// <summary>
 /// 将消息序列化为二进制的方法
 /// </summary>
 /// <param name="model">要序列化的对象</param>
 public static byte[] Serialize(IExtensible model)
 {
     try
     {
         //涉及格式转换,需要用到流,将二进制序列化到流中
         using (MemoryStream ms = new MemoryStream())
         {
             //使用ProtoBuf工具的序列化方法
             Serializer.Serialize <IExtensible>(ms, model);
             //定义二级制数组,保存序列化后的结果
             byte[] result = new byte[ms.Length];
             //将流的位置设为0,起始点
             ms.Position = 0;
             //将流中的内容读取到二进制数组中
             ms.Read(result, 0, result.Length);
             return(result);
         }
     }
     catch (Exception ex)
     {
         UIUtils.Log("序列化失败: " + ex.ToString());
         return(null);
     }
 }
Example #29
0
        public void AppendExtensionData(IExtensible instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            IExtension extensionObject = instance.GetExtensionObject(true);
            bool       commit          = false;
            Stream     stream          = extensionObject.BeginAppend();

            try
            {
                using (ProtoWriter protoWriter = new ProtoWriter(stream, this.model, null))
                {
                    this.AppendExtensionField(protoWriter);
                    protoWriter.Close();
                }
                commit = true;
            }
            finally
            {
                extensionObject.EndAppend(stream, commit);
            }
        }
Example #30
0
            public void SendRequest(
                IExtensible message,
                Type responseType,
                Action <IExtensible, Action <IExtensible> > successCallback,
                Action <IExtensible, Action <IExtensible> > failCallback,
                Action <IExtensible> uiSuccessCallback,
                Action <IExtensible> uiFailCallback)
            {
                int messageId = Interlocked.Increment(ref nextMessageId);

                lock (outgoingRpcResponseHandlers)
                {
                    if (!outgoingRpcResponseHandlers.ContainsKey(messageId))
                    {
                        var responseHandler = new UIResponseHandler(responseType, successCallback, failCallback, uiSuccessCallback, uiFailCallback);
                        outgoingRpcResponseHandlers.Add(messageId, responseHandler);
                        rpcSession.SendMessage(BcpRpc.REQUEST, messageId, message);
                    }
                    else
                    {
                        throw new IllegalRpcData("Already contains message id.");
                    }
                }
            }
Example #31
0
 /// <summary>
 /// Appends the value as an additional (unexpected) data-field for the instance.
 /// Note that for non-repeated sub-objects, this equates to a merge operation;
 /// for repeated sub-objects this adds a new instance to the set; for simple
 /// values the new value supercedes the old value.
 /// </summary>
 /// <remarks>Note that appending a value does not remove the old value from
 /// the stream; avoid repeatedly appending values for the same field.</remarks>
 /// <param name="model">The model to use for configuration.</param>
 /// <param name="format">The data-format to use when encoding the value.</param>
 /// <param name="instance">The extensible object to append the value to.</param>
 /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
 /// <param name="value">The value to append.</param>
 public static void AppendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value)
 {
     ExtensibleUtil.AppendExtendValue(model, instance, tag, format, value);
 }
Example #32
0
        /// <summary>
        /// Serializes extension information on an extensible object.
        /// </summary>
        /// <param name="extensible">The extensible object that may contain extensions.</param>
        /// <param name="serializeAttributes">If true, attributes extensions will be serialized, otherwise they'll be skipped.</param>
        /// <param name="serializeChildren">If true, element extensions will be serialized, otherwise they'll be skipped.</param>
        private void SerializeExtensions(IExtensible extensible, bool serializeAttributes, bool serializeChildren)
        {
            if (this.settings.IncludeExtensions && (extensible != null))
            {
                foreach (IExtension extension in extensible.Extensions)
                {
                    if (serializeAttributes && extension.HasAttributes)
                    {
                        if (extensible.SupportsAttributeExtensions)
                        {
                            this.SerializeExtensionAttributes(extension);
                        }
                        else
                        {
                            string message;

                            message = string.Format(
                                            Properties.Resources.XliffWriter_ExtensionTypeNotSupported_Format,
                                            extensible.GetType().Name,
                                            "Attribute");
                            throw new NotSupportedException(message);
                        }
                    }

                    if (serializeChildren && extension.HasChildren)
                    {
                        if (extensible.SupportsElementExtensions)
                        {
                            this.SerializeExtensionChildren(extension);
                        }
                        else
                        {
                            string message;

                            message = string.Format(
                                            Properties.Resources.XliffWriter_ExtensionTypeNotSupported_Format,
                                            extensible.GetType().Name,
                                            "Element");
                            throw new NotSupportedException(message);
                        }
                    }
                }
            }
        }
Example #33
0
        /// <summary>
        /// Enumerates all extensions and their descendants storing the set of unique Xml namespaces used for serializing
        /// the elements.
        /// </summary>
        /// <param name="extensible">The extensible object that may contain extensions to enumerate over. This value
        /// may be null.</param>
        /// <param name="namespaces">The set of unique namespaces.</param>
        private void GetXmlElementNamespaces(IExtensible extensible, Dictionary<string, string> namespaces)
        {
            if ((extensible != null) && extensible.HasExtensions)
            {
                foreach (IExtension extension in extensible.Extensions)
                {
                    if (extension.HasAttributes)
                    {
                        foreach (IExtensionAttribute attribute in extension.GetAttributes())
                        {
                            // Custom attributes must have a prefix and namespace.
                            this.ValidatePrefixAndNamespace(
                                                            attribute.Prefix,
                                                            attribute.Namespace,
                                                            attribute.LocalName,
                                                            false);

                            this.AddNamespaceOrThrowIfMismatch(namespaces, attribute.Prefix, attribute.Namespace);
                        }
                    }

                    if (extension.HasChildren)
                    {
                        this.GetXmlElementNamespaces(extension.GetChildren(), namespaces, true);
                    }
                }
            }
        }
 public MumblePacketEventArgs(IExtensible message)
 {
     Message = message;
 }
Example #35
0
 public static void AppendExtensionData(IExtensible instance, ProtoWriter writer)
 {
     if (instance == null)
     {
         throw new ArgumentNullException("instance");
     }
     if (writer == null)
     {
         throw new ArgumentNullException("writer");
     }
     if (writer.wireType != WireType.None)
     {
         throw ProtoWriter.CreateException(writer);
     }
     IExtension extensionObject = instance.GetExtensionObject(false);
     if (extensionObject != null)
     {
         Stream stream = extensionObject.BeginQuery();
         try
         {
             ProtoWriter.CopyRawFromStream(stream, writer);
         }
         finally
         {
             extensionObject.EndQuery(stream);
         }
     }
 }
Example #36
0
 /// <summary>
 /// Appends the value as an additional (unexpected) data-field for the instance.
 /// Note that for non-repeated sub-objects, this equates to a merge operation;
 /// for repeated sub-objects this adds a new instance to the set; for simple
 /// values the new value supercedes the old value.
 /// </summary>
 /// <remarks>Note that appending a value does not remove the old value from
 /// the stream; avoid repeatedly appending values for the same field.</remarks>
 /// <typeparam name="TValue">The data-type of the field.</typeparam>
 /// <param name="format">The data-format to use when encoding the value.</param>
 /// <param name="instance">The extensible object to append the value to.</param>
 /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
 /// <param name="value">The value to append.</param>
 public static void AppendValue <TValue>(IExtensible instance, int tag, DataFormat format, TValue value)
 {
     ExtensibleUtil.AppendExtendValue(RuntimeTypeModel.Default, instance, tag, format, value);
 }
        /// <summary>
        /// Creates an extension with every element and attribute and adds it to the container.
        /// </summary>
        /// <param name="extensible">The container to add the extension to.</param>
        private void AddExtension(IExtensible extensible)
        {
            GenericExtension extension;

            extension = new GenericExtension("extension");

            if (extensible.SupportsAttributeExtensions)
            {
                extension.AddAttribute(new GenericExtensionAttribute("ext", "ext:namespace", "attr2", "value"));
            }

            if (extensible.SupportsElementExtensions)
            {
                GenericElement element;

                element = new GenericElement();
                element.SetAttribute("ext", "ext:namespace", "attr1", "value");
                extension.AddChild(new ElementInfo(new XmlNameInfo("ext", "ext:namespace", "extelement"), element));
            }

            extensible.Extensions.Add(extension);
        }
Example #38
0
 private byte[] Serialize(IExtensible extensible)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         Serializer.Serialize(stream, extensible);
         return stream.ToArray();
     }
 }
Example #39
0
        /// <summary>
        /// Stores an attribute in an extension. If no appropriate extension handler was found, a general purpose
        /// one will be created.
        /// </summary>
        /// <param name="extensible">The object that contains the extensions.</param>
        /// <returns>A result indicating whether the attribute was stored.</returns>
        private SetAttributeResult StoreAttributeExtension(IExtensible extensible)
        {
            SetAttributeResult result;

            result = SetAttributeResult.InvalidAttribute;
            if (this.settings.IncludeExtensions)
            {
                if (this.reader.Prefix == NamespacePrefixes.XmlNamespace)
                {
                    result = SetAttributeResult.ReservedName;
                }
                else if ((extensible != null) && extensible.SupportsAttributeExtensions)
                {
                    ExtensionNameInfo info;
                    IExtensionHandler handler;

                    info = new ExtensionNameInfo(this.reader.Prefix, this.reader.NamespaceURI, this.reader.LocalName);
                    if (this.handlers.Value.TryGetValue(this.reader.NamespaceURI, out handler) ||
                        this.handlers.Value.TryGetValue(XliffReader.DefaultHandlerKey, out handler))
                    {
                        IExtensionAttribute attribute;

                        attribute = handler.CreateAttribute(info, this.reader.Value);
                        if (handler.StoreAttribute(extensible, attribute))
                        {
                            result = SetAttributeResult.Success;
                        }
                    }
                    else
                    {
                        Debug.Assert(false, "Default handler was not found.");
                    }
                }
            }

            return result;
        }
Example #40
0
 public void AppendExtensionData(IExtensible instance)
 {
     if (instance == null)
     {
         throw new ArgumentNullException("instance");
     }
     IExtension extensionObject = instance.GetExtensionObject(true);
     bool commit = false;
     Stream stream = extensionObject.BeginAppend();
     try
     {
         using (ProtoWriter protoWriter = new ProtoWriter(stream, this.model, null))
         {
             this.AppendExtensionField(protoWriter);
             protoWriter.Close();
         }
         commit = true;
     }
     finally
     {
         extensionObject.EndAppend(stream, commit);
     }
 }
Example #41
0
 /// <summary>
 /// Sends the protobuf serializable object autmatically determine the name.
 /// </summary>
 /// <param name="type">type of the object to send</param>
 public void SendObject(IExtensible o)
 {
     byte[] buffer = Serialize(o);
     string type = o.GetType().Name;
     Message message = PrepareMessage(type, buffer);
     send(message);
 }
 public static MessageTypes MessageType(IExtensible mumbleProto)
 {
     return Types.First(kvp => kvp.Value == mumbleProto.GetType()).Key;
 }
Example #43
0
 /// <summary>
 /// Queries an extensible object for an additional (unexpected) data-field for the instance.
 /// Each occurrence of the field is yielded separately, making this usage suitable for "repeated"
 /// (list) fields.
 /// </summary>
 /// <remarks>The extended data is processed lazily as the enumerator is iterated.</remarks>
 /// <param name="model">The model to use for configuration.</param>
 /// <param name="type">The data-type of the field.</param>
 /// <param name="instance">The extensible object to obtain the value from.</param>
 /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
 /// <param name="format">The data-format to use when decoding the value.</param>
 /// <returns>An enumerator that yields each occurrence of the field.</returns>
 public static IEnumerable GetValues(TypeModel model, System.Type type, IExtensible instance, int tag, DataFormat format)
 {
     return(ExtensibleUtil.GetExtendedValues(model, type, instance, tag, format, false, false));
 }
 /// <summary>
 /// Copies the current field into the instance as extension data
 /// </summary>
 public void AppendExtensionData(IExtensible instance)
 {
     if (instance == null) throw new ArgumentNullException("instance");
     IExtension extn = instance.GetExtensionObject(true);
     bool commit = false;
     // unusually we *don't* want "using" here; the "finally" does that, with
     // the extension object being responsible for disposal etc
     Stream dest = extn.BeginAppend();
     try
     {
         //TODO: replace this with stream-based, buffered raw copying
         using (ProtoWriter writer = new ProtoWriter(dest, model))
         {
             AppendExtensionField(writer);
             writer.Close();
         }
         commit = true;
     }
     finally { extn.EndAppend(dest, commit); }
 }
Example #45
0
 /// <summary>
 /// Appends the value as an additional (unexpected) data-field for the instance.
 /// Note that for non-repeated sub-objects, this equates to a merge operation;
 /// for repeated sub-objects this adds a new instance to the set; for simple
 /// values the new value supercedes the old value.
 /// </summary>
 /// <remarks>Note that appending a value does not remove the old value from
 /// the stream; avoid repeatedly appending values for the same field.</remarks>
 /// <typeparam name="TValue">The type of the value to append.</typeparam>
 /// <param name="instance">The extensible object to append the value to.</param>
 /// <param name="tag">The field identifier; the tag should not be defined as a known data-field for the instance.</param>
 /// <param name="value">The value to append.</param>
 public static void AppendValue <TValue>(IExtensible instance, int tag, TValue value)
 {
     AppendValue <TValue>(instance, tag, DataFormat.Default, value);
 }
Example #46
0
 /// <summary>
 /// Sends the protobuf serializable object.
 /// </summary>
 /// <param name="type">type of the object to send</param>
 /// <param name="o">the object to send</param>
 public void SendObject(String type, IExtensible o)
 {
     byte[] buffer = Serialize(o);
     Message message = PrepareMessage(type, buffer);
     send(message);
 }
Example #47
0
        public static void AppendExtensionData(IExtensible instance, ProtoWriter writer)
        {
            State state = writer.DefaultState();

            AppendExtensionData(instance, writer, ref state);
        }
Example #48
0
 /// <summary>
 /// Updates the function body and the invokable property of all modules in this IExtensible
 /// </summary>
 /// <param name="extensible">The object to update modules upon.</param>
 private void UpdateModules(IExtensible extensible)
 {
     foreach (var module in extensible.Modules)
     {
         module.FunctionBody = presetModules[module.Name].FunctionBody;
         module.IsInvokable = presetModules[module.Name].IsInvokable;
     }
 }
Example #49
0
        /// <summary>
        /// Copies any extension data stored for the instance to the underlying stream
        /// </summary>
        public static void AppendExtensionData(IExtensible instance, ProtoWriter writer)
        {
            if (instance == null) throw new ArgumentNullException("instance");
            // we expect the writer to be raw here; the extension data will have the
            // header detail, so we'll copy it implicitly
            if(writer.wireType != WireType.None) throw CreateException(writer);

            IExtension extn = instance.GetExtensionObject(false);
            if (extn != null)
            {
                // unusually we *don't* want "using" here; the "finally" does that, with
                // the extension object being responsible for disposal etc
                Stream source = extn.BeginQuery();
                try
                {
                    CopyRawFromStream(source, writer);
                }
                finally { extn.EndQuery(source); }
            }
        }
        private void MumbleWrite(IExtensible message)
        {
            var sslStreamWriter = new BinaryWriter(sslStream);
            if (message is UDPTunnel)
            {
                var audioMessage = message as UDPTunnel;

                Int16 messageType = (Int16)MumbleProtocolFactory.MessageType(message);
                Int32 messageSize = (Int32)audioMessage.packet.Length;

                sslStreamWriter.Write(IPAddress.HostToNetworkOrder(messageType));
                sslStreamWriter.Write(IPAddress.HostToNetworkOrder(messageSize));
                sslStreamWriter.Write(audioMessage.packet);
            }
            else
            {
                MemoryStream messageStream = new MemoryStream();
                Serializer.NonGeneric.Serialize(messageStream, message);

                Int16 messageType = (Int16)MumbleProtocolFactory.MessageType(message);
                Int32 messageSize = (Int32)messageStream.Length;

                sslStreamWriter.Write(IPAddress.HostToNetworkOrder(messageType));
                sslStreamWriter.Write(IPAddress.HostToNetworkOrder(messageSize));
                messageStream.Position = 0;
                sslStreamWriter.Write(messageStream.ToArray());
            }
            sslStreamWriter.Flush();
        }