C#工具类

using System;
using System.Collections.Generic;
using System.Data;
using ManageForm.ServiceComm;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ManageForm.Comm
{
    public class Util
    {

        public static ExcuteLabelRequest GetRequest(string label, string[] paramArr)
        {
            ExcuteLabelRequest request = new ExcuteLabelRequest();
            request.APIKey = Login.ApiKey;
            request.SessionKey = Login.SessionKey;
            request.UserID = Login.UserID;
            request.label = label;
            request.list = paramArr;
            return request;
        }

        public static SubmitTableRequest GetSubmitTableRequest(string label, string[][] paramArr)
        {
            SubmitTableRequest request = new SubmitTableRequest();
            request.APIKey = Login.ApiKey;
            request.SessionKey = Login.SessionKey;
            request.UserID = Login.UserID;
            request.label = label;
            request.list = paramArr;
            return request;
        }

        //--------------------------基本方法----------------------
        #region 求浮点型数小数
        /// <summary>
        /// 求浮点型数小数,小数位最后面的0去掉
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal ToDecimal(object obj)
        {
            if (obj + "" != "")
            {
                try
                {
                    decimal dm = Convert.ToDecimal(obj);

                    string str = dm.ToString("#.#########");//去除小数点后的0
                    if (str == "")
                    {
                        str = "0";
                    }

                    dm = decimal.Parse(str);

                    return dm;
                }
                catch
                {
                    return 0.0m;
                }
                // return Convert.ToDecimal(obj);
            }
            return 0.0m;
        }

        /// <summary>
        /// 求浮点型数小数,小数位最后面的0去掉,并截取指定位数小数位
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="precision"></param>
        /// <returns></returns>
        public static decimal ToDecimal(object obj, int digit)
        {
            if (obj + "" != "")
            {
                try
                {
                    decimal dm = Convert.ToDecimal(obj);

                    string str = dm.ToString("#.#########");//去除小数点后的0
                    if (str == "")
                    {
                        str = "0";
                    }

                    dm = decimal.Parse(str);

                    return decimal.Round(dm, digit, MidpointRounding.AwayFromZero);
                }
                catch
                {
                    return 0.0m;
                }
                // return Convert.ToDecimal(obj);
            }
            return 0.0m;
        }
        #endregion

        //格式化到整数,不会报错
        public static int ToInt(object var)
        {
            try
            {
                return Convert.ToInt32(var);
            }
            catch
            {
                return 0;
            }
        }

        //IsNullOrWhiteSpace
        public static bool isNull(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return true;
            }
            if (string.IsNullOrEmpty(str))
            {
                return true;
            }
            return false;
        }

        //表格对象为空,或者没有行
        public static bool isNull(DataTable dt)
        {
            if (null == dt || dt.Rows.Count <= 0)
            {
                return true;
            }
            return false;
        }

        //数据集对象为空,或者没有没有,或者表中没有行
        public static bool isNull(DataSet ds)
        {
            if (null == ds || null == ds.Tables || ds.Tables.Count <= 0 || isNull(ds.Tables[0]))
            {
                return true;
            }
            return false;
        }

        //数据集对象为空,或者没有没有,或者表中没有行
        public static string timeFormate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string ToMD5(string str)
        {
            //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            return "";
        }

        protected virtual IList<string> DataSetToArrayList(DataSet ds)
        {
            IList<string> WhereStr = new List<string>();
            DataRow dr;

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dr = ds.Tables[0].Rows[i];
                if (dr[0].ToString().Trim().Length != 0)
                {
                    WhereStr.Add(dr[0].ToString());
                }
            }
            return WhereStr;
        }

        protected virtual string[] DataSetToList(DataSet ds)
        {
            string[] SqlList = new string[ds.Tables[0].Rows.Count];
            DataRow dr;

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                dr = ds.Tables[0].Rows[i];
                if (dr[0].ToString().Trim().Length != 0)
                {
                    SqlList[i] = dr[0].ToString();
                }
            }
            return SqlList;
        }

        /// <summary>
        /// 将Byte数据反序列化成DataSet
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static DataSet ByteToDataSet(byte[] buffer)
        {
            DataSet tempDS = null;
            //解压压缩流
            byte[] bytes = Compression(buffer, CompressionMode.Decompress);
            MemoryStream stream = new MemoryStream(bytes);
            IFormatter formatter = new BinaryFormatter();
            //反序列化
            tempDS = (DataSet)formatter.Deserialize(stream);
            stream.Close();
            return tempDS;
        }

        /// <summary>
        /// 将Byte数据反序列化成DataSet
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static DataTable ByteToDataTable(byte[] buffer)
        {
            DataTable tempDS = null;
            //解压压缩流
            byte[] bytes = Compression(buffer, CompressionMode.Decompress);
            MemoryStream stream = new MemoryStream(bytes);
            IFormatter formatter = new BinaryFormatter();
            //反序列化
            tempDS = (DataTable)formatter.Deserialize(stream);
            stream.Close();
            return tempDS;
        }

        /// <summary>
        /// 将DataSet数据序列化成Byte
        /// </summary>
        /// <param name="tempDS"></param>
        /// <returns></returns>
        public static byte[] DataSetToByte(DataSet tempDS)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, tempDS);
            byte[] buffer_all = stream.ToArray();
            stream.Close();

            byte[] bytes_c = Compression(buffer_all, CompressionMode.Compress);
            return bytes_c;
        }

        /// <summary>
        /// 将DataTable数据序列化成Byte
        /// </summary>
        /// <param name="tempDS"></param>
        /// <returns></returns>
        public static byte[] DataTableToByte(DataTable tempTable)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, tempTable);
            byte[] buffer_all = stream.ToArray();
            stream.Close();

            byte[] bytes_c = Compression(buffer_all, CompressionMode.Compress);
            return bytes_c;
        }

        /// <summary>
        /// 解压缩/压缩
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static byte[] Compression(byte[] data, CompressionMode mode)
        {
            DeflateStream zip = null;
            try
            {
                if (mode == CompressionMode.Compress)
                {
                    MemoryStream ms = new MemoryStream();
                    zip = new DeflateStream(ms, mode, true);
                    zip.Write(data, 0, data.Length);
                    zip.Close();
                    return ms.ToArray();
                }
                else
                {
                    MemoryStream ms = new MemoryStream();
                    ms.Write(data, 0, data.Length);
                    ms.Flush();
                    ms.Position = 0;
                    zip = new DeflateStream(ms, mode, true);
                    MemoryStream os = new MemoryStream();
                    int SIZE = 1024;
                    byte[] buf = new byte[SIZE];
                    int l = 0;
                    do
                    {
                        l = zip.Read(buf, 0, SIZE);
                        if (l == 0) l = zip.Read(buf, 0, SIZE);
                        os.Write(buf, 0, l);
                    } while (l != 0);
                    zip.Close();
                    return os.ToArray();
                }
            }
            catch
            {
                if (zip != null) zip.Close();
                return null;
            }
            finally
            {
                if (zip != null) zip.Close();
            }
        }

        /// <summary>
        /// 分解数据表
        /// </summary>
        /// <param name="originalTab">需要分解的表</param>
        /// <param name="rowsNum">每个表包含的数据量</param>
        /// <returns></returns>
        public static DataSet SplitDataTable(DataTable sourceTable, int rowsNum)
        {
            //获取所需创建的表数量
            int tableNum = sourceTable.Rows.Count / rowsNum;
            //获取数据余数
            int remainder = sourceTable.Rows.Count % rowsNum;

            DataSet ds = new DataSet();

            //如果只需要创建1个表,直接将原始表存入DataSet
            if (tableNum == 0)
            {
                ds.Tables.Add(sourceTable);
            }
            else
            {
                DataTable[] tableSlice = new DataTable[tableNum];

                //Save orginal columns into new table.
                for (int c = 0; c < tableNum; c++)
                {
                    tableSlice[c] = new DataTable();
                    foreach (DataColumn dc in sourceTable.Columns)
                    {
                        tableSlice[c].Columns.Add(dc.ColumnName, dc.DataType);
                    }
                }
                //Import Rows
                for (int i = 0; i < tableNum; i++)
                {
                    // if the current table is not the last one
                    if (i != tableNum - 1)
                    {
                        for (int j = i * rowsNum; j < ((i + 1) * rowsNum); j++)
                        {
                            tableSlice[i].ImportRow(sourceTable.Rows[j]);
                        }
                    }
                    else
                    {
                        for (int k = i * rowsNum; k < ((i + 1) * rowsNum + remainder); k++)
                        {
                            tableSlice[i].ImportRow(sourceTable.Rows[k]);
                        }
                    }
                }

                //add all tables into a dataset                
                foreach (DataTable dt in tableSlice)
                {
                    ds.Tables.Add(dt);
                }
            }
            return ds;
        }
    }
}

猜你喜欢

转载自zheyiw.iteye.com/blog/2045960