利用反射,泛型,扩展方法快速获取表单值到实体类
Code
using System;
using System.Collections.Generic;
using System.Web;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using DotNetNuke.Common.Utilities;
namespace UCP.Library
{
public static class MehtodExtensionsUtility
{
private static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
/**//// <summary>
/// 从当前请求中提取类型T,如果不存在,则返回一个new T();
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T SerializableObject<T>(this HttpRequest source) where T:new ()
{
object objObject = Activator.CreateInstance(typeof(T));
PropertyInfo[] ps = objObject.GetType().GetProperties();
PropertyInfo objPropertyInfo = null;
Type objPropertyType = null;
object objDataValue = null;
Type objDataType = default(Type);
for (int i = 0; i < ps.Length; i++)
{
//PropertyInfo item = ps[i];
//item.SetValue(obj, string.IsNullOrEmpty(source[item.Name]) ? item.GetValue(obj, null) : source[item.Name], null);
//If the Column matches a Property in the Object Map's PropertyInfo Dictionary
if (true)
{
objPropertyInfo = ps[i];
//Get its type
objPropertyType = objPropertyInfo.PropertyType;
//If property can be set
if (objPropertyInfo.CanWrite)
{
//Get the Data Value from the data reader
if (string.IsNullOrEmpty(source[objPropertyInfo.Name]))
continue;
objDataValue =HttpUtility.HtmlEncode(source[objPropertyInfo.Name]);
//Get the Data Value's type
objDataType = objDataValue.GetType();
if (objDataValue == System.DBNull.Value)
{
// set property value to Null
objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null);
}
else if (objPropertyType.Equals(objDataType))
{
//Property and data objects are the same type
objPropertyInfo.SetValue(objObject, objDataValue, null);
}
else
{
// business object info class member data type does not match datareader member data type
try
{
//need to handle enumeration conversions differently than other base types
if (objPropertyType.BaseType.Equals(typeof(System.Enum)))
{
// check if value is numeric and if not convert to integer ( supports databases like Oracle )
if (IsNumeric(objDataValue))
{
objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, Convert.ToInt32(objDataValue)), null);
}
else
{
objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, objDataValue), null);
}
}
else if (objPropertyType.FullName.Equals("System.Guid"))
{
// guid is not a datatype common across all databases ( ie. Oracle )
objPropertyInfo.SetValue(objObject, Convert.ChangeType(new Guid(objDataValue.ToString()), objPropertyType), null);
}
else if (objPropertyType.FullName.Equals("System.Version"))
{
objPropertyInfo.SetValue(objObject, new Version(objDataValue.ToString()), null);
}
else
{
// try explicit conversion
objPropertyInfo.SetValue(objObject, objDataValue, null);
}
}
catch
{
objPropertyInfo.SetValue(objObject, Convert.ChangeType(objDataValue, objPropertyType), null);
}
}
}
}
}
return (T)objObject;
}
/**//// <summary>
/// 将当前请求中类型T序列化为XML格式,如果不存在则返回空
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static string SerializableToXml<T>(this HttpRequest source) where T : new()
{
T obj = SerializableObject<T>(source);
return obj.SerializableToXml();
//System.Text.Encoding encoding = System.Text.ASCIIEncoding.UTF8;
//XmlSerializer XMLSerializer = new XmlSerializer(obj.GetType());
//using (MemoryStream memoryStream = new MemoryStream())
//{
// XmlTextWriter XMLWriter = new XmlTextWriter(memoryStream, encoding);
// XMLSerializer.Serialize(XMLWriter, obj);
// string result = encoding.GetString(memoryStream.ToArray()).Trim();
// XMLWriter.Close();
// memoryStream.Close();
// return result;
//}
//return "";
}
/**//// <summary>
/// 将可系列化的对象序列化为XML格式字符串返回
/// 注意:
/// 如果字段的类型不是string类型,那么在转换为XML时.会自动使用此类型的默认值做为xml节点的的值.
/// 如
/// int类型使用0,
/// datetime使用0001-01-01
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializableToXml(this Object obj)
{
string result = "";
System.Text.Encoding encoding = System.Text.ASCIIEncoding.GetEncoding("GB2312");
XmlSerializer XMLSerializer = new XmlSerializer(obj.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
XmlTextWriter XMLWriter = new XmlTextWriter(memoryStream, encoding);
XMLSerializer.Serialize(XMLWriter, obj);
result = encoding.GetString(memoryStream.ToArray()).Trim();
XMLWriter.Close();
memoryStream.Close();
}
return result.Replace("encoding=\"gb2312\"", "");
}
/**//// <summary>
/// 检测当前请求来源是否来自本服务器
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static bool CheckRequstOrigin(this HttpRequest request)
{
string userIp = request.UserHostAddress;
if (userIp == "127.0.0.1" || userIp == "localhost" || userIp == "::1")
return true;
string strhostname= System.Net.Dns.GetHostName();
System.Net.IPHostEntry ip=System.Net.Dns.GetHostByName(strhostname);
foreach (System.Net.IPAddress ipA in ip.AddressList)
{
if (userIp == ipA.ToString().ToLower().Trim())
return true;
}
return false;
}
}
}
using System;
using System.Collections.Generic;
using System.Web;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using DotNetNuke.Common.Utilities;
namespace UCP.Library
{
public static class MehtodExtensionsUtility
{
private static bool IsNumeric(object Expression)
{
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
/**//// <summary>
/// 从当前请求中提取类型T,如果不存在,则返回一个new T();
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T SerializableObject<T>(this HttpRequest source) where T:new ()
{
object objObject = Activator.CreateInstance(typeof(T));
PropertyInfo[] ps = objObject.GetType().GetProperties();
PropertyInfo objPropertyInfo = null;
Type objPropertyType = null;
object objDataValue = null;
Type objDataType = default(Type);
for (int i = 0; i < ps.Length; i++)
{
//PropertyInfo item = ps[i];
//item.SetValue(obj, string.IsNullOrEmpty(source[item.Name]) ? item.GetValue(obj, null) : source[item.Name], null);
//If the Column matches a Property in the Object Map's PropertyInfo Dictionary
if (true)
{
objPropertyInfo = ps[i];
//Get its type
objPropertyType = objPropertyInfo.PropertyType;
//If property can be set
if (objPropertyInfo.CanWrite)
{
//Get the Data Value from the data reader
if (string.IsNullOrEmpty(source[objPropertyInfo.Name]))
continue;
objDataValue =HttpUtility.HtmlEncode(source[objPropertyInfo.Name]);
//Get the Data Value's type
objDataType = objDataValue.GetType();
if (objDataValue == System.DBNull.Value)
{
// set property value to Null
objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null);
}
else if (objPropertyType.Equals(objDataType))
{
//Property and data objects are the same type
objPropertyInfo.SetValue(objObject, objDataValue, null);
}
else
{
// business object info class member data type does not match datareader member data type
try
{
//need to handle enumeration conversions differently than other base types
if (objPropertyType.BaseType.Equals(typeof(System.Enum)))
{
// check if value is numeric and if not convert to integer ( supports databases like Oracle )
if (IsNumeric(objDataValue))
{
objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, Convert.ToInt32(objDataValue)), null);
}
else
{
objPropertyInfo.SetValue(objObject, System.Enum.ToObject(objPropertyType, objDataValue), null);
}
}
else if (objPropertyType.FullName.Equals("System.Guid"))
{
// guid is not a datatype common across all databases ( ie. Oracle )
objPropertyInfo.SetValue(objObject, Convert.ChangeType(new Guid(objDataValue.ToString()), objPropertyType), null);
}
else if (objPropertyType.FullName.Equals("System.Version"))
{
objPropertyInfo.SetValue(objObject, new Version(objDataValue.ToString()), null);
}
else
{
// try explicit conversion
objPropertyInfo.SetValue(objObject, objDataValue, null);
}
}
catch
{
objPropertyInfo.SetValue(objObject, Convert.ChangeType(objDataValue, objPropertyType), null);
}
}
}
}
}
return (T)objObject;
}
/**//// <summary>
/// 将当前请求中类型T序列化为XML格式,如果不存在则返回空
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static string SerializableToXml<T>(this HttpRequest source) where T : new()
{
T obj = SerializableObject<T>(source);
return obj.SerializableToXml();
//System.Text.Encoding encoding = System.Text.ASCIIEncoding.UTF8;
//XmlSerializer XMLSerializer = new XmlSerializer(obj.GetType());
//using (MemoryStream memoryStream = new MemoryStream())
//{
// XmlTextWriter XMLWriter = new XmlTextWriter(memoryStream, encoding);
// XMLSerializer.Serialize(XMLWriter, obj);
// string result = encoding.GetString(memoryStream.ToArray()).Trim();
// XMLWriter.Close();
// memoryStream.Close();
// return result;
//}
//return "";
}
/**//// <summary>
/// 将可系列化的对象序列化为XML格式字符串返回
/// 注意:
/// 如果字段的类型不是string类型,那么在转换为XML时.会自动使用此类型的默认值做为xml节点的的值.
/// 如
/// int类型使用0,
/// datetime使用0001-01-01
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializableToXml(this Object obj)
{
string result = "";
System.Text.Encoding encoding = System.Text.ASCIIEncoding.GetEncoding("GB2312");
XmlSerializer XMLSerializer = new XmlSerializer(obj.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
XmlTextWriter XMLWriter = new XmlTextWriter(memoryStream, encoding);
XMLSerializer.Serialize(XMLWriter, obj);
result = encoding.GetString(memoryStream.ToArray()).Trim();
XMLWriter.Close();
memoryStream.Close();
}
return result.Replace("encoding=\"gb2312\"", "");
}
/**//// <summary>
/// 检测当前请求来源是否来自本服务器
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static bool CheckRequstOrigin(this HttpRequest request)
{
string userIp = request.UserHostAddress;
if (userIp == "127.0.0.1" || userIp == "localhost" || userIp == "::1")
return true;
string strhostname= System.Net.Dns.GetHostName();
System.Net.IPHostEntry ip=System.Net.Dns.GetHostByName(strhostname);
foreach (System.Net.IPAddress ipA in ip.AddressList)
{
if (userIp == ipA.ToString().ToLower().Trim())
return true;
}
return false;
}
}
}