using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Telerik.Web.UI;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
using System.Threading;
using System.Configuration;
namespace VRS
{
///
/// 接口状态码
///
public enum APICode
{
///
/// 成功
///
Success,
///
/// 失败
///
Fail
}
public abstract class BasePage : System.Web.UI.Page
{
///
/// md5密码加密
///
///
///
public static string GetMD5(string passWord)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] bt = Encoding.Default.GetBytes(passWord);//将待加密字符转为 字节型数组
byte[] resualt = md5.ComputeHash(bt);//将字节数组转为加密的字节数组
string pwds = BitConverter.ToString(resualt).Replace("-", "");
passWord = pwds;
return passWord;
}
#region 根据属性名称获取值
///
/// 根据属性名称获取值
///
/// 对象实例
/// 属性名
/// object
private static object GetValueByStrAttribute(object obj, string strAttribute)
{
System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
if (null == propertyInfoName)
{
throw new Exception("属性名:" + strAttribute + " 不存在!");
}
return propertyInfoName.GetValue(obj, null);
}
#endregion
#region 根据属性名称设置值
///
/// 根据属性名称设置值
///
/// 对象实例
/// 属性名
/// 值
public static void SetValueByStrAttribute(object obj, string strAttribute, object value)
{
System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
if (null != propertyInfoName)
{
if (propertyInfoName.PropertyType == typeof(Nullable) || propertyInfoName.PropertyType == typeof(Int32))
{
int int_value = 0;
if (int.TryParse(value.ToString(), out int_value))
{
propertyInfoName.SetValue(obj, int_value, null);
}
}
else if (propertyInfoName.PropertyType == typeof(Nullable) || propertyInfoName.PropertyType == typeof(decimal))
{
decimal decimal_value = 0;
if (decimal.TryParse(value.ToString(), out decimal_value))
{
propertyInfoName.SetValue(obj, decimal_value, null);
}
propertyInfoName.SetValue(obj, decimal_value, null);
}
else
{
propertyInfoName.SetValue(obj, value, null);
}
}
}
#endregion
///
/// 验证手机号码是否符合标准
///
///
///
public static bool IsMobile(string mobile)
{
return System.Text.RegularExpressions.Regex.IsMatch(mobile, @"^(13|14|15|16|17|18|19)\d{9}$");
}
public static Dictionary DicKsMode()
{
var DicSysType = ConfigurationManager.AppSettings["KsMode"];
var array1 = DicSysType.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dic = new Dictionary();
for (var i = 0; i < array1.Length; i++)
{
var sub = array1[i].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var value = sub[0];
var text = sub[1];
dic.Add(value, text);
}
return dic;
}
protected void BindRole(RadDropDownList control, string defaultItem = null)
{
var dic = DicRole();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
foreach (var item in dic)
{
control.Items.Add(new DropDownListItem(item.Value, item.Key));
}
}
///
/// 是否管理员
///
///
///
public static bool isAdmin(string user_role_key)
{
var dic = DicRole();
if (dic.ContainsKey(user_role_key))
{
string role_name = dic[user_role_key];
if(role_name.Contains("管理员"))
{
return true;
}
}
return false;
}
private static Dictionary _dicRole;
public static Dictionary DicRole()
{
if (null == _dicRole)
{
var DicSysType = ConfigurationManager.AppSettings["RoleMode"];
var array1 = DicSysType.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var dic = new Dictionary();
for (var i = 0; i < array1.Length; i++)
{
var sub = array1[i].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var value = sub[0];
var text = sub[1];
dic.Add(value, text);
}
_dicRole = dic;
}
return _dicRole;
}
///
/// 是否IP地址
///
///
///
public static bool IsIP(string IP)
{
return System.Text.RegularExpressions.Regex.IsMatch(IP, @"^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$");
}
public static int GetPosition()
{
return (int)long.Parse(DateTime.Now.ToString("yMdHms"));
}
///
/// 新ID
///
///
///
public static string GetNewId(string flag)
{
string NewId = string.Format("{0}{1}", flag.ToUpper(), DateTime.Now.ToString("yMdHmsffff"));
return NewId;
}
public static string GetRandom()
{
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var value = array.OrderBy(s => Guid.NewGuid()).First() + array.OrderBy(s => Guid.NewGuid()).First() + array.OrderBy(s => Guid.NewGuid()).First() + array.OrderBy(s => Guid.NewGuid()).First();
return value;
}
public static string GetRandomSeed()
{
Random r = new Random();
byte[] buffer = Guid.NewGuid().ToByteArray();
int iSeed = BitConverter.ToInt32(buffer, 0);
r = new Random(iSeed);
var rtn = r.Next(0, 10000).ToString().PadLeft(4, '0');
return rtn;
}
public static int GetRandomSeed(int min,int max)
{
Random r = new Random();
byte[] buffer = Guid.NewGuid().ToByteArray();
int iSeed = BitConverter.ToInt32(buffer, 0);
r = new Random(iSeed);
var rtn = r.Next(min, max + 1);
return rtn;
}
public static string GetNewId()
{
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var NewId = string.Format("{0}{1}{2}{3}{4}{5}", DateTime.Now.ToString("yyyyMMddHHmmssff"), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First());
return NewId;
}
///
/// DateTime时间格式转换为10位不带毫秒的Unix时间戳
///
/// Unix时间戳格式
public static long ConvertDateTimeInt(DateTime dt)
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
return (long)(dt - startTime).TotalSeconds;
}
private static Object Lockobj = new object();
///
/// 获取房间号
///
///
public static string GetId()
{
lock (Lockobj)
{
Thread.Sleep(1000);
var val = ConvertDateTimeInt(DateTime.Now);
return val.ToString();
}
}
public static int GetIntWidth(int count)
{
return Math.Abs(count).ToString().Length;
}
public static string GetNewId(int pos, int count)
{
var array = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var width = GetIntWidth(count);
var position = pos.ToString().PadLeft(width, '0');
var NewId = string.Format("{0}{1}{2}{3}{4}{5}", DateTime.Now.ToString("yyyyMMddHHmmssff"), position, array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First(), array.OrderBy(s => Guid.NewGuid()).First());
return NewId;
}
///
/// 获取基础设备状态
///
///
public static Dictionary GetBaseDeviceState()
{
var devicetype = System.Configuration.ConfigurationManager.AppSettings["DeviceState"];
Dictionary dic = new Dictionary();
if (!string.IsNullOrEmpty(devicetype))
{
var array = devicetype.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
var sub = item.Split(':');
var key = int.Parse(sub[0]);
var value = sub[1];
dic.Add(key, value);
}
}
return dic;
}
/*
///
/// 绑定scene类型
///
///
///
protected void BindSceneType(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.mr_scene bll = new DataService.BLL.mr_scene();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.scene_name, item.id));
});
}
*/
/*
///
/// 绑定设备类型
///
///
///
protected void BindEquipMentType(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.mr_device_type bll = new DataService.BLL.mr_device_type();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.device_type_name, item.id));
});
}
*/
///
/// 绑定设备类型
///
///
///
protected void BindBasePatrolType(RadDropDownList control, string defaultItem = null)
{
var majors = GetBasePatrolType();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
foreach (var item in majors)
{
control.Items.Add(new DropDownListItem(item.Value, item.Key.ToString()));
}
}
/*
///
/// 绑定设备类型
///
///
///
protected void BindScene(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.mr_scene bll = new DataService.BLL.mr_scene();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.scene_name, item.id));
});
}
*/
///
/// 绑定存在单位
///
///
///
protected void BindExistsUnits( RadComboBox control, string defaultItem = null)
{
DataService.BLL.admin_user bll = new DataService.BLL.admin_user();
var majors = bll.GetUnitValues();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new RadComboBoxItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new RadComboBoxItem(item, item));
});
}
///
/// 获取基础设备状态
///
///
public static Dictionary GetBasePatrolType()
{
var devicetype = System.Configuration.ConfigurationManager.AppSettings["PatrolType"];
Dictionary dic = new Dictionary();
if (!string.IsNullOrEmpty(devicetype))
{
var array = devicetype.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
var sub = item.Split(':');
var key = int.Parse(sub[0]);
var value = sub[1];
dic.Add(key, value);
}
}
return dic;
}
///
/// 获取基础设备类型
///
///
public static List GetBaseDeviceType()
{
var devicetype = System.Configuration.ConfigurationManager.AppSettings["DeviceType"];
List list = new List();
if (!string.IsNullOrEmpty(devicetype))
{
var array = devicetype.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
list.AddRange(array);
}
return list;
}
///
/// 绑定软件类型
///
///
///
protected void BindSoft(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.admin_soft bll = new DataService.BLL.admin_soft();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.soft_name, item.soft_id));
});
}
///
/// 绑定专业
///
///
///
protected void BindMajors(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.admin_major bll = new DataService.BLL.admin_major();
var majors = bll.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.major_name, item.major_id));
});
}
///
/// 绑定专业科目
///
/// 专业id
///
///
protected void BindMajorSubject(string major_id, RadDropDownList control, string defaultItem = null)
{
DataService.BLL.admin_subject bll = new DataService.BLL.admin_subject();
var majors = bll.GetModelList(" major_id='" + major_id + "'");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.subject_name, item.subject_id));
});
}
public void BindYears(RadDropDownList control, string defaultItem = null)
{
var dpYear = control;
var year = DateTime.Now.Year;
dpYear.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
for (int i = 0; i < 20; i++)
{
var currentYear = (year - i).ToString();
dpYear.Items.Add(new DropDownListItem(currentYear, currentYear));
}
}
/*
///
/// 绑定专业
///
///
///
protected void BindMajors(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.base_major bllMajor = new DataService.BLL.base_major();
var majors = bllMajor.GetModelList("");
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(major =>
{
control.Items.Add(new DropDownListItem(major.major, major.major));
});
if (majors.Count > 0)
{
control.SelectedIndex = 1;
}
}
*/
///
/// 绑定设备类型
///
/// 父类型id
///
///
protected void BindDeviceType(string parent_id, RadDropDownList control, string defaultItem = null)
{
DataService.BLL.pro_type_manage bll = new DataService.BLL.pro_type_manage();
var majors = bll.GetModelList(string.Format(" parent_id = '{0}' ", parent_id));
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.type_name, item.type_name));
});
}
/*
///
/// 绑定设备类型
///
///
///
protected void BindProDeviceType(RadDropDownList control, string defaultItem = null)
{
DataService.BLL.pro_device_type bll = new DataService.BLL.pro_device_type();
var majors = bll.GetModelList("").OrderBy(s => s.type_name_zh).ToList();
control.Items.Clear();
if (null != defaultItem)
control.Items.Add(new DropDownListItem(defaultItem, defaultItem));
majors.ForEach(item =>
{
control.Items.Add(new DropDownListItem(item.type_name_zh, item.id));
});
}
*/
///
/// 根据名称获取类型
///
///
protected DataService.Model.pro_type_manage GetTypeByName(string typeName)
{
DataService.BLL.pro_type_manage bllType = new DataService.BLL.pro_type_manage();
var models = bllType.GetModelList(string.Format(" type_name = '{0}' ", typeName));
if (models.Any())
return models.First();
else
{
var model = new DataService.Model.pro_type_manage { type_id = Guid.NewGuid().ToString(), type_name = typeName };
if (bllType.Add(model))
return model;
}
return null;
}
///
/// 获取将对象转换为的JSON字符串
///
///
///
protected string GetJson(object dataObj)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(dataObj);
}
///
/// 获取带状态码的JSON字符串
///
///
///
///
protected string GetJsonWithCode(APICode code, object dataObj)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new { code = (int)code, state = code.ToString(), data = dataObj });
}
public static bool SaveFile(UploadedFile fileUpload, HttpContext httpContext, out string filePath)
{
string dirPath = httpContext.Server.MapPath("~/Upload/");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
//string fileName = Guid.NewGuid().ToString() + fileUpload.GetExtension();
string fileName = GetId()+ fileUpload.GetExtension();
string savePath = dirPath + fileName;
fileUpload.SaveAs(savePath);
filePath = "/Upload/" + fileName;
return true;
}
public static bool SaveFileWithName(UploadedFile fileUpload, HttpContext httpContext,string Name, out string filePath)
{
string dirPath = httpContext.Server.MapPath("~/Upload/");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
string fileName = Name + fileUpload.GetExtension();
string savePath = dirPath + fileName;
fileUpload.SaveAs(savePath);
filePath = "/Upload/" + fileName;
return true;
}
public static bool SaveFile(UploadedFile fileUpload, HttpContext httpContext, out string filePath, out string originalName)
{
string dirPath = httpContext.Server.MapPath("~/Upload/");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
originalName = fileUpload.FileName;
var index = originalName.LastIndexOf(".");
var prefix = originalName.Substring(0, index);
string fileName = prefix + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileUpload.GetExtension();
string savePath = dirPath + fileName;
fileUpload.SaveAs(savePath);
filePath = "/Upload/" + fileName;
return true;
}
///
/// 页面初始化
///
///
///
protected virtual void Page_Load(object sender, EventArgs e)
{
DataService.BLL.admin_user.load_login();
}
protected override void OnError(EventArgs e)
{
base.OnError(e);
var error = Server.GetLastError();
if (null != error)
{
write_log(error.ToString());
Response.Redirect("~/Util/Error.aspx?msg=" + error.Message);
}
}
///
/// 根据Web.Config中SystemName系统名称判断菜单是否显示
///
///
///
public static string menu_show_by_SystemName(string system_name)
{
var SystemName = System.Configuration.ConfigurationManager.AppSettings["SystemName"];
if (SystemName.ToUpper() == "ALL")
return "";
if (system_name == SystemName)
{
return "";
}
return "hidden";
}
///
/// 写日志
///
///
public static void write_log(string msg)
{
DateTime now = DateTime.Now;
HttpContext context = HttpContext.Current;
if (!Directory.Exists(context.Server.MapPath("/bin/logs/")))
{
Directory.CreateDirectory(context.Server.MapPath("/bin/logs/"));
}
StreamWriter sw = new StreamWriter(context.Server.MapPath("/bin/logs/" + now.ToString("yyyy-MM-dd") + ".txt"), true);
sw.Write("=============================================================\r\n" + now + "\r\n" + msg + "\r\n");
sw.Close();
}
public static void HttpGet(string url, Action callback, string Method = "GET")
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = Method;
req.ContentType = "application/json;charset=UTF-8";
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
callback(true, "", result);
}
catch (WebException ex)
{
//返回异常
var errorSr = new StreamReader(ex.Response.GetResponseStream());
string errMsg = errorSr.ReadToEnd();
Console.WriteLine(errMsg);
callback(false, errMsg, "");
}
}
public static DataTable ExcelToDataTable(string filePath, string sheetName, int startRow, bool isFirstRowColumn, bool cshz)
{
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int cellCount = 0;
// int startRow = 0;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(fs);
if (workbook != null)
{
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
if (cshz)
{
return null;
}
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(startRow);//第一行
int rowindex = 0; //搜索空行,并跳过
while (firstRow == null && rowindex < rowCount)
{
rowindex++;
firstRow = sheet.GetRow(rowindex);
} //如果全为空行则返回null值
if (rowindex == rowCount) return null;
cellCount = firstRow.LastCellNum;//列数
startRow = firstRow.RowNum;
// 构建datatable的列
if (isFirstRowColumn)
{
//如果第一行是列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.ToString() != null)
{
column = new DataColumn(cell.ToString());
dataTable.Columns.Add(column);
}
}
}
startRow++;
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + 1));
dataTable.Columns.Add(column);
}
}
// 填充行
for (int i = startRow; i <= rowCount; ++i)
{
row = sheet.GetRow(i);
if (row == null) continue;
cellCount = row.LastCellNum; //全文行之间的列数不一样的话,继续添加列
if (cellCount > dataTable.Columns.Count)
{
for (int c = dataTable.Columns.Count; c < cellCount; c++)
{
column = new DataColumn("column" + (c + 1));
dataTable.Columns.Add(column);
}
}
dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
// CellType(Unknown = -1, Numeric = 0, String = 1, Formula = 2, Blank = 3, Boolean = 4, Error = 5,)
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
// 对时间格式(2015.12.5、2015 / 12 / 5、2015 - 12 - 5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58)
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
return dataTable;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return null;
}
}
}
}