예제 #1
0
        private void OnReceiveInventoryMessage(object sender, EventArgs args)
        {
            CommMessage compressMessage = (CommMessage)((RealtimeDataEventArgument)args).Data;
            CommMessage message         = compressMessage.ExtractZipTypeMessage();

            int pos       = 0;
            int dictCount = SerializingHelper.DecodingInt32(message.Data, ref pos);

            for (int i = 0; i < dictCount; i++)
            {
                string viaKeys = SerializingHelper.DecodingString(message.Data, ref pos);

                if (viaKeys.Contains("ATD"))
                {
                    int count = SerializingHelper.DecodingInt32(message.Data, ref pos);
                    for (int j = 0; j < count; j++)
                    {
                        string custId = SerializingHelper.DecodingString(message.Data, ref pos);
                        int    sCount = SerializingHelper.DecodingInt32(message.Data, ref pos);

                        m_clientSessionDict.TryAdd(custId, new ConcurrentDictionary <string, byte[]>());

                        for (int k = 0; k < sCount; k++)
                        {
                            string sAccount = SerializingHelper.DecodingString(message.Data, ref pos);
                            byte[] data     = SerializingHelper.DecodingByteArray(message.Data, ref pos, 16); //session la 16 byte

                            m_clientSessionDict[custId].TryAdd(sAccount, data);
                        }
                    }
                }
            }
        }
        private TOut PostSerializableT <T, TOut>(String controller, String action, String parameters, T value, bool needResponseData = true) where T : APIBaseRequest
        {
            //parameters = "/1";
            byte[] data;
            var    request = PreparePostRequest <T>(controller, action, parameters, value, out data);

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            if (needResponseData)
            {
                XmlSerializer s2 = SerializingHelper.GetSerializer(typeof(TOut));
                using (var stream = response.GetResponseStream())
                {
                    return((TOut)s2.Deserialize(stream));
                }
            }
            else
            {
                return(default(TOut));
            }
        }
예제 #3
0
 private void OnReceiveOrderMessage(object sender, EventArgs args)
 {
     //if (sender == m_authenClient)
     {
         CommMessage message = (CommMessage)((RealtimeDataEventArgument)args).Data;
         int         pos     = 1;
         switch ((OrderMessageCommand)message.Data[0])
         {
         case OrderMessageCommand.SESSIONID_UPDATE:
             string viaKeys        = SerializingHelper.DecodingString(message.Data, ref pos);
             string customerID     = SerializingHelper.DecodingString(message.Data, ref pos);
             string sessionAccount = SerializingHelper.DecodingString(message.Data, ref pos);
             byte[] sessionData    = SerializingHelper.DecodingByteArray(message.Data, ref pos, 16);
             if (viaKeys.Contains("ATD"))
             {
                 if (!m_clientSessionDict.ContainsKey(customerID))
                 {
                     m_clientSessionDict.TryAdd(customerID, new ConcurrentDictionary <string, byte[]>());
                 }
                 if (!m_clientSessionDict[customerID].ContainsKey(sessionAccount))
                 {
                     m_clientSessionDict[customerID].TryAdd(sessionAccount, sessionData);
                 }
             }
             break;
         }
     }
 }
예제 #4
0
        private object SetValue([NotNull] MemberSetter setter, [CanBeNull] object obj, [CanBeNull] object value, [NotNull] Type serializedValueType)
        {
            var acceptedType = setter.GetValueType();

            if (ReferenceEquals(value, null))
            {
                if (acceptedType.IsValueType)
                {
                    throw new InvalidCastException("Cannot cast 'null' to a value type.");
                }
            }

            // Treat enum as inline, special case of integers
            if (acceptedType.IsEnum)
            {
                if (ReferenceEquals(value, null))
                {
                    throw new ApplicationException("Not possible.");
                }

                if (SerializingHelper.IsNumericType(serializedValueType))
                {
                    var enumValue = Enum.ToObject(acceptedType, value);

                    return(setter.SetValueDirect(obj, enumValue));
                }
            }

            var converterType  = setter.Attribute?.ConverterType;
            var convertedValue = Context.Converters.TryConvertTypeOfValue(serializedValueType, acceptedType, value, converterType);

            return(setter.SetValueDirect(obj, convertedValue));
        }
        private HttpWebRequest PreparePostRequest <T>(String controller, String action, String parameters, T value, out byte[] byteData) where T : APIBaseRequest
        {
            APICompIDRequest wrapper;

            SignBytes signFunction = Interlocked.CompareExchange(ref signFunc, null, null);

            if (signFunction != null)
            {
                wrapper = new APISignedRequest(CompId)
                {
                    Request = value, Signature = signFunction(SerializingHelper.GetRequestBytes(value))
                }
            }
            ;
            else
            {
                wrapper = new APIPasswordRequest(CompId)
                {
                    Request = value, Password = (this.password ?? String.Empty)
                }
            };

            byteData = SerializingHelper.GetRequestBytes(wrapper);
            var request = GetApiRequest(controller, action, parameters);

            request.ContentType = "application/xml;charset=utf-16";
            request.Method      = "POST";
            //using (var stream = request.GetRequestStream())
            //{
            //    stream.Write(byteData, 0, byteData.Length);
            //}
            return(request);
        }
예제 #6
0
        private object ApplyObjectMembers([CanBeNull] object obj, [NotNull] Dictionary <string, object> container, [NotNull] ScriptableObjectAttribute options, [CanBeNull] INamingConvention naming, int level)
        {
            foreach (var kv in container)
            {
                if (level == 0 && FilteredNames.Contains(kv.Key))
                {
                    continue;
                }

                var setter = FindSetterByName(kv.Key, naming);

                if (!setter.IsValid)
                {
                    if (options.ThrowOnUnmatched)
                    {
                        throw new SerializationException();
                    }
                    else
                    {
                        continue;
                    }
                }

                var acceptedType = setter.GetValueType();
                var rawValue     = DeserializeValue(kv.Value, acceptedType, level);
                var rawValueType = SerializingHelper.NonNullTypeOf(rawValue);

                obj = SetValue(setter, obj, rawValue, rawValueType);
            }

            return(obj);
        }
예제 #7
0
        public ITypedSerializer GetSerializerOf([NotNull] Type type)
        {
            if (SerializingHelper.IsPrimitiveType(type))
            {
                throw new ArgumentException("Cannot obtain a serializer for primitive types.");
            }

            return(_serializers.GetValue(type, CreateTypedSerializer));
        }
        private T GetSerializableT <T>(String controller, String action, String parameters)
        {
            var             request  = GetApiRequest(controller, action, parameters);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            XmlSerializer ser = SerializingHelper.GetSerializer(typeof(T));

            using (var stream = response.GetResponseStream())
            {
                return((T)ser.Deserialize(stream));
            }
        }
예제 #9
0
        public static bool ValidateDSASignature(APIBaseRequest value, byte[] signature, byte[] publicKey)
        {
            DSAParameters algParams;

            using (MemoryStream mstr = new MemoryStream(publicKey))
            {
                BinaryFormatter fmt = new BinaryFormatter();
                try { algParams = (DSAParameters)fmt.Deserialize(mstr); }
                catch (SerializationException) { return(false); }
            }
            using (var provider = new DSACryptoServiceProvider())
            {
                try { provider.ImportParameters(algParams); }
                catch (CryptographicException) { return(false); }
                return(provider.VerifyData(SerializingHelper.GetRequestBytes(value), signature));
            }
        }
예제 #10
0
        private object DeserializeDictionary([NotNull] ObjectDictionary dictionary, [NotNull] Type typeHint, int level)
        {
            var collectionInterfaceType = typeHint.GetGenericInterfaceImplementation(typeof(IDictionary <,>));

            if (collectionInterfaceType == null)
            {
                throw new ArgumentException($"{typeHint.Name} does not implement IDictionary<TKey, TValue>.");
            }

            var genericTypes = collectionInterfaceType.GetGenericArguments();
            var keyType      = genericTypes[0];
            var valueType    = genericTypes[1];

            MethodInfo addMethod;

            try {
                addMethod = typeHint.GetMethod("Add", InternalBindings);
            } catch (AmbiguousMatchException ex) {
                throw new SerializationException("Cannot find a proper Add() method.", ex);
            }

            if (addMethod == null)
            {
                throw new SerializationException("No Add() method found.");
            }

            var result = Context.Activator.CreateInstance(typeHint, true);

            var converters = Context.Converters;

            foreach (var kv in dictionary.Dictionary)
            {
                var key          = DeserializeValue(kv.Key, keyType, level + 1);
                var convertedKey = converters.TryConvertTypeOfValue(SerializingHelper.NonNullTypeOf(key), keyType, key, null);

                var value          = DeserializeValue(kv.Value, valueType, level + 1);
                var convertedValue = converters.TryConvertTypeOfValue(SerializingHelper.NonNullTypeOf(value), valueType, value, null);

                addMethod.Invoke(result, new[] { convertedKey, convertedValue });
            }

            return(result);
        }
예제 #11
0
        public object TryConvertTypeOfValue([NotNull] Type serializedValueType, [NotNull] Type acceptedType, [CanBeNull] object value, [CanBeNull] Type converterTypeHint)
        {
            if (acceptedType.IsAssignableFrom(serializedValueType))
            {
                return(value);
            }

            var converter = FindConverter(serializedValueType, acceptedType, converterTypeHint);

            if (converter != null)
            {
                var convertedValue = SerializingHelper.ConvertValue(converter, serializedValueType, acceptedType, value);

                return(convertedValue);
            }
            else
            {
                return(value);
            }
        }
예제 #12
0
        private Array DeserializeRank1Array([NotNull] ObjectArray arr, [NotNull] Type arrayType, int level)
        {
            var elementType = arrayType.GetElementType();

            Debug.Assert(elementType != null);

            var array       = arr.Array;
            var arrayLength = array.Length;
            var result      = Array.CreateInstance(elementType, arrayLength);

            var converters = Context.Converters;

            for (var i = 0; i < arrayLength; i += 1)
            {
                var element        = DeserializeValue(array[i], elementType, level + 1);
                var convertedValue = converters.TryConvertTypeOfValue(SerializingHelper.NonNullTypeOf(element), elementType, element, null);
                result.SetValue(convertedValue, i);
            }

            return(result);
        }
예제 #13
0
        private object DeserializeCollection([NotNull] ObjectArray array, [NotNull] Type typeHint, int level)
        {
            var collectionInterfaceType = typeHint.GetGenericInterfaceImplementation(typeof(ICollection <>));

            if (collectionInterfaceType == null)
            {
                throw new ArgumentException($"{typeHint.Name} does not implement ICollection<T>.");
            }

            var genericTypes = collectionInterfaceType.GetGenericArguments();
            var elementType  = genericTypes[0];

            MethodInfo addMethod;

            try {
                addMethod = typeHint.GetMethod("Add", InternalBindings);
            } catch (AmbiguousMatchException ex) {
                throw new SerializationException("Cannot find a proper Add() method.", ex);
            }

            if (addMethod == null)
            {
                throw new SerializationException("No Add() method found.");
            }

            var result = Context.Activator.CreateInstance(typeHint, true);

            var converters = Context.Converters;

            foreach (var item in array.Array)
            {
                var element        = DeserializeValue(item, elementType, level + 1);
                var convertedValue = converters.TryConvertTypeOfValue(SerializingHelper.NonNullTypeOf(element), elementType, element, null);
                addMethod.Invoke(element, new[] { convertedValue });
            }

            return(result);
        }
        private static void EndGetPostSerializableT <T>(IAsyncResult res, bool hasResultData)
        {
#if DEBUG
            Thread.Sleep(1500);
#endif
            AsyncGetObject <T> state = (AsyncGetObject <T>)res.AsyncState;
            HttpWebResponse    response;
            try { response = (HttpWebResponse)state.Request.EndGetResponse(res); }
            catch (ObjectDisposedException)
            {
                if (state.Callback != null)
                {
                    state.Callback(default(T), RequestResult.Exit, HttpStatusCode.InternalServerError, null, state.AsyncState);
                }
                return;
            }
            catch (Exception ex)
            {
                if (state.Callback != null)
                {
                    state.Callback(default(T), RequestResult.Error, HttpStatusCode.InternalServerError, ex, state.AsyncState);
                    return;
                }
                else
                {
                    throw;
                }
            }

            T    result = default(T);
            bool scs;
            if (hasResultData)
            {
                XmlSerializer ser = SerializingHelper.GetSerializer(typeof(T));

                scs = false;
                try
                {
                    using (var stream = response.GetResponseStream())
                    {
                        result = (T)ser.Deserialize(stream);
                        scs    = true;
                    }
                }
                catch (Exception ex)
                {
                    if (state.Callback != null)
                    {
                        state.Callback(default(T), RequestResult.Error, response.StatusCode, ex, state.AsyncState);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                scs = true;
            }
            if (scs && state.Callback != null)
            {
                state.Callback(result, RequestResult.Success, response.StatusCode, null, state.AsyncState);
            }
        }