C# WebUtils

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Reflection;
using VWFC.IT.CCG.Common;
using System.Xml.Serialization;
using System.Xml;

namespace BLL.Common
{
    /// <summary>
    /// web tools
    /// </summary>
    public sealed class WebUtils
    {
        /// <summary>
        /// Get SHA512 Hash From String
        /// </summary>
        /// <param name="originalData"></param>
        /// <returns></returns>
        static public string GetHash512String(string originalData)
        {
            string result = string.Empty;
            byte[] bytValue = Encoding.UTF8.GetBytes(originalData);
            SHA512 sha512 = new SHA512CryptoServiceProvider();
            byte[] retVal = sha512.ComputeHash(bytValue);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            result = sb.ToString();
            return result;
        }

        /// <summary>
        /// Dictionary Parse To String
        /// </summary>
        /// <param name="parameters">Dictionary</param>
        /// <returns>String</returns>
        static public string ParseToString(IDictionary<string, string> parameters)
        {
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            StringBuilder query = new StringBuilder("");
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append("=").Append(value).Append("&");
                }
            }
            string content = query.ToString().Substring(0, query.Length - 1);

            return content;
        }

        /// <summary>
        /// String Parse To Dictionary
        /// </summary>
        /// <param name="parameter">String</param>
        /// <returns>Dictionary</returns>
        static public Dictionary<string, string> ParseToDictionary(string parameter)
        {
            String[] dataArry = parameter.Split('&');
            Dictionary<string, string> dataDic = new Dictionary<string, string>();
            for (int i = 0; i <= dataArry.Length - 1; i++)
            {
                String dataParm = dataArry[i];
                int dIndex = dataParm.IndexOf("=");
                if (dIndex != -1)
                {
                    String key = dataParm.Substring(0, dIndex);
                    String value = dataParm.Substring(dIndex + 1, dataParm.Length - dIndex - 1);
                    dataDic.Add(key, value);
                }
            }

            return dataDic;
        }
        
        static public string Base64Encode(string data)
        {
            string result = data;

            byte[] encData_byte = Encoding.UTF8.GetBytes(data);
            result = Convert.ToBase64String(encData_byte);

            return result;
        }
        
        static public string Base64Decode(string data)
        {
            string result = data;
            string decode = string.Empty;

            UTF8Encoding encoder = new UTF8Encoding();
            Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(data);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            result = new String(decoded_char);

            return result;
        }

        static public T DictionaryToObject<T>(Dictionary<string, string> dic) where T : new()
        {
            Type myType = typeof(T);
            T entity = new T();
            var fields = myType.GetProperties();
            string val = string.Empty;
            object obj = null;
            int i = 0;
            foreach (var field in fields)
            {
                if (!dic.ContainsKey(field.Name))
                    continue;
                val = dic[field.Name];

                object defaultVal;
                if (field.PropertyType.Name.Equals("String"))
                    defaultVal = string.Empty;
                else if (field.PropertyType.Name.Equals("Boolean"))
                {
                    defaultVal = false;
                    val = (val.Equals("1") || val.Equals("on")).ToString();
                }
                else if (field.PropertyType.Name.Equals("Decimal"))
                    defaultVal = 0M;
                else
                    defaultVal = 0;
                if (!field.PropertyType.IsGenericType)
                {
                    obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, field.PropertyType);
                }
                else
                {
                    Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable<>))
                        obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
                }

                field.SetValue(entity, obj, null);
                i++;
            }

            return entity;
        }
        
        static public string SerializeToXml<T>(T obj)
        {
            string xmlString = string.Empty;
            //XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    xmlSerializer.Serialize(ms, obj);
            //    xmlString = Encoding.UTF8.GetString(ms.ToArray());
            //}
            Encoding encoding = Encoding.UTF8;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add("", "");

                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false));

                xmlTextWriter.Formatting = Formatting.None;
                xmlSerializer.Serialize(xmlTextWriter, obj, namespaces);
                xmlTextWriter.Flush();
                xmlTextWriter.Close();

                xmlString = encoding.GetString(memoryStream.ToArray());
            }
            return xmlString;
        }

        static public T DeserializeXml<T>(string xmlString)
        {
            T t = default(T);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
            {
                using (XmlReader xmlReader = XmlReader.Create(xmlStream))
                {
                    Object obj = xmlSerializer.Deserialize(xmlReader);
                    t = (T)obj;
                }
            }
            return t;
        }

        static public string VerifyXml(string xml)
        {
            string result = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
            }
            catch (XmlException ex) { result = ex.Message; }
            return result;
        }

        static public string GetXmlNodeText(string xml, string nodeName)
        {
            string result = string.Empty;
            try
            {
                var doc = new XmlDocument();
                doc.LoadXml(xml);
                XmlNode entityName = doc.SelectSingleNode(nodeName);
                if (entityName != null)
                {
                    result = entityName.InnerText.Trim();
                }
            }
            catch { }
            return result;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值