/// <summary>
        /// 尝试根据方法的修饰属性来构造IActionResult实例
        /// </summary>
        /// <param name="result">Action的执行结果</param>
        /// <param name="actionAttr">Action方法上的ActionAttribute实例</param>
        /// <returns></returns>
        private IActionResult ObjectToResult(object result, ActionAttribute actionAttr)
        {
            IActionResult   actionResult = null;
            SerializeFormat format       = actionAttr.OutFormat;

            // 先判断是不是由客户端指定的自动模式,如果是就解析客户端需要的序列化格式
            if (format == SerializeFormat.Auto)
            {
                // 如果是自动响应,那么就根据请求头的指定的方式来决定
                string expectFormat = this.HttpContext.Request.Headers["X-Result-Format"];

                if (string.IsNullOrEmpty(expectFormat) == false)
                {
                    SerializeFormat outFormat;
                    if (Enum.TryParse <SerializeFormat>(expectFormat, true, out outFormat))
                    {
                        format = outFormat;
                    }
                }
            }


            // 根据已指定的序列化格式包装具体的IActionResult实例

            if (format == SerializeFormat.Json)
            {
                actionResult = new JsonResult(result);
            }

            else if (format == SerializeFormat.Json2)
            {
                actionResult = new JsonResult(result, true);
            }

            else if (format == SerializeFormat.Xml)
            {
                actionResult = new XmlResult(result);
            }

            else if (format == SerializeFormat.Text)
            {
                actionResult = new TextResult(result);
            }

            else if (format == SerializeFormat.Form)
            {
                string text = FormDataCollection.Create(result).ToString();
                actionResult = new TextResult(text);
            }


            // 无法构造出IActionResult实例,就交给ActionProcessor来处理
            if (actionResult == null)
            {
                ActionHelper actionProcessor = ObjectFactory.New <ActionHelper>();
                actionResult = actionProcessor.ObjectToResult(result);
            }

            return(actionResult);
        }
        /// <summary>
        /// 从请求流中反序列化构造参数值
        /// </summary>
        /// <param name="p"></param>
        /// <param name="requst"></param>
        /// <returns></returns>
        public virtual object FromBodyDeserializeObject(ParameterInfo p, HttpRequest requst)
        {
            // 从请求流中反序列化对象中,要注意三点:
            // 1、忽略参数的名称
            // 2、直接使用参数类型,不做可空类型处理
            // 3、仅支持 JSON, XML 的数据格式

            SerializeFormat format = RequestContentType.GetFormat(requst.ContentType);

            if (format == SerializeFormat.Json)
            {
                string text = requst.GetPostText();
                return(JsonExtensions.FromJson(text, p.ParameterType));
            }

            if (format == SerializeFormat.Xml)
            {
                string text = requst.GetPostText();
                return(XmlExtensions.FromXml(text, p.ParameterType));
            }

            // 仅仅是需要读取整个请求流字符串,
            // 而且目标类型已经是字符串,就没有必要反序列化了,所以就直接以字符串返回
            if (p.ParameterType == typeof(string))
            {
                return(requst.GetPostText());
            }

            throw new NotSupportedException("[FromBody]标记只能配合 JSON/XML 数据格式来使用。");
        }
Example #3
0
        public void SerializeTest(SerializeFormat format)
        {
            var    engine = new NodeEngine();
            string stream = null;

            engine.GetOrCreateNode("Node1")
            .SetColor(Colors.Coral)
            .SetPos(150, 200);

            engine.GetOrCreateNode("Node2");

            engine.Connect("Node1", "Node2");

            stream = engine.Serialize(format);

            var engine2 = new NodeEngine();

            engine2.Deserialize(stream, format);

            Assert.Equal(engine.Network.Nodes[0].Guid, engine2.Network.Nodes[0].Guid);
            Assert.Equal(engine.Network.Nodes[0].Y, engine2.Network.Nodes[0].Y);
            Assert.Equal(engine.Network.Nodes[0].HeaderColor, engine2.Network.Nodes[0].HeaderColor);

            Assert.Equal(engine.Network.Nodes.Count, engine2.Network.Nodes.Count);
            Assert.Equal(engine.Network.Connections.Count, engine2.Network.Connections.Count);
            Assert.Equal(engine.Network.Nodes.SelectMany(x => x.InputPlugs).Count(), engine2.Network.Nodes.SelectMany(x => x.InputPlugs).Count());
            Assert.Equal(engine.Network.Nodes.SelectMany(x => x.OutputPlugs).Count(), engine2.Network.Nodes.SelectMany(x => x.OutputPlugs).Count());
        }
Example #4
0
        private void Write(Stream stream, object data, SerializeFormat format)
        {
            switch (format)
            {
            case SerializeFormat.Text:
                WriteAsTextFormat(stream, data);
                break;

            case SerializeFormat.Json:
                WriteAsJsonFormat(stream, data);
                break;

            case SerializeFormat.Json2:
                WriteAsJson2Format(stream, data);
                break;

            case SerializeFormat.Xml:
                WriteAsXmlFormat(stream, data);
                break;

            case SerializeFormat.Form:
                WriteAsFormFormat(stream, data);
                break;

            case SerializeFormat.Auto:
            case SerializeFormat.None:
                WriteAsAutoFormat(stream, data);
                break;

            default:
                throw new NotSupportedException();
            }
        }
Example #5
0
        private void Write(Stream stream, object data, SerializeFormat format)
        {
            switch (format)
            {
            case SerializeFormat.Text:
                WriteAsTextFormat(stream, data);
                break;

            case SerializeFormat.Json:
                WriteAsJsonFormat(stream, data);
                break;

            case SerializeFormat.Json2:
                WriteAsJson2Format(stream, data);
                break;

            case SerializeFormat.Xml:
                WriteAsXmlFormat(stream, data);
                break;

            case SerializeFormat.Form:
                WriteAsFormFormat(stream, data);
                break;

            default:
                WriteAsUnknownFormat(stream, data);
                break;
            }
        }
 public static string Serialize <T>(T data, SerializeFormat format)
 {
     return(format switch
     {
         SerializeFormat.XML => SerializeToXml(data),
         SerializeFormat.JSON => SerializeToJson(data),
         _ => string.Empty,
     });
Example #7
0
 /// <summary>
 /// 根据指定的URL以及提交数据,用【同步】方式发起一次HTTP请求
 /// </summary>
 /// <typeparam name="T">返回值的类型参数</typeparam>
 /// <param name="url">要访问的URL地址</param>
 /// <param name="data">要提交的数据对象</param>
 /// <param name="format">数据对象在传输过程中采用的序列化方式</param>
 /// <returns>返回服务端的调用结果,并转换成指定的类型</returns>
 public async static Task <T> SendAsync <T>(string url,
                                            object data            = null,
                                            SerializeFormat format = SerializeFormat.Form)
 {
     return(await new HttpOption {
         Url = url,
         Data = data,
         Format = format
     }.SendAsync <T>());
 }
Example #8
0
 /// <summary>
 /// 根据指定的URL以及提交数据,用【同步】方式发起一次HTTP请求
 /// </summary>
 /// <typeparam name="T">返回值的类型参数</typeparam>
 /// <param name="url">要访问的URL地址</param>
 /// <param name="data">要提交的数据对象</param>
 /// <param name="format">数据对象在传输过程中采用的序列化方式</param>
 /// <returns>返回服务端的调用结果,并转换成指定的类型</returns>
 public static T Send <T>(string url,
                          object data            = null,
                          SerializeFormat format = SerializeFormat.Form)
 {
     return(new HttpOption {
         Url = url,
         Data = data,
         Format = format
     }.Send <T>());
 }
Example #9
0
        private static SerializerStream CreateSerializer(SerializeFormat format, IEnumerable <Type> knownTypes)
        {
            switch (format)
            {
            default:
            case SerializeFormat.Xml: return(new DataContract.SerializerStreamXml(knownTypes: knownTypes));

            case SerializeFormat.Json: return(new DataContract.SerializerStreamJson(knownTypes));
            }
        }
Example #10
0
        /// <summary>
        /// 根据指定的URL以及提交数据,用【同步】方式发起一次HTTP请求
        /// </summary>
        /// <typeparam name="T">返回值的类型参数</typeparam>
        /// <param name="url">要访问的URL地址</param>
        /// <param name="obj">要提交的数据对象</param>
        /// <param name="format">数据对象在传输过程中采用的序列化方式</param>
        /// <returns>返回服务端的调用结果,并转换成指定的类型</returns>
        public async static Task <T> SendAsync <T>(string url, object obj = null, SerializeFormat format = SerializeFormat.FORM)
        {
            HttpOption option = new HttpOption {
                Url    = url,
                Data   = obj,
                Format = format
            };

            using (HttpClient client = ObjectFactory.New <HttpClient>()) {
                return(await client.GetResultAsync <T>(option));
            }
        }
Example #11
0
        /// <summary>
        /// 设置要提交的数据(以异步方式)
        /// </summary>
        /// <param name="data"></param>
        /// <param name="format"></param>
        public async Task SetRequestDataAsync(object data, SerializeFormat format)
        {
            if (data == null)
            {
                return;
            }

            _beforeArgs.Data   = data;
            _beforeArgs.Format = format;

            RequestWriter writer = new RequestWriter(Request);
            await writer.WriteAsync(data, format);
        }
Example #12
0
        /// <summary>
        /// 根据指定的URL以及提交数据,用【同步】方式发起一次HTTP请求
        /// </summary>
        /// <typeparam name="T">返回值的类型参数</typeparam>
        /// <param name="url">要访问的URL地址</param>
        /// <param name="data">要提交的数据对象</param>
        /// <param name="format">数据对象在传输过程中采用的序列化方式</param>
        /// <returns>返回服务端的调用结果,并转换成指定的类型</returns>
        public async static Task <T> SendAsync <T>(string url,
                                                   object data            = null,
                                                   SerializeFormat format = SerializeFormat.Form)
        {
            HttpClient client = ObjectFactory.New <HttpClient>();

            client.CreateWebRequest(url);
            await client.SetRequestDataAsync(data, format);

            using (HttpWebResponse response = await client.GetResponseAsync()) {
                return(client.GetResult <T>(response));
            }
        }
Example #13
0
        /// <summary>
        /// 设置要提交的数据
        /// </summary>
        /// <param name="data"></param>
        /// <param name="format"></param>
        public void SetRequestData(object data, SerializeFormat format)
        {
            if (data == null)
            {
                return;
            }

            _beforeArgs.Data   = data;
            _beforeArgs.Format = format;

            RequestWriter writer = new RequestWriter(Request);

            writer.Write(data, format);
        }
Example #14
0
        /// <summary>
        /// 尝试根据方法的修饰属性来构造IActionResult实例
        /// </summary>
        /// <param name="result"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        private IActionResult ObjectToActionResult(object result, SerializeFormat format)
        {
            IActionResult actionResult = null;

            if (format == SerializeFormat.AUTO)
            {
                // 如果是自动响应,那么就根据请求头的指定的方式来决定
                string expectFormat = this.HttpContext.Request.Headers["Result-Format"];

                if (string.IsNullOrEmpty(expectFormat) == false)
                {
                    SerializeFormat f2;
                    if (Enum.TryParse <SerializeFormat>(expectFormat.ToUpper(), out f2))
                    {
                        format = f2;
                    }
                }
            }


            if (format == SerializeFormat.JSON)
            {
                actionResult = new JsonResult(result);
            }

            else if (format == SerializeFormat.JSON2)
            {
                actionResult = new JsonResult(result, true);
            }

            else if (format == SerializeFormat.XML)
            {
                actionResult = new XmlResult(result);
            }

            else if (format == SerializeFormat.FORM)
            {
                string text = FormDataProvider.Serialize(result).ToString();
                actionResult = new TextResult(text);
            }


            // 无法构造出IActionResult实例,就按字符串形式输出
            if (actionResult == null)
            {
                actionResult = new TextResult(result);
            }

            return(actionResult);
        }
Example #15
0
        private Tuple <string, string> WriteStream(object data, SerializeFormat format)
        {
            HttpWebRequest request = WebRequest.CreateHttp("http://www.bing.com");
            RequestWriter  writer  = new RequestWriter(request);

            using (MemoryStream ms = new MemoryStream()) {
                _writeMethod.Invoke(writer, new object[] { ms, data, format });

                ms.Position = 0;

                return(new Tuple <string, string>(
                           request.ContentType,
                           Encoding.UTF8.GetString(ms.ToArray())
                           ));
            }
        }
Example #16
0
        /// <summary>
        /// Method to select a serialization.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t">Generic class of the type to be serialized</param>
        /// <param name="format">Enum of selected serialization method</param>
        /// <param name="filePath">File path to save/read file to/from</param>
        /// <returns></returns>
        public static bool Serialize <T>(T t, SerializeFormat format, string filePath)
        {
            switch (format)
            {
            case SerializeFormat.Bin:
                return(SerializeToBin(t, filePath));

            case SerializeFormat.XML:
                return(SerializeToXml(t, filePath));

            case SerializeFormat.TXT:
                return(SerializeToTxt(t, filePath));

            default:
                return(false);
            }
        }
        /// <summary>
        /// 根据SerializeFormat枚举转换成 Content-Type 请求头字符串,
        /// 对于无效的枚举,返回空字符串“”
        /// </summary>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string GetByFormat(SerializeFormat format)
        {
            switch (format)
            {
            case SerializeFormat.Form:
                return(RequestContentType.Form);

            case SerializeFormat.Json:
                return(RequestContentType.Json);

            case SerializeFormat.Xml:
                return(RequestContentType.Xml);

            default:
                return(string.Empty);
            }
        }
Example #18
0
        /// <summary>
        /// Generic method to select a deserialization method..
        /// </summary>
        /// <typeparam name="T">The Generic type of the deserialized data.</typeparam>
        /// <param name="data">The path (and name) of the file containing data to be deserialized.</param>
        /// <param name="format">type of deserialization</param>
        /// <returns></returns>
        public static T Deserialize <T>(string data, SerializeFormat format)
        {
            switch (format)
            {
            case SerializeFormat.Bin:
                return(DeserializeBin <T>(data, out string errorMessage));

            case SerializeFormat.XML:
                return(DeserializeXml <T>(data));

            case SerializeFormat.TXT:
                return(DeserializeTXT <T>(data));

            default:
                return(default(T));
            }
        }
Example #19
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="config"></param>
        public void Init(WriterSection config)
        {
            // 避免重复调用
            if (s_url != null)
            {
                return;
            }


            string url = config.GetOptionValue("url");

            if (string.IsNullOrEmpty(url))
            {
                throw new LogConfigException("日志配置文件中,没有为HttpWriter指定url属性。");
            }

            string format = config.GetOptionValue("format");

            if (string.IsNullOrEmpty(format))
            {
                s_format = SerializeFormat.Xml;     // 默认值
            }
            else
            {
                if (Enum.TryParse <SerializeFormat>(format, out s_format) == false ||
                    s_format == SerializeFormat.None ||
                    s_format == SerializeFormat.Auto
                    )
                {
                    throw new LogConfigException("日志配置文件中,为HttpWriter指定的format属性无效,建议选择:Json or Xml");
                }
            }

            s_retryCount           = config.GetOptionValue("retry-count").TryToUInt(10);
            s_retryWaitMillisecond = config.GetOptionValue("retry-wait-millisecond").TryToUInt(1000);
            s_datatypeInHeader     = config.GetOptionValue("datatype-in-header").TryToBool(true);

            List <NameValue> queryString = ReadHttpArgs(config, "querystring:");

            s_header = ReadHttpArgs(config, "header:");

            s_url    = url.ConcatQueryStringArgs(queryString);
            s_client = new HttpWriterClient();
        }
Example #20
0
        /// <summary>
        /// NetworkModelをストリームから構築します。
        /// </summary>
        public void Deserialize(string stream, SerializeFormat format)
        {
            if (format == SerializeFormat.Xml)
            {
                var xmlSerializer = new XmlSerializer(typeof(Network));
                using (var stringReader = new StringReader(stream))
                {
                    Network = (Network)xmlSerializer.Deserialize(stringReader);
                }
            }
#if NETCOREAPP3_1
            else if (format == SerializeFormat.Json)
            {
                var option = new JsonSerializerOptions();
                option.Converters.Add(new JsonStringEnumConverter());
                Network = JsonSerializer.Deserialize <Network>(stream, option);
            }
#endif
            Network.Deserialized();
            NodeMap.Clear();
        }
Example #21
0
        /// <summary>
        /// NetworkModelをシリアライズします。
        /// </summary>
        /// <param name="serializeType"></param>
        /// <returns></returns>
        public string Serialize(SerializeFormat serializeType)
        {
            Network.PreSerialize();
            if (serializeType == SerializeFormat.Xml)
            {
                var xmlSerializer = new XmlSerializer(typeof(Network));
                using (var streamWriter = new StringWriter())
                {
                    xmlSerializer.Serialize(streamWriter, Network);
                    return(streamWriter.ToString());
                }
            }
#if NETCOREAPP3_1
            else if (serializeType == SerializeFormat.Json)
            {
                var options = new JsonSerializerOptions();
                options.WriteIndented = true;
                return(JsonSerializer.Serialize(Network, options));
            }
#endif
            return(string.Empty);
        }
Example #22
0
        public virtual void Init(WriterSection config)
        {
            string url = config.GetOptionValue("url");

            if (string.IsNullOrEmpty(url))
            {
                throw new LogConfigException("日志配置文件中,没有为HttpWriter指定url参数。");
            }

            string format = config.GetOptionValue("format");

            _format = (string.IsNullOrEmpty(format) || format.Is("json")) ? SerializeFormat.Json : SerializeFormat.Xml;


            _retryCount           = config.GetOptionValue("retry-count").TryToUInt(10);
            _retryWaitMillisecond = config.GetOptionValue("retry-wait-millisecond").TryToUInt(1000);

            _header = ReadHttpArgs(config, "header:");

            List <NameValue> queryString = ReadHttpArgs(config, "querystring:");

            _url = url.ConcatQueryStringArgs(queryString);
        }
Example #23
0
        public void Save(string path, SerializeFormat serializeFormat)
        {
            Stream s = File.Open(path, FileMode.Create);

            switch (serializeFormat)
            {
            case SerializeFormat.Binary:
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(s, this);
                break;

            case SerializeFormat.Soap:
                SoapFormatter binFormat = new SoapFormatter();
                binFormat.Serialize(s, this);
                break;

            case SerializeFormat.Xml:
                XmlSerializer xmlFormat = new XmlSerializer(typeof(CoolImage));
                xmlFormat.Serialize(s, this);
                break;
            }
            s.Close();
        }
Example #24
0
        public void Read(string path)
        {
            SerializeFormat serializeFormat = getFormat(path);

            using (Stream s = File.Open(path, FileMode.Open))
            {
                CoolImage cl = this;
                switch (serializeFormat)
                {
                case SerializeFormat.Binary:

                    BinaryFormatter bf = new BinaryFormatter();
                    cl = bf.Deserialize(s) as CoolImage;
                    break;

                case SerializeFormat.Soap:
                    SoapFormatter soapFormat = new SoapFormatter();
                    cl = soapFormat.Deserialize(s) as CoolImage;
                    break;

                case SerializeFormat.Xml:
                    XmlSerializer xmlFormat = new XmlSerializer(typeof(CoolImage));
                    cl = xmlFormat.Deserialize(s) as CoolImage;
                    break;

                case SerializeFormat.Png:
                    //  using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    //  Bitmap a = new Bitmap(fs);
                    cl = new CoolImage(new Bitmap(s));
                }
                break;
                }
                this.img      = cl.img;
                this.pixelArr = cl.pixelArr;
            }
        }
Example #25
0
 public static extern int hb_buffer_serialize_glyphs(IntPtr buffer, int start, int end, IntPtr buf, int buf_size, out int buf_consumed, IntPtr font, SerializeFormat format, SerializeFlag flags);
Example #26
0
 public static extern bool hb_buffer_deserialize_glyphs(IntPtr buffer, [MarshalAs(UnmanagedType.LPStr)] string buf, int buf_len, out IntPtr end_ptr, IntPtr font, SerializeFormat format);
Example #27
0
 public Serializer(string fileName, string directoryPath, SerializeFormat format = SerializeFormat.Binary)
 {
     FileName      = fileName;
     DirectoryPath = directoryPath;
     Format        = format;
 }
Example #28
0
 public Serializer(string fileName, SerializeFormat format = SerializeFormat.Binary)
 {
     FileName = fileName;
     Format   = format;
 }
Example #29
0
 //Classe permettant de (dé)serialiser un objet dans l'un des formats json,xml ou binaire
 public Serializer(SerializeFormat format = SerializeFormat.Binary)
 {
     Format = format;
 }
		/// <summary>
		/// 尝试根据方法的修饰属性来构造IActionResult实例
		/// </summary>
		/// <param name="result"></param>
		/// <param name="format"></param>
		/// <returns></returns>
		private IActionResult ObjectToActionResult(object result, SerializeFormat format)
		{
			IActionResult actionResult = null;

			if( format == SerializeFormat.AUTO ) {
				// 如果是自动响应,那么就根据请求头的指定的方式来决定
				string expectFormat = this.HttpContext.Request.Headers["Result-Format"];

				if( string.IsNullOrEmpty(expectFormat) == false ) {
					SerializeFormat f2;
					if( Enum.TryParse<SerializeFormat>(expectFormat.ToUpper(), out f2) )
						format = f2;
				}
			}


			if( format == SerializeFormat.JSON )
				actionResult = new JsonResult(result);

			else if( format == SerializeFormat.JSON2 )
				actionResult = new JsonResult(result, true);

			else if( format == SerializeFormat.XML )
				actionResult = new XmlResult(result);

			else if( format == SerializeFormat.FORM ) {
				string text = FormDataProvider.Serialize(result).ToString();
				actionResult = new TextResult(text);
			}


			// 无法构造出IActionResult实例,就按字符串形式输出
			if( actionResult == null )
				actionResult = new TextResult(result);

			return actionResult;
		}
Example #31
0
 public Serializer(SerializeFormat format = SerializeFormat.Json, IEnumerable <Type> knownTypes = null)
 {
     this.Format           = format;
     this.SerializerStream = CreateSerializer(format, knownTypes);
 }