C#常用Utils帮助类

1、Utils类:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;

namespace DemoAPI
{
    public class Utils
    {
        #region 001:DataSet、DataTable是否为空
        /// <summary>
        /// 验证DataTable是否为空,空返回FALSE,不为空返回TRUE
        /// </summary>
        /// <param name="dt">DataTable 对象</param>
        /// <returns></returns>
        public static bool isNoNullDataSet(DataTable dt)
        {
            bool bl = false;
            if (dt != null && dt.Rows.Count > 0)
            {
                bl = true;
            }
            return bl;
        }

        /// <summary>
        /// 验证DataTable是否为空,空返回FALSE,不为空返回TRUE
        /// </summary>
        /// <param name="ds">DataSet 对象</param>
        /// <returns></returns>
        public static bool isNoNullDataSet(DataSet ds)
        {
            bool bl = false;
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                bl = true;
            }
            return bl;
        }
        #endregion

        #region 002:string是否为空
        /// <summary>
        /// string是否为空,空返回FALSE,不为空返回TRUE
        /// </summary>
        /// <param name="dt">DataTable 对象</param>
        /// <returns></returns>
        public static bool isNoNullString(string str)
        {
            bool bl = false;
            if (str != null && !string.IsNullOrEmpty(str))
            {
                bl = true;
            }
            return bl;
        }
        #endregion

        #region 003:Int32是否为空
        /// <summary>
        /// int是否为空,空返回FALSE,不为空且大于0返回TRUE
        /// </summary>
        /// <param name="dt">DataTable 对象</param>
        /// <returns></returns>
        public static bool isNoNullInt32(Int32 val)
        {
            bool bl = false;
            if (val != null && val > 0)
            {
                bl = true;
            }
            return bl;
        }
        #endregion

        #region 003:DateTime是否为空
        /// <summary>
        /// DateTime是否为空,空返回FALSE,不为空返回TRUE
        /// </summary>
        /// <param name="dt">DataTable 对象</param>
        /// <returns></returns>
        public static bool isNoNullDateTime(DateTime dt)
        {
            bool bl = false;
            DateTime init = new DateTime(1900, 1, 1);
            if (dt != null && !string.IsNullOrEmpty(dt.ToString()) && dt > init)
            {
                bl = true;
            }
            return bl;
        }
        #endregion

        #region 004获取Get、Post提交的参数值
        public static string GetPost(string name)
        {

            string value = HttpContext.Current.Request[name];
            return value == null ? string.Empty : value.Trim();
        }
        public static int GetPostInt(string name)
        {

            string value = HttpContext.Current.Request[name];
            int tmp = 0;

            if (!string.IsNullOrWhiteSpace(value))
            {
                int.TryParse(value, out tmp);
            }
            return tmp;
        }
        public static int? GetPostIntNull(string name)
        {

            string value = HttpContext.Current.Request[name];
            int? tmp = 0;
            int t = 0;
            if (!string.IsNullOrWhiteSpace(value))
            {
                if (int.TryParse(value, out t))
                    tmp = t;
            }
            else
            {
                tmp = null;
            }
            return tmp;
        }
        #endregion

        #region 设置全局变量
        //获得固有的加密字符串
        //private static string jmStr = System.Configuration.ConfigurationManager.AppSettings["jmStr"].ToString();
        private static string jmStr = "RXJY";
        //设置加密的密钥 
        private static string sKey = "华跃博弈精益求精";


        //private static string tuiGuangUrl = System.Configuration.ConfigurationManager.AppSettings["tgurl"].ToString();

        #endregion

        #region  可逆的加密方法
        /// <summary>
        /// 可逆的加密方法
        /// </summary>
        /// <param name="strEnCrypt">需要加密的字符串</param>
        /// <returns>加密后的结果</returns>
        public static string EnCrypt(string strEnCrypt)
        {
            try
            {
                DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                byte[] bs1 = Encoding.Default.GetBytes(strEnCrypt);
                dESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(sKey);
                dESCryptoServiceProvider.IV = Encoding.ASCII.GetBytes(sKey);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(), CryptoStreamMode.Write);
                cryptoStream.Write(bs1, 0, (int)bs1.Length);
                cryptoStream.FlushFinalBlock();
                StringBuilder stringBuilder = new StringBuilder();
                byte[] bs2 = memoryStream.ToArray();
                foreach (byte b in bs2)
                {
                    stringBuilder.AppendFormat("{0:X2}", b);
                }
                string strBuilder = stringBuilder.ToString();
                strBuilder = strBuilder + jmStr;
                return NiXu(strBuilder);
            }
            catch (Exception e)
            {
                //System.Web.HttpContext.Current.Response.Write(e.Message);
                //System.Web.HttpContext.Current.Response.End();
                throw new Exception(e.Message);
            }
        }
        #endregion

        #region 可逆的解密方法
        /// <summary>
        /// 可逆的解密方法
        /// </summary>
        /// <param name="strDeCrypt">需要解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public static string DeCrypt(string strDeCrypt)
        {
            try
            {
                if (strDeCrypt != "" && strDeCrypt != null)
                {
                    strDeCrypt = Utils.ReplaceStringTrim(strDeCrypt);
                    string strBuilder = NiXu(strDeCrypt);
                    strDeCrypt = strBuilder.Substring(0, strBuilder.LastIndexOf("" + jmStr + "")).ToString();
                    DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                    byte[] bs = new byte[strDeCrypt.Length / 2];
                    for (int i = 0; i < strDeCrypt.Length / 2; i++)
                    {
                        int j = Convert.ToInt32(strDeCrypt.Substring(i * 2, 2), 16);
                        bs[i] = (byte)j;
                    }
                    dESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(sKey);
                    dESCryptoServiceProvider.IV = Encoding.ASCII.GetBytes(sKey);
                    MemoryStream memoryStream = new MemoryStream();
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write);
                    cryptoStream.Write(bs, 0, (int)bs.Length);
                    cryptoStream.FlushFinalBlock();
                    new StringBuilder();
                    return Encoding.Default.GetString(memoryStream.ToArray());
                }
                else
                {
                    return "0";
                }

            }
            catch (Exception e)
            {
                //System.Web.HttpContext.Current.Response.Write(e.Message);
                //System.Web.HttpContext.Current.Response.End();
                //throw new Exception(e.Message);
                return "0";
            }
        }
        #endregion

        #region 字符串逆序排列
        /// <summary>
        /// 字符串逆序排列
        /// </summary>
        /// <param name="txtStr">逆序前字符串</param>
        /// <returns>逆序后字符串</returns>
        private static string NiXu(string txtStr)
        {
            string niXuStr = "";
            for (int i = txtStr.Length - 1; i >= 0; i--)
            {
                niXuStr += txtStr[i];
            }
            return niXuStr;
        }
        #endregion

        #region 去除字符串中空格
        /// <summary>
        /// 去除字符串中空格
        /// </summary>
        /// <param name="zifu"></param>
        /// <returns></returns>
        public static string ReplaceStringTrim(string zifu)
        {
            return System.Text.RegularExpressions.Regex.Replace(zifu, @"\s+", "");
        }
        #endregion

        /// <summary>
        ///  工程部加密 字符Md5加密
        /// </summary>
        /// <param name="input">string:需要加密的字符串</param>
        /// <returns>string:加密后的字符串</returns>
        public static string GetMd5Hash(string input)
        {
            string txtStr = string.Empty;
            string niXuStr = string.Empty;
            //创建MD5CryptoServiceProvider对象实例.
            MD5 md5Hasher = MD5.Create();
            // 输入字符串转换为一个字节数组并计算哈希
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            StringBuilder sBuilder = new StringBuilder();
            // 循环每个哈希数,作为十六进制去匹配
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            sBuilder.Append("RXJY");
            txtStr = sBuilder.ToString();
            for (int i = txtStr.Length - 1; i >= 0; i--)
            {
                niXuStr += txtStr[i];
            }
            // 返回十六进制数组
            return niXuStr;
        }

        /// <summary>
        /// 获取当前星期第一天
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime GetWeekFirstDayMon()
        {
            var datetime = DateTime.Now;
            //星期一为第一天  
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);

            //因为是以星期一为第一天,所以要判断weeknow等于0时,要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;

            //本周第一天  
            string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(FirstDay);
        }

        #region 获取日任务的回访剩余
        /// <summary>
        /// 获取日任务的回访剩余
        /// </summary>
        /// <param name="time"></param>
        /// <param name="t_cycle"></param>
        /// <returns></returns>
        public int GetDayVisitTime(DateTime? time, string t_cycle)
        {
            if (time == null)
            {
                var today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + t_cycle);//当天应写回访时间
                var num = (today.AddDays(1) - DateTime.Now).Hours;
                return num;
            }
            else
            {
                var visitTime = Convert.ToDateTime(time);//写回访的时间
                //对于日任务,如果当天已写回访,则计算到第二天应写回访的时间,
                //如果当天未写回访,则显示应写回访时间-当前时间,如果到了第二天,则重新计算到第二天应写回访的倒计时
                if (visitTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd"))
                {
                    var hour = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + t_cycle).Hour;//当天应写回访时间
                    var nowHour = DateTime.Now.Hour;
                    if (nowHour > hour)
                    {
                        return hour - nowHour;
                    }
                    else
                    {
                        return nowHour - hour;
                    }
                }
                else
                {
                    //应写回访时间-当前时间
                    var today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + t_cycle);//当天应写回访时间
                    var num = (today.AddDays(1) - DateTime.Now).Hours;
                    return num;
                }

            }
        }
        #endregion

        #region 获取周任务的回访剩余
        /// <summary>
        /// 获取周任务的回访剩余
        /// </summary>
        /// <param name="time">近一次写回访的时间</param>
        /// <param name="chronography">每周同</param>
        /// <param name="t_cycle">几点</param>
        /// <returns></returns>
        public int GetWeekVisitTime(DateTime? time, int chronography, string t_cycle)
        {
            if (time == null)
            {
                #region
                //计算现在到下次应写回访的时间差
                int week = (int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek;//获取当前时间是周几
                int nowHour = (int)DateTime.Now.Hour;
                int hour = int.Parse(t_cycle.Split(':')[0]);
                if ((week < chronography) || (week == chronography && nowHour < hour))//在规定的周日期之前显示到本周的倒计时
                {
                    int num = (chronography - week) * 24 - DateTime.Now.Hour + int.Parse(t_cycle.Split(':')[0]);
                    return num;
                }
                else //计算到下周应写的倒计时
                {
                    int totDay = chronography + 7 - week - 1;//获取到下周总的天数
                    //总的天数小时数+今天剩余小时数-当天写的
                    int num = totDay * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);
                    return num;
                }
                #endregion
            }
            else
            {
                var date = Convert.ToDateTime(time);
                //判断本周是否写过
                if (GetWeekOfYear(DateTime.Now) == GetWeekOfYear(date))
                {
                    int week = (int)date.DayOfWeek == 0 ? 7 : (int)date.DayOfWeek;//获取是周几写的
                    //判断是否是规定的当天之前写的
                    //之前写的还显示倒计时。之后的显示到下周五的倒计时
                    if (week == chronography)//判断是否是同一周的同一天-----是否在规定 的当天 写的  
                    {
                        //当天已经写过则计算当前当下周应写的时间差
                        var noewWeek = (int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek;//获取当前日期是周几
                        int totDay = chronography + 7 - noewWeek - 1;//获取到下周总的天数 
                        //总的天数小时数+今天剩余小时数-当天写的
                        int num = totDay * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);
                        return num;
                    }
                    else if (week < chronography)//在规定的周日期之前写的任务显示到本周的倒计时
                    {
                        var nowWeek = (int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek;//获取当前日期是周几
                        int num = (6 - nowWeek - 1) * 24 + int.Parse(t_cycle.Split(':')[0]) + 24 - DateTime.Now.Hour;
                        return num;
                    }
                    else //计算到下周应写的倒计时
                    {
                        var nowWeek = (int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek;//获取当前日期是周几
                        int totDay = chronography + 7 - nowWeek - 1;//获取到下周总的天数 
                        //总的天数小时数+今天剩余小时数-当天写的
                        int num = totDay * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);
                        return num;
                    }
                }
                else//如果本周没有写
                {
                    var nowWeek = (int)DateTime.Now.DayOfWeek == 0 ? 7 : (int)DateTime.Now.DayOfWeek;//获取当前日期是周几
                    int num = (chronography - nowWeek) * 24 - DateTime.Now.Hour + int.Parse(t_cycle.Split(':')[0]);
                    return num;
                }
            }
        }
        #endregion

        #region 获取月任务的回访剩余
        public int GetMonthVisitTime(DateTime? time, int chronography, string t_cycle)
        {
            if (time == null)
            {
                var now = DateTime.Now;
                int day = DateTime.Now.Day;//获取当前时间是本月哪一天写的
                if (day < chronography)//在规定的月任务日期之前显示到本月的倒计时
                {
                    //应写日期减已写的日期
                    int num = (chronography - day - 1) * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);
                    return num;
                }
                else //计算到下月应写的倒计时
                {
                    int days = GetDays(DateTime.Now);//获取当月的天数
                    //当月的天数减去当前的天数
                    int totDay = days - day;
                    int num = (totDay + chronography - 1) * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);

                    return num;
                }
            }
            else
            {
                var date = Convert.ToDateTime(time);//最近一次回访时间
                //判断是否是本月写的
                if (date.ToString("yyyy-MM") == DateTime.Now.ToString("yyyy-MM"))
                {
                    int day = date.Day;//获取是本月哪一天写的
                    //判断是否是规定的当天之前写的
                    //之前写的还显示倒计时。之后的显示到下月应写的日期的倒计时
                    if (day == chronography)//判断是否是月任务选中的当月的同一天
                    {
                        //当天已经写过则计算当前当下月应写的时间差
                        int days = GetDays(DateTime.Now);//获取当月的天数
                        //当月的天数减去当前的天数
                        int totDay = days - DateTime.Now.Day;
                        //当月的天数+下月应写之前的天数
                        int num = (totDay + chronography - 1) * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);
                        return num;
                    }
                    else if (day < chronography)//在规定的月任务日期之前写的任务显示到本月的倒计时
                    {
                        var nowDay = DateTime.Now.Day;//获取当前日期是当月第几天
                        //应写日期减已写的日期
                        int num = (chronography - nowDay - 1) * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);
                        return num;
                    }
                    else //计算到下月应写的倒计时
                    {
                        int days = GetDays(DateTime.Now);//获取当月的天数
                        //当月的天数减去当前的天数
                        int totDay = days - DateTime.Now.Day;
                        int num = (totDay + chronography - 1) * 24 + (24 - DateTime.Now.Hour) + int.Parse(t_cycle.Split(':')[0]);
                        return num;
                    }
                }
                else//如果本月没有写
                {
                    int days = GetDays(DateTime.Now);//获取当月的天数
                    //当月的天数减去当前的天数
                    int totDay = days - DateTime.Now.Day;
                    int num = (totDay + chronography) * 24 - DateTime.Now.Hour + 12;
                    return num;
                }
            }
        }
        #endregion
        private static int GetWeekOfYear(DateTime dt)
        {
            GregorianCalendar gc = new GregorianCalendar();
            int weekOfYear = gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            return weekOfYear;
        }

        private int GetDays(DateTime dt)
        {
            int day = DateTime.DaysInMonth(dt.Year, dt.Month);
            return day;
        }

        #region 回访内容换行处理
        /// <summary>
        /// 回访内容换行处理
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string DealVisitContent(string content)
        {
            content = content.Replace("", ";</br>");
            content = content.Replace(";", ";</br>");
            return content;
        }
        #endregion


        #region 状态对应阶段
        /// <summary>
        /// 状态对应阶段
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string ZhuangTaiZhuanHuan(string ZhuangTai)
        {
            var jie = "";
            switch (ZhuangTai)
            {
                case "0": jie = "在跟踪"; break;
                case "5": jie = "在谈"; break;
                case "7": jie = "已签"; break;
                case "8": jie = "未签"; break;
                case "18": jie = "商务打回"; break;
                case "21": jie = "初审打回"; break;
                case "22": jie = "终审打回"; break;
                case "2": jie = "地方放弃"; break;
                case "3": jie = "集团放弃"; break;
                case "17": jie = "商务审批"; break;
                case "23":
                case "24":
                case "25": jie = "主案审批"; break;
                default: jie = "暂无记载"; break;
            }
            return jie;
        }
        #endregion

        #region 传入服务器地址 返回Json数据
        /// <summary>
        /// 传入服务器地址 返回Json数据 Get
        /// </summary>
        /// <param name="serviceAddress">http地址</param>
        /// <returns></returns>
        internal static string HttpReturnJson(string serviceAddress)
        {
            string retString = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            if (request != null)
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            else
            {
                retString = "{'StatusMsg': '接口请求失败!','StatusCode': -1}";
            }
            return retString;
        }
        #endregion

        #region 根据图片路径返回图片的字节流byte[]
        /// <summary>
        /// 根据图片路径返回图片的字节流byte[]
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <returns>返回的字节流</returns>
        internal static byte[] GetImageByte(string imagePath)
        {
            FileStream files = new FileStream(imagePath, FileMode.Open);
            byte[] imgByte = new byte[files.Length];
            files.Read(imgByte, 0, imgByte.Length);
            files.Close();
            return imgByte;
        }
        #endregion

        #region  用于url传值的base64加密算法
        /// <summary>
        /// 用于url传值的base64加密算法
        /// </summary>
        /// <param name="input">需加密的字符串</param>
        /// <returns></returns>
        public static string GetParEncoded(string input)
        {
            byte[] temp = Encoding.Default.GetBytes(input);
            return Base64Encoder.Encoder.GetEncoded(temp);
        }
        public class Base64Encoder
        {
            #region base64加密算法

            byte[] source;
            int length, length2;
            int blockCount;
            int paddingCount;
            public static Base64Encoder Encoder = new Base64Encoder();

            public Base64Encoder()
            {

            }
            private void init(byte[] input)
            {
                source = input;
                length = input.Length;
                if ((length % 3) == 0)
                {
                    paddingCount = 0;
                    blockCount = length / 3;
                }
                else
                {
                    paddingCount = 3 - (length % 3);
                    blockCount = (length + paddingCount) / 3;
                }
                length2 = length + paddingCount;
            }
            public string GetEncoded(byte[] input)
            {
                //初始化
                init(input);

                byte[] source2;
                source2 = new byte[length2];

                for (int x = 0; x < length2; x++)
                {
                    if (x < length)
                    {
                        source2[x] = source[x];
                    }
                    else
                    {
                        source2[x] = 0;
                    }
                }

                byte b1, b2, b3;
                byte temp, temp1, temp2, temp3, temp4;
                byte[] buffer = new byte[blockCount * 4];
                char[] result = new char[blockCount * 4];
                for (int x = 0; x < blockCount; x++)
                {
                    b1 = source2[x * 3];
                    b2 = source2[x * 3 + 1];
                    b3 = source2[x * 3 + 2];

                    temp1 = (byte)((b1 & 252) >> 2);

                    temp = (byte)((b1 & 3) << 4);
                    temp2 = (byte)((b2 & 240) >> 4);
                    temp2 += temp;

                    temp = (byte)((b2 & 15) << 2);
                    temp3 = (byte)((b3 & 192) >> 6);
                    temp3 += temp;

                    temp4 = (byte)(b3 & 63);

                    buffer[x * 4] = temp1;
                    buffer[x * 4 + 1] = temp2;
                    buffer[x * 4 + 2] = temp3;
                    buffer[x * 4 + 3] = temp4;

                }

                for (int x = 0; x < blockCount * 4; x++)
                {
                    result[x] = sixbit2char(buffer[x]);
                }


                switch (paddingCount)
                {
                    case 0: break;
                    case 1: result[blockCount * 4 - 1] = '_'; break;
                    case 2: result[blockCount * 4 - 1] = '_';
                        result[blockCount * 4 - 2] = '_';
                        break;
                    default: break;
                }
                return new string(result);
            }
            private char sixbit2char(byte b)
            {
                char[] lookupTable = new char[64]{
                  'A','B','C','D','E','F','G','H','I','J','K','L','$',
                 'N','O','P','Q','R','S','T','U','M','W','X','Y','Z',
                 'a','b','c','d','e','f','g','h','i','j','k','l','m',
                 'n','o','p','q','*','s','t','u','v','w','x','y','z',
                 '0','1','2','3','4','5','6','7','8','9','r','V'};

                if ((b >= 0) && (b <= 63))
                {
                    return lookupTable[(int)b];
                }
                else
                {

                    return ' ';
                }
            }


            #endregion
        }
        #endregion

        #region 发送通知
        /// <summary>
        /// 发送通知
        /// </summary>
        /// <param name="AlertText"></param>
        /// <param name="Iphone"></param>
        /// <param name="Type"></param>
        /// <param name="Group"></param>
        /// <param name="AlertTitle"></param>
        /// <param name="IsApnsProduction"></param>
        /// <param name="InitiatorCard"></param>
        /// <param name="InitiatorName"></param>
        /// <param name="RewardMoney"></param>
        /// <returns></returns>
        public static string SendPhone(IDictionary<string, string> dict, string url)
        {
            string results = "";
            try
            {

                string par = string.Format("param={0}", Newtonsoft.Json.JsonConvert.SerializeObject(dict));
                WebRequest request = WebRequest.Create(url);
                request.Method = "post";
                request.ContentType = "application/x-www-form-urlencoded";

                byte[] data = System.Text.Encoding.UTF8.GetBytes(par);

                request.ContentLength = data.Length;
                //设置请求流
                System.IO.Stream requestStream = request.GetRequestStream();
                //将参数加入到请求流中。
                requestStream.Write(data, 0, data.Length);

                //获取服务器端的响应
                WebResponse response = request.GetResponse();
                //获取响应回来的流数据。
                System.IO.Stream responseStream = response.GetResponseStream();


                using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream))
                {
                    results = reader.ReadToEnd();

                    //seee = (JObject)JsonConvert.DeserializeObject(results);
                }
            }
            catch (Exception e)
            {
                NetLog.WriteTextLog(e.Message);
            }

            return results;
        }
        #endregion



        /// <summary>
        /// 公共事件奖罚
        /// </summary>
        /// <param name="em_Sponsor">发起人卡号</param>
        /// <param name="em_Executor">执行人卡号</param>
        /// <param name="em_Content">执行内容</param>
        /// <param name="rp_Money">奖罚金额</param>
        /// <param name="em_theme">标题</param>
        /// <param name="rp_Method">奖罚方式 1=现金 2=工资</param>
        /// <returns></returns>
        public static string LaunchEventAndOver(string em_Sponsor, string em_Executor, string em_Content, string rp_Money, string em_theme, string rp_Method)
        {
            string ShiJianAPI = System.Configuration.ConfigurationManager.AppSettings["ShiJianAPI"];
            string url = ShiJianAPI + "/api/EventPlatform/LaunchEventAndOver/";
            string _params = "em_Sponsor=" + em_Sponsor + "&em_Executor=" + em_Executor + "&em_Content=" + em_Content + "&rp_Money=" + rp_Money + "&em_theme=" + em_theme + "&rp_Method=" + rp_Method;
            WebRequest request = WebRequest.Create(url);
            request.Method = "post";
            request.ContentType = "application/x-www-form-urlencoded";

            byte[] data = System.Text.Encoding.UTF8.GetBytes(_params);

            request.ContentLength = data.Length;
            //设置请求流
            System.IO.Stream requestStream = request.GetRequestStream();
            //将参数加入到请求流中。
            requestStream.Write(data, 0, data.Length);

            //获取服务器端的响应
            WebResponse response = request.GetResponse();
            //获取响应回来的流数据。
            System.IO.Stream responseStream = response.GetResponseStream();

            string results = string.Empty;
            using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream))
            {
                results = reader.ReadToEnd();

                var seee = (JObject)JsonConvert.DeserializeObject(results);
            }


            return results;
        }

        #region json转为DataTable
        /// <summary>
        /// json转为DataTable
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        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 rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.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 = "";
                    foreach (string str in strRows)
                    {
                        DataColumn dc = new DataColumn();
                        string[] strCell = str.Split(':');

                        dc.ColumnName = strCell[0].ToString().Replace("\"", "").Trim();
                        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("\"", "").Trim();
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }
        #endregion

        
    }
}

 

posted @ 2018-07-05 12:06  狼人666  阅读(2744)  评论(0编辑  收藏  举报