private static bool SaveStateForProperty(ISerializedObject obj, InspectedProperty property, BaseSerializer serializer, ISerializationOperator serializationOperator, out string serializedValue, ref bool success)
        {
            object currentValue = property.Read(obj);

            try {
                if (currentValue == null)
                {
                    serializedValue = null;
                }
                else
                {
                    serializedValue = serializer.Serialize(property.MemberInfo, currentValue, serializationOperator);
                }
                return(true);
            }
            catch (Exception e) {
                success         = false;
                serializedValue = null;

                Debug.LogError("Exception caught when serializing property <" +
                               property.Name + "> in <" + obj + "> with value " + currentValue + "\n" +
                               e);
                return(false);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Выполняет конвертацию из XML в аналогиченый JSON - элемент
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public JsonItem ConvertToJsonItem(XElement xml)
        {
            if (xml.Attribute("__isarray") != null)
            {
                if (xml.Attribute("__isarray").Value == "true")
                {
                    xml.SetAttributeValue(JsonItem.JsonTypeAttributeName, "array");
                }
            }

            if (null == xml.Attribute(JsonItem.JsonTypeAttributeName))
            {
                var json   = BaseSerializer.Serialize("root", xml);
                var result = Parser.Parse(json);
                foreach (var n in result.CollectAllValues())
                {
                    n.Type = JsonTokenType.Auto;
                }
                return(result);
            }
            if (IsValue(xml))
            {
                return(new JsonValue(xml));
            }
            else if (IsArray(xml))
            {
                return(ConvertToJsonArray(xml));
            }
            else if (IsObject(xml))
            {
                return(ConvertToJsonObject(xml));
            }
            return(null);
        }
        public static void Test(BaseSerializer serializer, Action<MemoryStream> logger, object value,Type type)
        {
            SerializationServices.AssemblyLoader = assemblyLoader;
            SerializationServices.InstanceFactory = factory;

            object other;
            using (var mem = new MemoryStream())
            {
                serializer.Serialize(mem,value);
                mem.Position = 0;
                logger(mem);
                mem.Position = 0;
                other = serializer.Deserialize(mem, type);
            }

            Assert.AreEqual(value,other);
        }
Exemplo n.º 4
0
        public static void Test(BaseSerializer serializer, Action <MemoryStream> logger, object value, Type type)
        {
            //TODO: Ask Pedro

            /*SerializationServices.AssemblyLoader = assemblyLoader;
             * SerializationServices.InstanceFactory = factory;*/

            object other;

            using (var mem = new MemoryStream())
            {
                serializer.Serialize(mem, value);
                mem.Position = 0;
                logger(mem);
                mem.Position = 0;
                other        = serializer.Deserialize(mem, type);
            }

            Assert.AreEqual(value, other);
        }
Exemplo n.º 5
0
        public void RunSerialize <TSymbols, TObject>(BaseSerializer <TSymbols> serializer, BaseTest <TObject> test)
        {
            object result = null;

            var dataRow = results.Rows.Cast <DataRow>().First(dataRow => Equals(dataRow[TestName], test.TestName) && Equals(dataRow[MethodName], SerValue));

            Dispatcher.InvokeAsync(() =>
            {
                dataRow[serializer.Name] = RuningValue;
            });

            try
            {
                TObject  obj     = default;
                TSymbols symbols = default;

                double ns = default;

                var isTimeout = !Task.Run(() =>
                {
                    obj     = test.GetObject();
                    symbols = serializer.Serialize(obj);

                    var stopwatch = Stopwatch.StartNew();

                    serializer.Serialize(obj);

                    ns = stopwatch.ElapsedNanoseconds();
                }).Wait(MillisecondsTimeout);

                if (isTimeout)
                {
                    throw new TimeoutException();
                }

                long   count = 0;
                double total = 0;
                double min   = double.MaxValue;
                double max   = double.MinValue;

                for (int i = 0; i < 10; i++)
                {
                    Run(1);

                    Run((int)(10 / GetAvg()));
                    Run((int)(100 / GetAvg()));
                    Run((int)(1000 / GetAvg()));
                    Run((int)(10000 / GetAvg()));
                    Run((int)(100000 / GetAvg()));
                    Run((int)(1000000 / GetAvg()));
                    Run((int)(10000000 / GetAvg()));
                    Run((int)(100000000 / GetAvg()));
                    Run((int)(500000000 / GetAvg()));
                }

                double GetAvg()
                {
                    return(total / count);
                }

                void Run(int times)
                {
                    if (!(times > 0))
                    {
                        return;
                    }

                    TSymbols tSym = default;

                    var stopwatch = Stopwatch.StartNew();

                    for (int i = 0; i < times; i++)
                    {
                        tSym = serializer.Serialize(obj);
                    }

                    var ns = stopwatch.ElapsedNanoseconds();

                    total += ns;
                    count += times;

                    min = Math.Min(min, ns / times);
                    max = Math.Max(min, ns / times);

                    var tObj = serializer.Deserialize <TObject>(tSym);

                    if (!test.Equals(tObj, obj))
                    {
                        throw new IncorrectException();
                    }
                }

                result = new Result(GetAvg());
            }
            catch (Exception e)
            {
                result = new ExceptionResult(e);
            }
            finally
            {
                Dispatcher.InvokeAsync(() =>
                {
                    dataRow[serializer.Name] = result;
                });
            }
        }
Exemplo n.º 6
0
        //private readonly IEnumerable<BaseSerializer> _serializations;

        //public Serializer(IEnumerable<BaseSerializer> serializations)
        //{
        //    _serializations = serializations;
        //}

        public string Serialize()
        {
            return(_serializerType.Serialize());
            //throw new NotImplementedException();
        }
Exemplo n.º 7
0
 protected void RejectWithPayload <T>(SessionRequest request, T payload) where T : IDisconnectPayload
 {
     request.Reject(_serializer.Serialize(payload, null).To());
 }
Exemplo n.º 8
0
        public async Task DispatchAsync(Session session)
        {
            while (session.HasAvailableData)
            {
                var rawMessage = await session.ReceiveMessageAsync();

                var type = _serializer.ReadMessageType(rawMessage);
                switch (type)
                {
                case TypeMessage.Response:
                    if (_responseReceiver == null)
                    {
                        throw new Exception("Don't subscribed receive event");
                    }
                    _responseReceiver.Receive(_serializer.Deserialize <TResponse>(rawMessage, session));
                    continue;

                case TypeMessage.Request:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                var request     = _serializer.Deserialize <TRequest>(rawMessage, session);
                var description = Model.GetDescriptionBy(request.OperationCode);
                var context     = new RequestContext <TRequest>(request, session, description, _descriptionRuntimeModel.GetByOperation(description.OperationType));
                try
                {
                    if (GlobalRequestFilter != null)
                    {
                        var response = await GlobalRequestFilter.Handle(context);

                        response.Id   = request.Id;
                        response.Type = TypeMessage.Response;
                        if (response.Status != BuiltInOperationState.Success)
                        {
                            await session.SendMessageAsync(_serializer.Serialize(response, session).To(), description.ForResponse);

                            continue;
                        }
                    }

                    if (IsContinue(request))
                    {
                        continue;
                    }


                    var rawResponse = await ProcessHandler(request, context, CreateCancellationToken(request, description));

                    if (description.WaitResponse)
                    {
                        await SendAsync(session, rawResponse, request, description.ForResponse);
                    }
                }
                catch (OperationCanceledException e) { Logger.LogInformation("Operation canceled: {request}, {exception}", request, e); }
                catch (Exception e)
                {
                    try
                    {
                        Logger.LogError("Handle error : {exception}", e);
                    }
                    finally
                    {
                        var failOp = new TResponse()
                        {
                            Id            = request.Id,
                            Type          = TypeMessage.Response,
                            OperationCode = request.OperationCode,
                            Status        = BuiltInOperationState.InternalError,
                            OperationData = DebugMode ? _serializer.Serialize(e.Message, session) : null
                        };
                        await session.SendMessageAsync(_serializer.Serialize(failOp, session).To(), MinRequiredDeliveryMode.ReliableWithOrdered);
                    }
                }
                finally
                {
                    RemoveCancellationSource(request);
                }
            }
        }