Esempio n. 1
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();
                byteStream     = _serviceSerializer.Serialize(castList);
            }
            else
            {
                byteStream = _serviceSerializer.Serialize(item);
            }

            return(new Tuple <Type, byte[]>(serializedType, byteStream));
        }
Esempio n. 2
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);
            }
        }
        /// <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);
        }