框架公用方法

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Arise.Common
{
    public class Utility
    {

        public static int ConvertToInt32(string num)
        {
            try
            {
                return Convert.ToInt32(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
        public static int ConvertToInt32(Object obj)
        {
            try
            {
                return Convert.ToInt32(obj.ToString());
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static short ConvertToShort(string num)
        {
            try
            {
                return short.Parse(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static decimal ConvertToDecimal(string num)
        {
            try
            {
                return Convert.ToDecimal(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }
        public static decimal ConvertToDecimal(decimal? num)
        {
            try
            {
                return Convert.ToDecimal(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }
        public static decimal ConvertToDecimal(Object obj)
        {
            try
            {
                return Convert.ToDecimal(obj.ToString());
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static double ConvertToDouble(decimal num)
        {
            try
            {
                return Convert.ToDouble(num);
            }
            catch (Exception)
            {
                return 0;
            }
        }
        public static double ConvertToDouble(Object obj)
        {
            try
            {
                return Convert.ToDouble(obj);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static DateTime ConvertToDatetime(string value)
        {
            try
            {
                return Convert.ToDateTime(value);
            }
            catch (Exception)
            {
                return DateTime.Now;
            }
        }

        public static DateTime ConvertToDatetime(object value)
        {
            try
            {
                return Convert.ToDateTime(value.ToString());
            }
            catch (Exception)
            {
                return DateTime.Now;
            }
        }

        public static DateTime GetCurrentDateTime(double GMT)
        {
            try
            {
                return DateTime.Now.ToUniversalTime().AddHours(GMT);
            }
            catch (Exception)
            {
                return DateTime.Now.ToUniversalTime();
            }
        }

        public static Exception GetInnerException(Exception exception)
        {
            if (exception.InnerException != null)
            {
                return GetInnerException(exception.InnerException);
            }
            return exception;
        }

        public static string GetFinnalExceptionMessage(Exception exception)
        {
            if (exception.InnerException != null)
            {
                return GetFinnalExceptionMessage(exception.InnerException);
            }
            return exception.Message;
        }

        /// <summary>
        /// Convert Date dd/MM/yyyy to MM/dd/yyyy or MM/dd/yyyy to dd/MM/yyyy
        /// </summary>
        /// <param name="strDate"></param>
        /// <returns></returns>
        public static string ConvertDate(string strDate)
        {
            string date = "";
            string[] TempDate;
            if (strDate != "")
            {
                TempDate = strDate.Split('/');
                date = TempDate[1].ToString() + "/" + TempDate[0].ToString() + "/" + TempDate[2].ToString();
            }
            return date;
        }

        public static JsonResult ReturnJsonResult(string result, string message)
        {
            return new JsonResult
            {
                Data = new { result = result, message = message },
            };
        }

        public static JsonResult ReturnJsonResult(string result)
        {
            JsonResult js = new JsonResult();
            js.Data = result;
            return js;
        }

        public static JsonResult ReturnJsonResult<T>(T t)
        {
            JsonResult js = new JsonResult();
            js.Data = t;
            return js;
        }

        /// <summary>
        /// 转换为Json格式
        /// </summary>
        /// <param name="obj">要转换的对象</param>
        /// <returns>结果Json对象</returns>
        public static string ToJson(object obj)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "dd/MM/yyyy";
            return JsonConvert.SerializeObject(obj, timeConverter);
        }

        public static string ToJsonIgnoreForeignKey(object obj)
        {
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
            jsonSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            return JsonConvert.SerializeObject(obj, jsonSerializerSettings);
        }

        /// <summary>
        /// 转换为带记录总数的Json格式
        /// </summary>
        /// <param name="obj">要转换的对象</param>
        /// <param name="total">记录总数</param>
        /// <returns>结果Json对象</returns>
        public static string ToGridJson(object obj, int total)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "dd/MM/yyyy";
            Hashtable hash = new Hashtable();
            hash["total"] = total;
            hash["rows"] = obj;
            return (JsonConvert.SerializeObject(hash, timeConverter)).Replace("rn", " ").Replace("n", "");
        }
        public static string ToGridJsonWithTime(object obj, int total)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "dd/MM/yyyy HH:mm:ss";
            Hashtable hash = new Hashtable();
            hash["total"] = total;
            hash["rows"] = obj;
            return (JsonConvert.SerializeObject(hash, timeConverter)).Replace("rn", " ").Replace("n", "");
        }



        /// <summary>
        /// 使Json反序列化
        /// </summary>
        /// <typeparam name="T">反序列化类型</typeparam>
        /// <param name="obj">Json</param>
        /// <returns>结果对象</returns>
        public static T Deserialize<T>(string obj)
        {
            return JsonConvert.DeserializeObject<T>(obj);
        }

        public static DataTable JsonToDataTable(string strJson)
        {
            //取出表名   
            Regex rg = new Regex(@"(?<={)[^:]+(?=:[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //获取数据   
            Regex rgData = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rgData.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');

                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        DataColumn dc = new DataColumn();
                        string[] strCell = str.Split(':');
                        dc.ColumnName = strCell[0].Replace(""", "");
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split(':')[1].Trim().Replace("", ",").Replace("", ":").Replace(""", "").Replace("null", "").Replace("NULL", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;

        }

        public static string DataTableToJson(DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append(""" + dt.Columns[j].ColumnName.ToString() + "":"" + dt.Rows[i][j].ToString() + """);
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]");
            return Json.ToString();
        }

        public static void DeleteFile(string fileNameAndPath)
        {
            if (System.IO.File.Exists(fileNameAndPath))
            {
                System.IO.File.Delete(fileNameAndPath);
            }
        }

    }
}

2.日志工具类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.IO;

namespace Arise.Common
{
    public static class LogHelper
    {
        public static string RecordError(Exception exception)
        {
            string Url = HttpContext.Current.Request.RawUrl;//错误发生地址            
            string errorMessage = Utility.GetFinnalExceptionMessage(exception);
            try
            {
                string path = ConfigurationManager.AppSettings["TempFilePath"].ToString().Trim();
                string year = DateTime.Now.ToString("dd/MM/yyyy").Substring(6, 4);
                string month = DateTime.Now.ToString("dd/MM/yyyy").Substring(3, 2);
                string day = DateTime.Now.ToString("dd/MM/yyyy").Substring(0, 2);
                path += @"ErrorLog" + year + month;
                if (!Directory.Exists(path)) //如果文件夹不存在,则创建文件夹(每个月一个文件夹)
                {
                    Directory.CreateDirectory(path);
                }

                string fileName = @"ErrorLog" + year + month + day + ".txt";
                path += fileName;

                if (!File.Exists(path)) //如果文件不存在,则创建文件(每天一个文件)
                {
                    File.Create(path).Close();
                }

                StreamWriter writer = new StreamWriter(path, true);
                String date = DateTime.Now.ToString();
                writer.WriteLine("rn" + date);
                writer.WriteLine("Message: ");
                writer.WriteLine("t" + errorMessage);                
                writer.Close();
                return errorMessage;
            }
            catch (Exception)
            {                
                throw new Exception(errorMessage);
            }            
        }
        public static string GetFinnalExceptionMessage(Exception exception)
        {
            if (exception.InnerException != null)
            {
                return GetFinnalExceptionMessage(exception.InnerException);
            }
            return exception.Message;
        }
    }
}
3.UserMessageShow:(常用的信息,有效的避免了在代码中硬编码)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arise.Common
{
    public static class UserMessageShow
    {
        public static string ErrorPassword = "Your Password OR UserName is Error!";
        public static string ErrorLogin = "Your have alreadly Login System!";
    }
}
 

相关内容推荐