namespace BLL
{
using MiniExcelLibs;
using Model;
using Quartz;
using RestSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
///
/// 通用方法类。
///
public static class Funs
{
///
/// 维护一个DB集合
///
private static ConcurrentDictionary dataBaseLinkList = new ConcurrentDictionary();
///
/// 维护一个DB集合
///
public static ConcurrentDictionary DBList
{
get
{
return dataBaseLinkList;
}
}
public static IScheduler ScheduledTasks
{
get;
set;
}
///
/// 数据库连接字符串
///
private static string connString;
///
/// 数据库连结字符串。
///
public static string ConnString
{
get
{
if (connString == null)
{
throw new NotSupportedException("请设置连接字符串!");
}
return connString;
}
set
{
if (connString != null)
{
throw new NotSupportedException("连接已设置!");
}
connString = value;
}
}
///
/// 服务器路径
///
public static string AttachRootPath { get; set; }
///
/// 系统名称
///
public static string SystemName
{
get;
set;
}
///
/// 服务器路径
///
public static string RootPath
{
get;
set;
}
///
/// 集团服务器路径
///
public static string CNCECPath
{
get;
set;
}
public static string SGGLUrl
{
get;
set;
}
///
/// 实名制地址
///
public static string RealNameApiUrl
{
get;
set;
}
///
/// 软件版本
///
public static string SystemVersion
{
get;
set;
}
public static string MobileWebUrl
{
get;
set;
}
///
/// 每页数量
///
public static int PageSize
{
get;
set;
} = 15;
///
/// 数据库上下文。
///
public static SGGLDB DB
{
get
{
if (!DBList.ContainsKey(System.Threading.Thread.CurrentThread.ManagedThreadId))
{
DBList.TryAdd(System.Threading.Thread.CurrentThread.ManagedThreadId, new Model.SGGLDB(connString));
}
// DBList[System.Threading.Thread.CurrentThread.ManagedThreadId].CommandTimeout = 1200;
return DBList[System.Threading.Thread.CurrentThread.ManagedThreadId];
}
}
///
/// 加密密码
///
/// 加密前的密码
/// 加密后的密码
public static string EncryptionPassword(string password)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
return BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(password))).Replace("-", null);
//return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
}
#region 获取用户初始密码
///
/// 获取用户初始密码
///
///
///
public static string getInitialPassword(string unitId, string idCard)
{
string prefixValue = "sedin";
string suffixValue = "1234";
//var getUnit = UnitService.GetUnitByUnitId(unitId);
//if (getUnit != null)
//{
// if (!string.IsNullOrEmpty(getUnit.UnitCode))
// {
// if (getUnit.UnitCode.Length > 10)
// {
// prefixValue = getUnit.UnitCode.Substring(getUnit.UnitCode.Length - 10);
// }
// else
// {
// prefixValue = getUnit.UnitCode;
// }
// }
//}
if (!string.IsNullOrEmpty(idCard))
{
if (idCard.Length > 4)
{
suffixValue = idCard.Substring(idCard.Length - 4);
}
else
{
suffixValue = idCard;
}
}
return prefixValue + "." + suffixValue;
}
#endregion
#region 验证密码
///
///
///
///
///
public static bool IsLetter(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
public static bool IsDigit(char c)
{
return c >= '0' && c <= '9';
}
static bool IsSymbol(char c)
{
return c > 32 && c < 127 && !IsDigit(c) && !IsLetter(c);
}
public static bool IsValIDPassword(string password)
{
return
password.Any(c => IsLetter(c)) &&
password.Any(c => IsDigit(c)) &&
password.Any(c => IsSymbol(c));
}
#endregion
///
/// 为目标下拉框加上 "请选择" 项
///
/// 目标下拉框
public static void PleaseSelect(System.Web.UI.WebControls.DropDownList DDL)
{
DDL.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- 请选择 -", "0"));
return;
}
///
/// 为目标下拉框加上 "请选择" 项
///
/// 目标下拉框
public static void FineUIPleaseSelect(FineUIPro.DropDownList DDL)
{
DDL.Items.Insert(0, new FineUIPro.ListItem("- 请选择 -", BLL.Const._Null));
return;
}
///
/// 为目标下拉框加上选择内容
///
/// 目标下拉框
public static void FineUIPleaseSelect(FineUIPro.DropDownList DDL, string text)
{
DDL.Items.Insert(0, new FineUIPro.ListItem(text, BLL.Const._Null));
return;
}
///
/// 为目标下拉框加上选择内容
///
/// 目标下拉框
public static void FineUIPleaseSelectNull(FineUIPro.DropDownList DDL, string text)
{
DDL.Items.Insert(0, new FineUIPro.ListItem(text, null));
return;
}
///
/// 为目标下拉框加上 "重新编制" 项
///
/// 目标下拉框
public static void ReCompileSelect(System.Web.UI.WebControls.DropDownList DDL)
{
DDL.Items.Insert(0, new System.Web.UI.WebControls.ListItem("重新编制", "0"));
return;
}
///
/// 页码下拉框
///
/// 目标下拉框
public static void DropDownPageSize(FineUIPro.DropDownList DDL)
{
DDL.Items.Insert(0, new FineUIPro.ListItem("10", "10"));
DDL.Items.Insert(1, new FineUIPro.ListItem("20", "20", true));
DDL.Items.Insert(2, new FineUIPro.ListItem("30", "30"));
DDL.Items.Insert(3, new FineUIPro.ListItem("50", "50"));
DDL.Items.Insert(4, new FineUIPro.ListItem("所有行", "1000000"));
return;
}
///
/// 字符串是否为浮点数
///
/// 要检查的字符串
/// 返回是或否
public static bool IsDecimal(string decimalStr)
{
if (String.IsNullOrEmpty(decimalStr))
{
return false;
}
try
{
Convert.ToDecimal(decimalStr, NumberFormatInfo.InvariantInfo);
return true;
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
return false;
}
}
///
/// 判断一个字符串是否是整数
///
/// 要检查的字符串
/// 返回是或否
public static bool IsInteger(string integerStr)
{
if (String.IsNullOrEmpty(integerStr))
{
return false;
}
try
{
Convert.ToInt32(integerStr, NumberFormatInfo.InvariantInfo);
return true;
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
return false;
}
}
///
/// 获取新的数字
///
/// 要转换的数字
/// 新的数字
public static string InterceptDecimal(object number)
{
if (number == null)
{
return null;
}
decimal newNumber = 0;
string newNumberStr = "";
int an = -1;
string numberStr = number.ToString();
int n = numberStr.IndexOf(".");
if (n == -1)
{
return numberStr;
}
for (int i = n + 1; i < numberStr.Length; i++)
{
string str = numberStr.Substring(i, 1);
if (str == "0")
{
if (GetStr(numberStr, i))
{
an = i;
break;
}
}
}
if (an == -1)
{
newNumber = Convert.ToDecimal(numberStr);
}
else if (an == n + 1)
{
newNumberStr = numberStr.Substring(0, an - 1);
newNumber = Convert.ToDecimal(newNumberStr);
}
else
{
newNumberStr = numberStr.Substring(0, an);
newNumber = Convert.ToDecimal(newNumberStr);
}
return newNumber.ToString();
}
///
/// 判断字符串从第n位开始以后是否都为0
///
/// 要判断的字符串
/// 开始的位数
/// false不都为0,true都为0
public static bool GetStr(string number, int n)
{
for (int i = n; i < number.Length; i++)
{
if (number.Substring(i, 1) != "0")
{
return false;
}
}
return true;
}
///
/// 截取字符串长度
///
/// 要截取的字符串
/// 长度
/// 截取后字符串
public static string GetSubStr(object str, object n)
{
if (str != null)
{
if (str.ToString().Length > Convert.ToInt32(n))
{
return str.ToString().Substring(0, Convert.ToInt32(n)) + "....";
}
else
{
return str.ToString();
}
}
return "";
}
///
/// 根据标识返回字符串list
///
///
///
///
public static List GetStrListByStr(string str, char n)
{
List strList = new List();
if (!string.IsNullOrEmpty(str))
{
strList.AddRange(str.Split(n));
}
return strList;
}
///
/// json字符串将属性值中的英文双引号变成中文双引号
///
/// json字符串
///
public static string JsonReplaceSign(string strJson)
{
//获取每个字符
char[] temp = strJson.ToCharArray();
//获取字符数组长度
int n = temp.Length;
//循环整个字符数组
for (int i = 0; i < n; i++)
{
//查找json属性值(:+" )
if (temp[i] == ':' && temp[i + 1] == '"')
{
//循环属性值内的字符(:+2 推算到value值)
for (int j = i + 2; j < n; j++)
{
//判断是否是英文双引号
if (temp[j] == '"')
{
//排除json属性的双引号
if (temp[j + 1] != ',' && temp[j + 1] != '}')
{
//替换成中文双引号
temp[j] = '”';
}
else if (temp[j + 1] == ',' || temp[j + 1] == '}')
{
break;
}
}
//else if (temp[j] == '-')
//{
// temp[j] = ' ';
//}
//else if (true)
//{
// // 要过虑其他字符,继续添加判断就可以
//}
}
}
}
return new String(temp);
}
///
///
///
///
///
public static String GetStrListByList(List list)
{
string str = string.Empty;
foreach (var item in list)
{
if (!str.Contains(item))
{
str += item + ",";
}
}
if (!string.IsNullOrEmpty(str))
{
str = str.Substring(0, str.Length - 1);
}
return str;
}
#region 数字转换
///
/// 输入文本转换数字类型
///
///
public static decimal GetNewDecimalOrZero(string value)
{
decimal revalue = 0;
if (!String.IsNullOrEmpty(value))
{
try
{
revalue = decimal.Parse(value);
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
}
}
return revalue;
}
///
/// 输入文本转换数字类型
///
///
public static decimal? GetNewDecimal(string value)
{
decimal? revalue = null;
if (!String.IsNullOrEmpty(value))
{
try
{
revalue = decimal.Parse(value);
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
}
}
return revalue;
}
///
/// 输入文本转换数字类型
///
///
public static int? GetNewInt(string value)
{
if (!String.IsNullOrEmpty(value))
{
try
{
return Int32.Parse(value);
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
return null;
}
}
else
{
return null;
}
}
///
/// 输入文本转换数字类型
///
///
public static int GetNewIntOrZero(string value)
{
int revalue = 0;
if (!String.IsNullOrEmpty(value))
{
try
{
revalue = Int32.Parse(value);
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
}
}
return revalue;
}
#endregion
///
/// 指定上传文件的名称
///
///
public static string GetNewFileName()
{
Random rm = new Random(Environment.TickCount);
return DateTime.Now.ToString("yyyyMMddhhmmss") + rm.Next(1000, 9999).ToString();
}
///
/// 指定上传文件的名称
///
///
public static string GetNewFileName(DateTime? dateTime)
{
string str = string.Empty;
Random rm = new Random(System.Environment.TickCount);
if (dateTime.HasValue)
{
str = dateTime.Value.ToString("yyyyMMddhhmmss") + rm.Next(1000, 9999).ToString();
}
return str;
}
public static bool DeleteDir(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//如果有子文件删除文件
File.Delete(f);
Console.WriteLine(f);
}
else
{
//循环递归删除子文件夹
DeleteDir(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
return true;
}
catch (Exception ex) // 异常处理
{
return false;
}
}
#region 时间转换
///
/// 输入文本转换时间类型
///
///
public static DateTime? GetNewDateTime(string time)
{
try
{
if (!String.IsNullOrEmpty(time))
{
return DateTime.Parse(time);
}
else
{
return null;
}
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
return null;
}
}
///
/// 输入文本转换时间类型(空时:默认当前时间)
///
///
public static DateTime GetNewDateTimeOrNow(string time)
{
try
{
if (!String.IsNullOrEmpty(time))
{
return DateTime.Parse(time);
}
else
{
return System.DateTime.Now;
}
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
return System.DateTime.Now;
}
}
///
/// 根据时间获取是哪个季度
///
///
public static string GetQuarterlyByTime(DateTime time)
{
string quarterly = string.Empty;
string yearName = time.Year.ToString();
int month = time.Month;
string name = string.Empty;
if (month >= 1 && month <= 3)
{
name = "第一季度";
}
else if (month >= 4 && month <= 6)
{
name = "第二季度";
}
else if (month >= 7 && month <= 9)
{
name = "第三季度";
}
else if (month >= 10 && month <= 12)
{
name = "第四季度";
}
quarterly = yearName + "年" + name;
return quarterly;
}
///
/// 根据时间获取是哪个季度
///
///
public static int GetNowQuarterlyByTime(DateTime time)
{
int quarterly = 0;
int month = time.Month;
if (month >= 1 && month <= 3)
{
quarterly = 1;
}
else if (month >= 4 && month <= 6)
{
quarterly = 2;
}
else if (month >= 7 && month <= 9)
{
quarterly = 3;
}
else if (month >= 10 && month <= 12)
{
quarterly = 4;
}
return quarterly;
}
///
/// 根据月获取是哪个季度
///
///
public static int GetNowQuarterlyByMonth(int month)
{
int quarterly = 0;
if (month >= 1 && month <= 3)
{
quarterly = 1;
}
else if (month >= 4 && month <= 6)
{
quarterly = 2;
}
else if (month >= 7 && month <= 9)
{
quarterly = 3;
}
else if (month >= 10 && month <= 12)
{
quarterly = 4;
}
return quarterly;
}
///
/// 根据时间获取是哪个季度
///
///
public static string GetQuarterlyNameByMonth(int month)
{
string name = string.Empty;
if (month >= 1 && month <= 3)
{
name = "第一季度";
}
else if (month >= 4 && month <= 6)
{
name = "第二季度";
}
else if (month >= 7 && month <= 9)
{
name = "第三季度";
}
else if (month >= 10 && month <= 12)
{
name = "第四季度";
}
return name;
}
///
/// 根据时间获取是上、下半年
///
///
public static int GetNowHalfYearByTime(DateTime time)
{
int quarterly = 1;
int month = time.Month;
if (month >= 1 && month <= 6)
{
quarterly = 1;
}
else
{
quarterly = 2;
}
return quarterly;
}
///
/// 根据时间获取是上、下半年
///
///
public static int GetNowHalfYearByMonth(int month)
{
int halfYear = 1;
if (month >= 1 && month <= 6)
{
halfYear = 1;
}
else
{
halfYear = 2;
}
return halfYear;
}
///
/// 根据时间获取是上、下半年
///
///
public static string GetNowHalfYearNameByTime(DateTime time)
{
string quarterly = "上半年";
int month = time.Month;
if (month >= 1 && month <= 6)
{
quarterly = "上半年";
}
else
{
quarterly = "下半年";
}
return quarterly;
}
#endregion
///
/// 相差月份
///
///
///
///
public static int CompareMonths(DateTime datetime1, DateTime datetime2)
{
DateTime dt = datetime1;
DateTime dt2 = datetime2;
if (DateTime.Compare(dt, dt2) < 0)
{
dt2 = dt;
dt = datetime2;
}
int year = dt.Year - dt2.Year;
int month = dt.Month - dt2.Month;
month = year * 12 + month;
if (dt.Day - dt2.Day < -15)
{
month--;
}
else if (dt.Day - dt2.Day > 14)
{
month++;
}
return month;
}
public static DateTime GetQuarterlyMonths(string year, string quarterly)
{
string startMonth = string.Empty;
if (quarterly == "1")
{
startMonth = "1";
}
else if (quarterly == "2")
{
startMonth = "4";
}
else if (quarterly == "3")
{
startMonth = "7";
}
else if (quarterly == "4")
{
startMonth = "10";
}
return Funs.GetNewDateTimeOrNow(year + "-" + startMonth + "-01");
}
///
/// 获取单位工程类型
///
///
///
public static string GetUnitWorkType(string projectType)
{
string type = string.Empty;
if (projectType == "1")
{
type = "建筑";
}
if (projectType == "2")
{
type = "安装";
}
return type;
}
#region 获取大写金额事件
public static string NumericCapitalization(decimal num)
{
string str1 = "零壹贰叁肆伍陆柒捌玖"; //0-9所对应的汉字
string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字
string str3 = ""; //从原num值中取出的值
string str4 = ""; //数字的字符串形式
string str5 = ""; //人民币大写金额形式
int i; //循环变量
int j; //num的值乘以100的字符串长度
string ch1 = ""; //数字的汉语读法
string ch2 = ""; //数字位的汉字读法
int nzero = 0; //用来计算连续的零值是几个
int temp; //从原num值中取出的值
num = Math.Round(Math.Abs(num), 2); //将num取绝对值并四舍五入取2位小数
str4 = ((long)(num * 100)).ToString(); //将num乘100并转换成字符串形式
j = str4.Length; //找出最高位
if (j > 15) { return "溢出"; }
str2 = str2.Substring(15 - j); //取出对应位数的str2的值。如:200.55,j为5所以tr2=佰拾元角分
//循环取出每一位需要转换的值
for (i = 0; i < j; i++)
{
str3 = str4.Substring(i, 1); //取出需转换的某一位的值
temp = Convert.ToInt32(str3); //转换为数字
if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
{
//当所取位数不为元、万、亿、万亿上的数字时
if (str3 == "0")
{
ch1 = "";
ch2 = "";
nzero = nzero + 1;
}
else
{
if (str3 != "0" && nzero != 0)
{
ch1 = "零" + str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
ch1 = str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
}
}
else
{
//该位是万亿,亿,万,元位等关键位
if (str3 != "0" && nzero != 0)
{
ch1 = "零" + str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
if (str3 != "0" && nzero == 0)
{
ch1 = str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
if (str3 == "0" && nzero >= 3)
{
ch1 = "";
ch2 = "";
nzero = nzero + 1;
}
else
{
if (j >= 11)
{
ch1 = "";
nzero = nzero + 1;
}
else
{
ch1 = "";
ch2 = str2.Substring(i, 1);
nzero = nzero + 1;
}
}
}
}
}
if (i == (j - 11) || i == (j - 3))
{
//如果该位是亿位或元位,则必须写上
ch2 = str2.Substring(i, 1);
}
str5 = str5 + ch1 + ch2;
if (i == j - 1 && str3 == "0")
{
//最后一位(分)为0时,加上“整”
str5 = str5 + '整';
}
}
if (num == 0)
{
str5 = "零元整";
}
return str5;
}
#endregion
///
/// 去除选择框多选项中请选择
///
///
///
public static string[] RemoveDropDownListNull(string[] selectedValueArray)
{
List str = new List();
foreach (var item in selectedValueArray)
{
if (item != BLL.Const._Null)
{
str.Add(item);
}
}
return str.ToArray();
}
public static string GetStringByArray(string[] array)
{
string str = string.Empty;
foreach (var item in array)
{
if (item != BLL.Const._Null)
{
str += item + ",";
}
}
if (!string.IsNullOrEmpty(str))
{
str = str.Substring(0, str.LastIndexOf(","));
}
return str;
}
///
/// 将IEnumerable类型的集合转换为DataTable类型
///
///
///
///
public static DataTable LINQToDataTable(IEnumerable varlist)
{
//定义要返回的DataTable对象
DataTable dtReturn = new DataTable();
// 保存列集合的属性信息数组
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;//安全性检查
//循环遍历集合,使用反射获取类型的属性信息
foreach (T rec in varlist)
{
//使用反射获取T类型的属性信息,返回一个PropertyInfo类型的集合
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
//循环PropertyInfo数组
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;//得到属性的类型
//如果属性为泛型类型
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{ //获取泛型类型的参数
colType = colType.GetGenericArguments()[0];
}
//将类型的属性名称与属性类型作为DataTable的列数据
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
//新建一个用于添加到DataTable中的DataRow对象
DataRow dr = dtReturn.NewRow();
//循环遍历属性集合
foreach (PropertyInfo pi in oProps)
{ //为DataRow中的指定列赋值
dr[pi.Name] = pi.GetValue(rec, null) == null ?
DBNull.Value : pi.GetValue(rec, null);
}
//将具有结果值的DataRow添加到DataTable集合中
dtReturn.Rows.Add(dr);
}
return dtReturn;//返回DataTable对象
}
///
/// 将DataTable类型转换为IEnumerable类型的集合
///
///
///
///
public static List TableToEntity(DataTable dt) where T : class, new()
{
Type type = typeof(T);
List list = new List();
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = type.GetProperties();
T entity = new T();
foreach (PropertyInfo p in pArray)
{
if (string.IsNullOrEmpty(row[p.Name].ToString()))
{
p.SetValue(entity, "", null);
continue;
}
if (row[p.Name] is Int64)
{
p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
continue;
}
p.SetValue(entity, row[p.Name], null);
}
list.Add(entity);
}
return list;
}
public static DataTable ToDataTable(this T[] entities)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo propInfo in properties)
{
dataTable.Columns.Add(propInfo.Name, propInfo.PropertyType);
}
foreach (T entity in entities)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
///
/// 在设定的数值内产生随机数的数量
///
/// 随机数的数量
/// 随机数的最小值
/// 随机数的最大值
///
public static int[] GetRandomNum(int num, int minValue, int maxValue)
{
if ((maxValue + 1 - minValue - num < 0))
maxValue += num - (maxValue + 1 - minValue);
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
int[] arrNum = new int[num];
int tmp = 0;
StringBuilder sb = new StringBuilder(num * maxValue.ToString().Trim().Length);
for (int i = 0; i <= num - 1; i++)
{
tmp = ra.Next(minValue, maxValue);
while (sb.ToString().Contains("#" + tmp.ToString().Trim() + "#"))
tmp = ra.Next(minValue, maxValue + 1);
arrNum[i] = tmp;
sb.Append("#" + tmp.ToString().Trim() + "#");
}
return arrNum;
}
///
/// 根据第一页和第二页行数及总记录数,确定需要打印几页
///
/// 第一页行数
/// 第二页行数
/// 总记录数
///
public static int GetPagesCountByPageSize(int pageSize1, int pageSize2, int count)
{
int pagesCount = 0;
if (pageSize1 >= count) //总记录数小于等于第一页行数
{
pagesCount = 1;
}
else if (count > pageSize1 && count <= (pageSize1 + pageSize2)) //总记录数大于第一页行数且小于等于第一页加第二页总行数
{
pagesCount = 2;
}
else //总记录数大于第一页加第二页总行数
{
int lastCount = count - pageSize1;
decimal c = Convert.ToDecimal(Math.Round(Convert.ToDecimal(lastCount) / Convert.ToDecimal(pageSize2), 2));
if (c.ToString().IndexOf(".") > 0 && c.ToString().Substring(c.ToString().IndexOf("."), c.ToString().Length - c.ToString().IndexOf(".")) != ".00")
{
string c1 = c.ToString().Substring(0, c.ToString().IndexOf("."));
pagesCount = Convert.ToInt32(c1) + 1;
}
else
{
pagesCount = Convert.ToInt32(c);
}
pagesCount = pagesCount + 1;
}
return pagesCount;
}
///
/// 根据时间获取是上、下半年
///
///
public static string ReturnEvaluationResultByScore(decimal? score)
{
string value = string.Empty;
if (score.HasValue)
{
if (score >= 80)
{
value = "A级(合格)";
}
else if (score >= 71 && score <= 79)
{
value = "B级(基本合格)";
}
else if (score <= 70)
{
value = "C级(不合格)";
}
}
return value;
}
///
/// 输入文本转换数字类型
///
///
public static long? GetNewlong(string value)
{
if (!String.IsNullOrEmpty(value))
{
try
{
return long.Parse(value);
}
catch (Exception ex)
{
ErrLogInfo.WriteLog(string.Empty, ex);
return null;
}
}
else
{
return null;
}
}
///
///获取最大页数
///
/// 总数
/// 每页条数
///
public static int GetEndPageNumber(int pageTotal, int pagesize)
{
double aa = (pageTotal + pagesize - 1) / pagesize; //使用数据条数/每页显示条数,来获得最大页数,是double类型
return Convert.ToInt32(Math.Ceiling(aa)); //返回double类型取上限后的结果
}
///
/// 过滤空白行
///
///
///
public static DataTable FilterBlankLines(this DataTable dt)
{
DataView dv = dt.DefaultView;
string filterRule = "";
foreach (DataColumn col in dt.Columns)
{
filterRule += $"{col.ColumnName} <> '' or ";
}
filterRule = filterRule.Substring(0, filterRule.LastIndexOf("or"));
dv.RowFilter = $"({filterRule})";
return dv.ToTable();
}
public static IEnumerable QueryWithoutEmptyRow(Stream stream, bool useHeaderRow, string sheetName, ExcelType excelType, string startCell, IConfiguration configuration)
{
var rows = stream.Query(useHeaderRow, sheetName, excelType, startCell, configuration);
foreach (IDictionary row in rows)
{
if (row.Keys.Any(key => row[key] != null))
yield return row;
}
}
///
/// 用于Linq的去重,扩展方法需要放到静态类中
///
///
///
///
///
///
public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector)
{
HashSet seenKeys = new HashSet();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
public static string RequestGet(string Baseurl, string Token)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient(Baseurl);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("token", Token);
request.AddHeader("ClientId", SysConstSetService.ClientId);
request.AddHeader("OperationCode", Baseurl.Substring(Baseurl.LastIndexOf("/", StringComparison.Ordinal) + 1));
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
return response.Content;
}
public static string RequestPost(string Baseurl, string Token, string JsonBody)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient(Baseurl);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("token", Token);
request.AddHeader("ClientId", SysConstSetService.ClientId);
request.AddHeader("OperationCode", Baseurl.Substring(Baseurl.LastIndexOf("/", StringComparison.Ordinal) + 1));
if (!string.IsNullOrEmpty(JsonBody))
{
request.AddJsonBody(JsonBody);
}
IRestResponse response = client.Execute(request);
return response.Content;
}
public static string RequestPost(string Baseurl, Dictionary Token, string JsonBody)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient(Baseurl);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
foreach (var item in Token)
{
request.AddHeader(item.Key, item.Value);
}
request.AddHeader("ClientId", SysConstSetService.ClientId);
request.AddHeader("OperationCode", Baseurl.Substring(Baseurl.LastIndexOf("/", StringComparison.Ordinal) + 1));
if (!string.IsNullOrEmpty(JsonBody))
{
request.AddJsonBody(JsonBody);
}
IRestResponse response = client.Execute(request);
return response.Content;
}
public static string RequestGet(string Baseurl, Dictionary Token)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient(Baseurl);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
foreach (var item in Token)
{
request.AddHeader(item.Key, item.Value);
}
request.AddHeader("ClientId", SysConstSetService.ClientId);
request.AddHeader("OperationCode", Baseurl.Substring(Baseurl.LastIndexOf("/", StringComparison.Ordinal) + 1));
IRestResponse response = client.Execute(request);
return response.Content;
}
///
/// 根据星期几返回值
///
///
public static string GetWeekDay(string value)
{
if (!String.IsNullOrEmpty(value))
{
if (value == "Sunday")
{
return "日";
}
else if (value == "Monday")
{
return "一";
}
else if (value == "Tuesday")
{
return "二";
}
else if (value == "Wednesday")
{
return "三";
}
else if (value == "Thursday")
{
return "四";
}
else if (value == "Friday")
{
return "五";
}
else if (value == "Saturday")
{
return "六";
}
else
{
return "";
}
}
else
{
return "";
}
}
///
/// 将List 中的数据平均拆分为多个List
///
///
/// 原始List
/// 拆分后的子列表数量
///
/**们首先计算出每个子列表的大小chunkSize和余数remainder。然后,使用一个循环来创建并添加子列表到splitLists中。
在每次迭代中,我们根据当前索引是否小于余数来确定子列表的大小。如果小于余数,则将子列表大小加1,以确保最后一个子列表包含余数部分。
最后,我们更新startIndex以便正确获取下一个子列表的元素范围*/
public static List> SplitList(List originalList, int numberOfLists)
{
List> splitLists = new List>();
int chunkSize = originalList.Count / numberOfLists;
int remainder = originalList.Count % numberOfLists;
int startIndex = 0;
for (int i = 0; i < numberOfLists; i++)
{
int sublistSize = chunkSize + (i < remainder ? 1 : 0);
List sublist = originalList.GetRange(startIndex, sublistSize);
splitLists.Add(sublist);
startIndex += sublistSize;
}
return splitLists;
}
public static int GetWeekOfYear(DateTime dtWeek)
{
System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
int weekOfYear = gc.GetWeekOfYear(dtWeek, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
return weekOfYear;
}
private static string _SGGLApiUrl;
public static string SGGLApiUrl
{
get
{
var sysSet = (from x in DB.Sys_Const where x.ConstText == "程序接口访问地址" select x).ToList().FirstOrDefault();
if (sysSet != null)
{
_SGGLApiUrl = sysSet.ConstValue;
}
else
{
_SGGLApiUrl = "";
}
return _SGGLApiUrl;
}
set { _SGGLApiUrl = value; }
}
}
}