/// <summary>
        /// The serialization strategy tries to serialize the type with the first serializer and if
        /// it fails it uses the next one.
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        private static IServiceSerializer CreateSerializationStrategy(SerializationOption option)
        {
            IServiceSerializer serviceSerializer = null;

            switch (option)
            {
            case SerializationOption.JsonSerializer:
                serviceSerializer = new JsonSerializer()
                {
                    Next = new BinarySerializer()
                };
                break;

            case SerializationOption.BinarySerializer:
                serviceSerializer = new BinarySerializer()
                {
                    Next = new JsonSerializer()
                };
                break;

            case SerializationOption.XmlSerializer:
                serviceSerializer = new XmlSerializer()
                {
                    Next = new JsonSerializer()
                };
                break;
            }
            Log.Write("CreateSerializationStrategy - SerializationOption is valid : {0}", option);

            return(serviceSerializer);
        }
示例#2
0
        public Tuple <Type, byte[]> Grab <T>(T item)
        {
            Type @type = item.GetType();

            byte[] byteStream     = { };
            Type   serializedType = @type;

            if (@type.IsNestedPrivate && @type.Name.Contains("Iterator") &&
                @type.FullName.Contains("System.Linq.Enumerable") && item is IEnumerable)
            {
                MethodInfo toList   = typeof(Enumerable).GetMethod("ToList");
                Type       baseType = item.GetType().BaseType;
                if (baseType == null)
                {
                    return(new Tuple <Type, byte[]>(serializedType, byteStream));
                }

                MethodInfo constructedToList = toList.MakeGenericMethod(baseType.GetGenericArguments()[0]);
                object     castList          = constructedToList.Invoke(null, new object[] { item });

                serializedType = castList.GetType();
                IServiceSerializer serviceSerializer = FactorySerializer.CreateServiceSerializer(serializedType);
                byteStream = serviceSerializer.Serialize(castList);
            }
            else
            {
                IServiceSerializer serviceSerializer = FactorySerializer.CreateServiceSerializer(serializedType);

                byteStream = serviceSerializer.Serialize(item);
            }

            return(new Tuple <Type, byte[]>(serializedType, byteStream));
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item">The object to serialize</param>
        /// <param name="truckId">the unique id used to save the serialize item to disk</param>
        /// <param name="serializationOption"> the proposed serialization strategy</param>
        /// <returns>Returns the actual serialization strategy used to serialize the <paramref name="item"/> </returns>
        public static SerializationOption?SendCargo <T>(T item, string truckId, SerializationOption serializationOption)
        {
            byte[] byteStream = null;

Try:
            IServiceSerializer serializer = CreateSerializationStrategy(serializationOption);

            Log.Write($"SendCargo - Type {typeof(T).FullName} - Serialization strategy: {serializer}");

            do
            {
                try
                {
                    byteStream = serializer.Serialize(item);
                }
                catch (ThreadAbortException tae)
                {
                    Thread.ResetAbort();
                    Log.Write(tae, "SendCargo - Thread Exception.");
                    goto Try;
                }
                catch (Exception e)
                {
                    Log.Write(e, "SendCargo - Error During serializing cargo");
                    serializer = serializer.Next;
                }
            }while (byteStream == null || byteStream.Length == 0 && serializer != null);

            if (byteStream.Length > 0)
            {
                string filePath = Path.Combine(Path.GetTempPath(), truckId);
                File.WriteAllBytes(filePath, byteStream);
                if (serializer == null)
                {
                    return(null);
                }

                SerializationOption successfulSerialization = (SerializationOption)Enum.Parse(typeof(SerializationOption), serializer.ToString());
                Log.Write($"SendCargo - Cargo Sent - Byte sent: {byteStream.Length} - File Created: {filePath} - Serialization Used: {successfulSerialization}");

                return(successfulSerialization);
            }

            Log.Write($"SendCargo - It was not possible to serialize at all the type {typeof(T).FullName}");


            return(null);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T ReceiveCargo <T>(string truckId, SerializationOption serializationOption)
        {
            Log.Write("ReceiveCargo - Receiving Cargo of Type {0}", typeof(T).FullName);

            try
            {
                byte[]             byteStream        = File.ReadAllBytes(Path.Combine(FileSystemFactory.FileSystem.Path.GetTempPath(), truckId));
                IServiceSerializer serviceSerializer = CreateDeserializationStrategy(serializationOption);
                return(serviceSerializer != null?serviceSerializer.Deserialize <T>(byteStream) : default(T));
            }
            catch (Exception e)
            {
                Log.Write(e, $"ReceiveCargo - Error while deserializing type {typeof(T).FullName}");
                throw;
            }
        }
        public static object ReceiveCargo(string truckId, SerializationOption serializationOption, Type type)
        {
            Log.Write("ReceiveCargo - UnLoading Cargo for Typeless object");
            try
            {
                byte[] byteStream = File.ReadAllBytes(Path.Combine(FileSystemFactory.FileSystem.Path.GetTempPath(), truckId));

                IServiceSerializer serviceSerializer = CreateDeserializationStrategy(serializationOption);

                return(serviceSerializer?.Deserialize(byteStream, type));
            }
            catch (Exception e)
            {
                Log.Write(e, "ReceiveCargo - Error while deserializing");
                throw;
            }
        }
示例#6
0
        public object Release(byte[] item, Type type)
        {
            IServiceSerializer serviceSerializer = FactorySerializer.CreateServiceSerializer(type);

            return(serviceSerializer.Deserialize(item, type));
        }
示例#7
0
        public T Release <T>(byte[] item)
        {
            IServiceSerializer serviceSerializer = FactorySerializer.CreateServiceSerializer(typeof(T));

            return(serviceSerializer.Deserialize <T>(item));
        }
示例#8
0
        public async Task <Resp> Call <Req, Resp>(string uri, Req request, int timeoutInMs, IServiceSerializer serializer)
        {
            using (var client = new HttpClient())
            {
                logger.Debug($"http request : {JsonConvert.SerializeObject(request, Formatting.None)}");
                var sw = new Stopwatch();
                sw.Start();

                // 设置超时时间
                var timeout = GetTimeout(timeoutInMs);
                logger.Debug($"Http client : {uri}, timeout : {timeout}");
                client.Timeout = new TimeSpan(0, 0, 0, timeout);

                ByteArrayContent content = new ByteArrayContent(serializer.Serialize <Req>(request));
                var response             = await client.PostAsync(uri, content);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new FrameworkException(ErrorCode.InvalidHttpResponse,
                                                 $"Access {uri} failed, responsed code : {response.StatusCode}");
                }

                var buffer = await response.Content.ReadAsByteArrayAsync();

                var resp = serializer.Deserialize <Resp>(buffer);
                logger.Debug($"Total elapsed : {sw.Elapsed.TotalSeconds.ToString("0.000")}s, " +
                             $"response : {Environment.NewLine}{JsonConvert.SerializeObject(resp, Formatting.None)}");

                return(resp);
            }
        }
示例#9
0
 public BinaryGrapple(IServiceSerializer serviceSerializer)
 {
     _serviceSerializer = serviceSerializer;
 }