添加项目文件。
This commit is contained in:
28
WaterCloud.Code/Util/AsyncTaskHelper.cs
Normal file
28
WaterCloud.Code/Util/AsyncTaskHelper.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class AsyncTaskHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 开始异步任务
|
||||
/// </summary>
|
||||
/// <param name="action"></param>
|
||||
public static void StartTask(Action action)
|
||||
{
|
||||
try
|
||||
{
|
||||
Action newAction = () =>
|
||||
{ };
|
||||
newAction += action;
|
||||
Task task = new Task(newAction);
|
||||
task.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
124
WaterCloud.Code/Util/CommonEnum.cs
Normal file
124
WaterCloud.Code/Util/CommonEnum.cs
Normal file
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public enum StatusEnum
|
||||
{
|
||||
[Description("启用")]
|
||||
Yes = 1,
|
||||
|
||||
[Description("禁用")]
|
||||
No = 0
|
||||
}
|
||||
|
||||
public enum IsEnum
|
||||
{
|
||||
[Description("是")]
|
||||
Yes = 1,
|
||||
|
||||
[Description("否")]
|
||||
No = 0
|
||||
}
|
||||
|
||||
public enum NeedEnum
|
||||
{
|
||||
[Description("不需要")]
|
||||
NotNeed = 0,
|
||||
|
||||
[Description("需要")]
|
||||
Need = 1
|
||||
}
|
||||
|
||||
public enum OperateStatusEnum
|
||||
{
|
||||
[Description("失败")]
|
||||
Fail = 0,
|
||||
|
||||
[Description("成功")]
|
||||
Success = 1
|
||||
}
|
||||
|
||||
public enum UploadFileType
|
||||
{
|
||||
[Description("头像")]
|
||||
Portrait = 1,
|
||||
|
||||
[Description("新闻图片")]
|
||||
News = 2,
|
||||
|
||||
[Description("导入的文件")]
|
||||
Import = 10
|
||||
}
|
||||
|
||||
public enum PlatformEnum
|
||||
{
|
||||
[Description("Web后台")]
|
||||
Web = 1,
|
||||
|
||||
[Description("WebApi")]
|
||||
WebApi = 2
|
||||
}
|
||||
|
||||
public enum PayStatusEnum
|
||||
{
|
||||
[Description("未知")]
|
||||
Unknown = 0,
|
||||
|
||||
[Description("已支付")]
|
||||
Success = 1,
|
||||
|
||||
[Description("转入退款")]
|
||||
Refund = 2,
|
||||
|
||||
[Description("未支付")]
|
||||
NotPay = 3,
|
||||
|
||||
[Description("已关闭")]
|
||||
Closed = 4,
|
||||
|
||||
[Description("已撤销(付款码支付)")]
|
||||
Revoked = 5,
|
||||
|
||||
[Description("用户支付中(付款码支付)")]
|
||||
UserPaying = 6,
|
||||
|
||||
[Description("支付失败(其他原因,如银行返回失败)")]
|
||||
PayError = 7
|
||||
}
|
||||
|
||||
public class EnumHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取枚举列表
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<int, string> EnumToDic<T>()
|
||||
{
|
||||
Dictionary<int, string> list = new Dictionary<int, string>();
|
||||
foreach (var e in Enum.GetValues(typeof(T)))
|
||||
{
|
||||
list.Add(Convert.ToInt32(e), e.GetDescriptionByEnum<T>());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取枚举列表
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns></returns>
|
||||
public static List<string> EnumToList<T>()
|
||||
{
|
||||
List<string> list = new List<string>();
|
||||
|
||||
foreach (var e in Enum.GetValues(typeof(T)))
|
||||
{
|
||||
list.Add(e.GetDescriptionByEnum<T>());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
150
WaterCloud.Code/Util/ComputerHelper.cs
Normal file
150
WaterCloud.Code/Util/ComputerHelper.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ComputerHelper
|
||||
{
|
||||
public static ComputerInfo GetComputerInfo()
|
||||
{
|
||||
ComputerInfo computerInfo = new ComputerInfo();
|
||||
try
|
||||
{
|
||||
MemoryMetricsClient client = new MemoryMetricsClient();
|
||||
MemoryMetrics memoryMetrics = client.GetMetrics();
|
||||
computerInfo.TotalRAM = Math.Ceiling(memoryMetrics.Total / 1024).ToString() + " GB";
|
||||
computerInfo.RAMRate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total).ToString();
|
||||
computerInfo.CPURate = Math.Ceiling(GetCPURate().ToDouble()).ToString();
|
||||
computerInfo.RunTime = GetRunTime();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return computerInfo;
|
||||
}
|
||||
|
||||
public static bool IsUnix()
|
||||
{
|
||||
var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
|
||||
return isUnix;
|
||||
}
|
||||
|
||||
public static string GetCPURate()
|
||||
{
|
||||
string cpuRate = string.Empty;
|
||||
if (IsUnix())
|
||||
{
|
||||
string output = ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
|
||||
cpuRate = output.Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage");
|
||||
cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
|
||||
}
|
||||
return cpuRate;
|
||||
}
|
||||
|
||||
public static string GetRunTime()
|
||||
{
|
||||
string runTime = string.Empty;
|
||||
try
|
||||
{
|
||||
if (IsUnix())
|
||||
{
|
||||
string output = ShellHelper.Bash("uptime -s");
|
||||
output = output.Trim();
|
||||
runTime = Extensions.FormatTime((DateTime.Now - output.ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
|
||||
}
|
||||
else
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "OS get LastBootUpTime/Value");
|
||||
string[] outputArr = output.Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
if (outputArr.Length == 2)
|
||||
{
|
||||
runTime = Extensions.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return runTime;
|
||||
}
|
||||
}
|
||||
|
||||
public class MemoryMetrics
|
||||
{
|
||||
public double Total { get; set; }
|
||||
public double Used { get; set; }
|
||||
public double Free { get; set; }
|
||||
}
|
||||
|
||||
public class MemoryMetricsClient
|
||||
{
|
||||
public MemoryMetrics GetMetrics()
|
||||
{
|
||||
if (ComputerHelper.IsUnix())
|
||||
{
|
||||
return GetUnixMetrics();
|
||||
}
|
||||
return GetWindowsMetrics();
|
||||
}
|
||||
|
||||
private MemoryMetrics GetWindowsMetrics()
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
|
||||
|
||||
var lines = output.Trim().Split("\n");
|
||||
var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var metrics = new MemoryMetrics();
|
||||
metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
|
||||
metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
|
||||
metrics.Used = metrics.Total - metrics.Free;
|
||||
|
||||
return metrics;
|
||||
}
|
||||
|
||||
private MemoryMetrics GetUnixMetrics()
|
||||
{
|
||||
string output = ShellHelper.Bash("free -m");
|
||||
|
||||
var lines = output.Split("\n");
|
||||
var memory = lines[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var metrics = new MemoryMetrics();
|
||||
metrics.Total = double.Parse(memory[1]);
|
||||
metrics.Used = double.Parse(memory[2]);
|
||||
metrics.Free = double.Parse(memory[3]);
|
||||
|
||||
return metrics;
|
||||
}
|
||||
}
|
||||
|
||||
public class ComputerInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// CPU使用率
|
||||
/// </summary>
|
||||
public string CPURate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 总内存
|
||||
/// </summary>
|
||||
public string TotalRAM { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 内存使用率
|
||||
/// </summary>
|
||||
public string RAMRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 系统运行时间
|
||||
/// </summary>
|
||||
public string RunTime { get; set; }
|
||||
}
|
||||
}
|
||||
140
WaterCloud.Code/Util/ConcurrentList.cs
Normal file
140
WaterCloud.Code/Util/ConcurrentList.cs
Normal file
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ConcurrentList<T> : IList<T>
|
||||
{
|
||||
protected static object _lock = new object();
|
||||
protected List<T> _interalList = new List<T>();
|
||||
|
||||
public IEnumerator<T> GetEnumerator()
|
||||
{
|
||||
return Clone().GetEnumerator();
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return Clone().GetEnumerator();
|
||||
}
|
||||
|
||||
public int Count
|
||||
{ get { return _interalList.Count; } }
|
||||
|
||||
public bool IsReadOnly
|
||||
{ get { return false; } }
|
||||
|
||||
public T this[int index]
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _interalList[index];
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList[index] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> Clone()
|
||||
{
|
||||
List<T> newList = new List<T>();
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.ForEach(x => newList.Add(x));
|
||||
}
|
||||
return newList;
|
||||
}
|
||||
|
||||
public int IndexOf(T item)
|
||||
{
|
||||
return _interalList.IndexOf(item);
|
||||
}
|
||||
|
||||
public void Insert(int index, T item)
|
||||
{
|
||||
_interalList.Insert(index, item);
|
||||
}
|
||||
|
||||
public void RemoveAt(int index)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.RemoveAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(T item)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRange(IEnumerable<T> list)
|
||||
{
|
||||
foreach (T item in list)
|
||||
{
|
||||
Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_interalList.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
public bool Contains(T item)
|
||||
{
|
||||
return _interalList.Contains(item);
|
||||
}
|
||||
|
||||
public void CopyTo(T[] array, int arrayIndex)
|
||||
{
|
||||
_interalList.CopyTo(array, arrayIndex);
|
||||
}
|
||||
|
||||
public bool Remove(T item)
|
||||
{
|
||||
if (item == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
lock (_lock)
|
||||
{
|
||||
return _interalList.Remove(item);
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveAll(Predicate<T> match)
|
||||
{
|
||||
if (match == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
Contract.Ensures(Contract.Result<int>() >= 0);
|
||||
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
|
||||
Contract.EndContractBlock();
|
||||
|
||||
foreach (T t in Clone())
|
||||
{
|
||||
if (match(t))
|
||||
{
|
||||
Remove(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
128
WaterCloud.Code/Util/DataTableHelper.cs
Normal file
128
WaterCloud.Code/Util/DataTableHelper.cs
Normal file
@@ -0,0 +1,128 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class DataTableHelper
|
||||
{
|
||||
public static DataTable ListToDataTable<T>(List<T> entitys)
|
||||
{
|
||||
//检查实体集合不能为空
|
||||
if (entitys == null || entitys.Count < 1)
|
||||
{
|
||||
throw new Exception("需转换的集合为空");
|
||||
}
|
||||
//取出第一个实体的所有Propertie
|
||||
Type entityType = entitys[0].GetType();
|
||||
PropertyInfo[] entityProperties = entityType.GetProperties();
|
||||
|
||||
//生成DataTable的structure
|
||||
//生产代码中,应将生成的DataTable结构Cache起来,此处略
|
||||
DataTable dt = new DataTable();
|
||||
for (int i = 0; i < entityProperties.Length; i++)
|
||||
{
|
||||
dt.Columns.Add(entityProperties[i].Name);
|
||||
}
|
||||
//将所有entity添加到DataTable中
|
||||
foreach (object entity in entitys)
|
||||
{
|
||||
//检查所有的的实体都为同一类型
|
||||
if (entity.GetType() != entityType)
|
||||
{
|
||||
throw new Exception("要转换的集合元素类型不一致");
|
||||
}
|
||||
object[] entityValues = new object[entityProperties.Length];
|
||||
for (int i = 0; i < entityProperties.Length; i++)
|
||||
{
|
||||
entityValues[i] = entityProperties[i].GetValue(entity, null);
|
||||
}
|
||||
dt.Rows.Add(entityValues);
|
||||
}
|
||||
return dt;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// List过滤
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="entitys"></param>
|
||||
/// <param name="list"></param>
|
||||
/// <returns></returns>
|
||||
public static List<T> ListFilter<T>(List<T> entitys, List<string> list)
|
||||
{
|
||||
//检查实体集合不能为空
|
||||
if (entitys == null || entitys.Count < 1)
|
||||
{
|
||||
throw new Exception("需转换的集合为空");
|
||||
}
|
||||
//取出第一个实体的所有Propertie
|
||||
Type entityType = entitys[0].GetType();
|
||||
PropertyInfo[] entityProperties = entityType.GetProperties();
|
||||
|
||||
//将所有entity过滤
|
||||
foreach (object entity in entitys)
|
||||
{
|
||||
//检查所有的的实体都为同一类型
|
||||
if (entity.GetType() != entityType)
|
||||
{
|
||||
throw new Exception("要转换的集合元素类型不一致");
|
||||
}
|
||||
for (int i = 0; i < entityProperties.Length; i++)
|
||||
{
|
||||
if (!list.Contains(entityProperties[i].Name))
|
||||
{
|
||||
entityProperties[i].SetValue(entity, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
return entitys;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DataTable转成List
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="dt"></param>
|
||||
/// <returns></returns>
|
||||
public static List<T> ToDataList<T>(this DataTable dt)
|
||||
{
|
||||
var list = new List<T>();
|
||||
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
|
||||
foreach (DataRow item in dt.Rows)
|
||||
{
|
||||
T s = Activator.CreateInstance<T>();
|
||||
for (int i = 0; i < dt.Columns.Count; i++)
|
||||
{
|
||||
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
|
||||
if (info != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Convert.IsDBNull(item[i]))
|
||||
{
|
||||
object v = null;
|
||||
if (info.PropertyType.ToString().Contains("System.Nullable"))
|
||||
{
|
||||
v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
|
||||
}
|
||||
else
|
||||
{
|
||||
v = Convert.ChangeType(item[i], info.PropertyType);
|
||||
}
|
||||
info.SetValue(s, v, null);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
list.Add(s);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
697
WaterCloud.Code/Util/FileHelper.cs
Normal file
697
WaterCloud.Code/Util/FileHelper.cs
Normal file
@@ -0,0 +1,697 @@
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class FileHelper
|
||||
{
|
||||
public static string MapPath(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string rootdir = Directory.GetCurrentDirectory();
|
||||
//DirectoryInfo Dir = Directory.GetParent(rootdir);
|
||||
//string root = Dir.Parent.Parent.Parent.FullName;
|
||||
return rootdir + path;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
#region 获取文件到集合中
|
||||
|
||||
/// <summary>
|
||||
/// 读取指定位置文件列表到集合中
|
||||
/// </summary>
|
||||
/// <param name="path">指定路径</param>
|
||||
/// <returns></returns>
|
||||
public static DataTable GetFileTable(string path)
|
||||
{
|
||||
DataTable dt = new DataTable();
|
||||
dt.Columns.Add("name", typeof(string));
|
||||
dt.Columns.Add("ext", typeof(string));
|
||||
dt.Columns.Add("size", typeof(long));
|
||||
dt.Columns.Add("time", typeof(DateTime));
|
||||
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
DirectoryInfo dirinfo = new DirectoryInfo(path);
|
||||
FileInfo fi;
|
||||
DirectoryInfo dir;
|
||||
string FileName, FileExt;
|
||||
long FileSize = 0;
|
||||
DateTime FileModify;
|
||||
try
|
||||
{
|
||||
foreach (FileSystemInfo fsi in dirinfo.GetFileSystemInfos())
|
||||
{
|
||||
FileName = string.Empty;
|
||||
FileExt = string.Empty;
|
||||
if (fsi is FileInfo)
|
||||
{
|
||||
fi = (FileInfo)fsi;
|
||||
//获取文件名称
|
||||
FileName = fi.Name;
|
||||
//获取文件扩展名
|
||||
FileExt = fi.Extension;
|
||||
//获取文件大小
|
||||
FileSize = fi.Length;
|
||||
//获取文件最后修改时间
|
||||
FileModify = fi.LastWriteTime;
|
||||
}
|
||||
else
|
||||
{
|
||||
dir = (DirectoryInfo)fsi;
|
||||
//获取目录名
|
||||
FileName = dir.Name;
|
||||
//获取目录最后修改时间
|
||||
FileModify = dir.LastWriteTime;
|
||||
//设置目录文件为文件夹
|
||||
FileExt = "文件夹";
|
||||
}
|
||||
DataRow dr = dt.NewRow();
|
||||
dr["name"] = FileName;
|
||||
dr["ext"] = FileExt;
|
||||
dr["size"] = FileSize;
|
||||
dr["time"] = FileModify;
|
||||
dt.Rows.Add(dr);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return dt;
|
||||
}
|
||||
|
||||
#endregion 获取文件到集合中
|
||||
|
||||
#region 检测指定路径是否存在
|
||||
|
||||
/// <summary>
|
||||
/// 检测指定路径是否存在
|
||||
/// </summary>
|
||||
/// <param name="path">目录的绝对路径</param>
|
||||
public static bool IsExistDirectory(string path)
|
||||
{
|
||||
return Directory.Exists(path);
|
||||
}
|
||||
|
||||
#endregion 检测指定路径是否存在
|
||||
|
||||
#region 检测指定文件是否存在,如果存在则返回true
|
||||
|
||||
/// <summary>
|
||||
/// 检测指定文件是否存在,如果存在则返回true
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static bool IsExistFile(string filePath)
|
||||
{
|
||||
return File.Exists(filePath);
|
||||
}
|
||||
|
||||
#endregion 检测指定文件是否存在,如果存在则返回true
|
||||
|
||||
#region 创建文件夹
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="folderPath">文件夹的绝对路径</param>
|
||||
public static void CreateFolder(string folderPath)
|
||||
{
|
||||
if (!IsExistDirectory(folderPath))
|
||||
{
|
||||
Directory.CreateDirectory(folderPath);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 创建文件夹
|
||||
|
||||
#region 判断上传文件后缀名
|
||||
|
||||
/// <summary>
|
||||
/// 判断上传文件后缀名
|
||||
/// </summary>
|
||||
/// <param name="strExtension">后缀名</param>
|
||||
public static bool IsCanEdit(string strExtension)
|
||||
{
|
||||
strExtension = strExtension.ToLower();
|
||||
if (strExtension.LastIndexOf(".", StringComparison.Ordinal) >= 0)
|
||||
{
|
||||
strExtension = strExtension.Substring(strExtension.LastIndexOf(".", StringComparison.Ordinal));
|
||||
}
|
||||
else
|
||||
{
|
||||
strExtension = ".txt";
|
||||
}
|
||||
string[] strArray = new string[] { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
|
||||
for (int i = 0; i < strArray.Length; i++)
|
||||
{
|
||||
if (strExtension.Equals(strArray[i]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsSafeName(string strExtension)
|
||||
{
|
||||
strExtension = strExtension.ToLower();
|
||||
if (strExtension.LastIndexOf(".") >= 0)
|
||||
{
|
||||
strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
|
||||
}
|
||||
else
|
||||
{
|
||||
strExtension = ".txt";
|
||||
}
|
||||
string[] strArray = new string[] { ".jpg", ".gif", ".png" };
|
||||
for (int i = 0; i < strArray.Length; i++)
|
||||
{
|
||||
if (strExtension.Equals(strArray[i]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool IsZipName(string strExtension)
|
||||
{
|
||||
strExtension = strExtension.ToLower();
|
||||
if (strExtension.LastIndexOf(".") >= 0)
|
||||
{
|
||||
strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
|
||||
}
|
||||
else
|
||||
{
|
||||
strExtension = ".txt";
|
||||
}
|
||||
string[] strArray = new string[] { ".zip", ".rar" };
|
||||
for (int i = 0; i < strArray.Length; i++)
|
||||
{
|
||||
if (strExtension.Equals(strArray[i]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion 判断上传文件后缀名
|
||||
|
||||
#region 创建文件夹
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="fileName">文件的绝对路径</param>
|
||||
public static void CreateSuffic(string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(fileName))
|
||||
{
|
||||
Directory.CreateDirectory(fileName);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="fileName">文件的绝对路径</param>
|
||||
public static void CreateFiles(string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
//判断文件是否存在,不存在创建该文件
|
||||
if (!IsExistFile(fileName))
|
||||
{
|
||||
FileInfo file = new FileInfo(fileName);
|
||||
FileStream fs = file.Create();
|
||||
fs.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
}
|
||||
|
||||
#region 创建文本文件
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="content"></param>
|
||||
public static void CreateFile(string path, string content)
|
||||
{
|
||||
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||||
}
|
||||
using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
|
||||
{
|
||||
sw.Write(content);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 创建文本文件
|
||||
|
||||
/// <summary>
|
||||
/// 创建一个文件,并将字节流写入文件。
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
/// <param name="buffer">二进制流数据</param>
|
||||
public static void CreateFile(string filePath, byte[] buffer)
|
||||
{
|
||||
try
|
||||
{
|
||||
//判断文件是否存在,不存在创建该文件
|
||||
if (!IsExistFile(filePath))
|
||||
{
|
||||
FileInfo file = new FileInfo(filePath);
|
||||
FileStream fs = file.Create();
|
||||
fs.Write(buffer, 0, buffer.Length);
|
||||
fs.Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
File.WriteAllBytes(filePath, buffer);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 创建文件夹
|
||||
|
||||
#region 将文件移动到指定目录
|
||||
|
||||
/// <summary>
|
||||
/// 将文件移动到指定目录
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
|
||||
/// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
|
||||
public static void Move(string sourceFilePath, string descDirectoryPath)
|
||||
{
|
||||
string sourceName = GetFileName(sourceFilePath);
|
||||
if (IsExistDirectory(descDirectoryPath))
|
||||
{
|
||||
//如果目标中存在同名文件,则删除
|
||||
if (IsExistFile(descDirectoryPath + "\\" + sourceFilePath))
|
||||
{
|
||||
DeleteFile(descDirectoryPath + "\\" + sourceFilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
//将文件移动到指定目录
|
||||
File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 将文件移动到指定目录
|
||||
|
||||
#region 将源文件的内容复制到目标文件中
|
||||
|
||||
/// <summary>
|
||||
/// 将源文件的内容复制到目标文件中
|
||||
/// </summary>
|
||||
/// <param name="sourceFilePath">源文件的绝对路径</param>
|
||||
/// <param name="descDirectoryPath">目标文件的绝对路径</param>
|
||||
public static void Copy(string sourceFilePath, string descDirectoryPath)
|
||||
{
|
||||
File.Copy(sourceFilePath, descDirectoryPath, true);
|
||||
}
|
||||
|
||||
#endregion 将源文件的内容复制到目标文件中
|
||||
|
||||
#region 从文件的绝对路径中获取文件名( 不包含扩展名 )
|
||||
|
||||
/// <summary>
|
||||
/// 从文件的绝对路径中获取文件名( 不包含扩展名 )
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static string GetFileName(string filePath)
|
||||
{
|
||||
FileInfo file = new FileInfo(filePath);
|
||||
return file.Name;
|
||||
}
|
||||
|
||||
#endregion 从文件的绝对路径中获取文件名( 不包含扩展名 )
|
||||
|
||||
#region 获取文件的后缀名
|
||||
|
||||
/// <summary>
|
||||
/// 获取文件的后缀名
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static string GetExtension(string filePath)
|
||||
{
|
||||
FileInfo file = new FileInfo(filePath);
|
||||
return file.Extension;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回文件扩展名,不含“.”
|
||||
/// </summary>
|
||||
/// <param name="filepath">文件全名称</param>
|
||||
/// <returns>string</returns>
|
||||
public static string GetFileExt(string filepath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(filepath))
|
||||
{
|
||||
return "";
|
||||
}
|
||||
if (filepath.LastIndexOf(".", StringComparison.Ordinal) > 0)
|
||||
{
|
||||
return filepath.Substring(filepath.LastIndexOf(".", StringComparison.Ordinal) + 1); //文件扩展名,不含“.”
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
#endregion 获取文件的后缀名
|
||||
|
||||
#region 删除指定文件
|
||||
|
||||
/// <summary>
|
||||
/// 删除指定文件
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static void DeleteFile(string filePath)
|
||||
{
|
||||
if (IsExistFile(filePath))
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 删除指定文件
|
||||
|
||||
#region 删除指定目录及其所有子目录
|
||||
|
||||
/// <summary>
|
||||
/// 删除指定目录及其所有子目录
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">文件的绝对路径</param>
|
||||
public static void DeleteDirectory(string directoryPath)
|
||||
{
|
||||
if (IsExistDirectory(directoryPath))
|
||||
{
|
||||
Directory.Delete(directoryPath);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 删除指定目录及其所有子目录
|
||||
|
||||
#region 清空指定目录下所有文件及子目录,但该目录依然保存.
|
||||
|
||||
/// <summary>
|
||||
/// 清空指定目录下所有文件及子目录,但该目录依然保存.
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static void ClearDirectory(string directoryPath)
|
||||
{
|
||||
if (!IsExistDirectory(directoryPath)) return;
|
||||
//删除目录中所有的文件
|
||||
string[] fileNames = GetFileNames(directoryPath);
|
||||
for (int i = 0; i < fileNames.Length; i++)
|
||||
{
|
||||
DeleteFile(fileNames[i]);
|
||||
}
|
||||
//删除目录中所有的子目录
|
||||
string[] directoryNames = GetDirectories(directoryPath);
|
||||
for (int i = 0; i < directoryNames.Length; i++)
|
||||
{
|
||||
DeleteDirectory(directoryNames[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 清空指定目录下所有文件及子目录,但该目录依然保存.
|
||||
|
||||
#region 剪切 粘贴
|
||||
|
||||
/// <summary>
|
||||
/// 剪切文件
|
||||
/// </summary>
|
||||
/// <param name="source">原路径</param>
|
||||
/// <param name="destination">新路径</param>
|
||||
public bool FileMove(string source, string destination)
|
||||
{
|
||||
bool ret = false;
|
||||
FileInfo file_s = new FileInfo(source);
|
||||
FileInfo file_d = new FileInfo(destination);
|
||||
if (file_s.Exists)
|
||||
{
|
||||
if (!file_d.Exists)
|
||||
{
|
||||
file_s.MoveTo(destination);
|
||||
ret = true;
|
||||
}
|
||||
}
|
||||
if (ret == true)
|
||||
{
|
||||
//Response.Write("<script>alert('剪切文件成功!');</script>");
|
||||
}
|
||||
else
|
||||
{
|
||||
//Response.Write("<script>alert('剪切文件失败!');</script>");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
#endregion 剪切 粘贴
|
||||
|
||||
#region 检测指定目录是否为空
|
||||
|
||||
/// <summary>
|
||||
/// 检测指定目录是否为空
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static bool IsEmptyDirectory(string directoryPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
//判断文件是否存在
|
||||
string[] fileNames = GetFileNames(directoryPath);
|
||||
if (fileNames.Length > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
//判断是否存在文件夹
|
||||
string[] directoryNames = GetDirectories(directoryPath);
|
||||
if (directoryNames.Length > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 检测指定目录是否为空
|
||||
|
||||
#region 获取指定目录中所有文件列表
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定目录中所有文件列表
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static string[] GetFileNames(string directoryPath)
|
||||
{
|
||||
if (!IsExistDirectory(directoryPath))
|
||||
{
|
||||
throw new FileNotFoundException();
|
||||
}
|
||||
return Directory.GetFiles(directoryPath);
|
||||
}
|
||||
|
||||
#endregion 获取指定目录中所有文件列表
|
||||
|
||||
#region 获取指定目录中的子目录列表
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
public static string[] GetDirectories(string directoryPath)
|
||||
{
|
||||
return Directory.GetDirectories(directoryPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定目录及子目录中所有子目录列表
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">指定目录的绝对路径</param>
|
||||
/// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
|
||||
/// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
|
||||
/// <param name="isSearchChild">是否搜索子目录</param>
|
||||
public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
|
||||
{
|
||||
if (isSearchChild)
|
||||
{
|
||||
return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 获取指定目录中的子目录列表
|
||||
|
||||
#region 获取一个文件的长度
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个文件的长度,单位为Byte
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static int GetFileSize(string filePath)
|
||||
{
|
||||
//创建一个文件对象
|
||||
FileInfo fi = new FileInfo(filePath);
|
||||
//获取文件的大小
|
||||
return (int)fi.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个文件的长度,单位为KB
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的路径</param>
|
||||
public static double GetFileSizeByKb(string filePath)
|
||||
{
|
||||
//创建一个文件对象
|
||||
FileInfo fi = new FileInfo(filePath);
|
||||
//获取文件的大小
|
||||
return Math.Round(Convert.ToDouble(filePath.Length) / 1024, 2);// ConvertHelper.ToDouble(ConvertHelper.ToDouble(fi.Length) / 1024, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个文件的长度,单位为MB
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的路径</param>
|
||||
public static double GetFileSizeByMb(string filePath)
|
||||
{
|
||||
//创建一个文件对象
|
||||
FileInfo fi = new FileInfo(filePath);
|
||||
//获取文件的大小
|
||||
return Math.Round(Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024), 2);
|
||||
}
|
||||
|
||||
#endregion 获取一个文件的长度
|
||||
|
||||
#region 获取文件大小并以B,KB,GB,TB
|
||||
|
||||
/// <summary>
|
||||
/// 计算文件大小函数(保留两位小数),Size为字节大小
|
||||
/// </summary>
|
||||
/// <param name="size">初始文件大小</param>
|
||||
/// <returns></returns>
|
||||
public static string ToFileSize(long size)
|
||||
{
|
||||
string m_strSize = "";
|
||||
long FactSize = 0;
|
||||
FactSize = size;
|
||||
if (FactSize < 1024.00)
|
||||
m_strSize = FactSize.ToString("F2") + " 字节";
|
||||
else if (FactSize >= 1024.00 && FactSize < 1048576)
|
||||
m_strSize = (FactSize / 1024.00).ToString("F2") + " KB";
|
||||
else if (FactSize >= 1048576 && FactSize < 1073741824)
|
||||
m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " MB";
|
||||
else if (FactSize >= 1073741824)
|
||||
m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " GB";
|
||||
return m_strSize;
|
||||
}
|
||||
|
||||
#endregion 获取文件大小并以B,KB,GB,TB
|
||||
|
||||
#region 将文件读取到字符串中
|
||||
|
||||
/// <summary>
|
||||
/// 将文件读取到字符串中
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
public static string FileToString(string filePath)
|
||||
{
|
||||
return FileToString(filePath, Encoding.UTF8);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将文件读取到字符串中
|
||||
/// </summary>
|
||||
/// <param name="filePath">文件的绝对路径</param>
|
||||
/// <param name="encoding">字符编码</param>
|
||||
public static string FileToString(string filePath, Encoding encoding)
|
||||
{
|
||||
//创建流读取器
|
||||
StreamReader reader = new StreamReader(filePath, encoding);
|
||||
try
|
||||
{
|
||||
//读取流
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
finally
|
||||
{
|
||||
//关闭流读取器
|
||||
reader.Close();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 将文件读取到字符串中
|
||||
|
||||
#region 判断文件
|
||||
|
||||
// 判断文件是否是bai图片
|
||||
public static bool IsPicture(string fileName)
|
||||
{
|
||||
string strFilter = ".jpeg|.gif|.jpg|.png|.bmp|.pic|.tiff|.ico|.iff|.lbm|.mag|.mac|.mpt|.opt|";
|
||||
char[] separtor = { '|' };
|
||||
string[] tempFileds = StringSplit(strFilter, separtor);
|
||||
foreach (string str in tempFileds)
|
||||
{
|
||||
if (str.ToUpper() == fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")).ToUpper()) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 判断文件是否是excle
|
||||
public static bool IsExcel(string fileName)
|
||||
{
|
||||
string strFilter = ".xls|.xlsx|";
|
||||
char[] separtor = { '|' };
|
||||
string[] tempFileds = StringSplit(strFilter, separtor);
|
||||
foreach (string str in tempFileds)
|
||||
{
|
||||
if (str.ToUpper() == fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf(".")).ToUpper()) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 通过字符串,分隔符返回zhistring[]数组
|
||||
public static string[] StringSplit(string s, char[] separtor)
|
||||
{
|
||||
string[] tempFileds = s.Trim().Split(separtor); return tempFileds;
|
||||
}
|
||||
|
||||
#endregion 判断文件
|
||||
}
|
||||
}
|
||||
225
WaterCloud.Code/Util/HttpWebClient.cs
Normal file
225
WaterCloud.Code/Util/HttpWebClient.cs
Normal file
@@ -0,0 +1,225 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class HttpWebClient
|
||||
{
|
||||
private IHttpClientFactory _httpClientFactory;
|
||||
|
||||
public HttpWebClient(IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
this._httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get异步请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="dicHeaders"></param>
|
||||
/// <param name="timeoutSecond"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> GetAsync(string url, Dictionary<string, string> dicHeaders, int timeoutSecond = 120)
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (dicHeaders != null)
|
||||
{
|
||||
foreach (var header in dicHeaders)
|
||||
{
|
||||
request.Headers.Add(header.Key, header.Value);
|
||||
}
|
||||
}
|
||||
client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
|
||||
var response = await client.SendAsync(request);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="requestString"></param>
|
||||
/// <param name="dicHeaders"></param>
|
||||
/// <param name="timeoutSecond"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> PostAsync(string url, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond)
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
var requestContent = new StringContent(requestString);
|
||||
if (dicHeaders != null)
|
||||
{
|
||||
foreach (var head in dicHeaders)
|
||||
{
|
||||
requestContent.Headers.Add(head.Key, head.Value);
|
||||
}
|
||||
}
|
||||
client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
|
||||
var response = await client.PostAsync(url, requestContent);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="requestString"></param>
|
||||
/// <param name="dicHeaders"></param>
|
||||
/// <param name="timeoutSecond"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> PutAsync(string url, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond)
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
var requestContent = new StringContent(requestString);
|
||||
if (dicHeaders != null)
|
||||
{
|
||||
foreach (var head in dicHeaders)
|
||||
{
|
||||
requestContent.Headers.Add(head.Key, head.Value);
|
||||
}
|
||||
}
|
||||
client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
|
||||
var response = await client.PutAsync(url, requestContent);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Patch异步请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="requestString"></param>
|
||||
/// <param name="dicHeaders"></param>
|
||||
/// <param name="timeoutSecond"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> PatchAsync(string url, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond)
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
var requestContent = new StringContent(requestString);
|
||||
if (dicHeaders != null)
|
||||
{
|
||||
foreach (var head in dicHeaders)
|
||||
{
|
||||
requestContent.Headers.Add(head.Key, head.Value);
|
||||
}
|
||||
}
|
||||
client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
|
||||
var response = await client.PatchAsync(url, requestContent);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> DeleteAsync(string url, Dictionary<string, string> dicHeaders, int timeoutSecond)
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
var request = new HttpRequestMessage(HttpMethod.Delete, url);
|
||||
if (dicHeaders != null)
|
||||
{
|
||||
foreach (var head in dicHeaders)
|
||||
{
|
||||
request.Headers.Add(head.Key, head.Value);
|
||||
}
|
||||
}
|
||||
client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
|
||||
var response = await client.SendAsync(request);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步请求(通用)
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="method"></param>
|
||||
/// <param name="requestString"></param>
|
||||
/// <param name="dicHeaders"></param>
|
||||
/// <param name="timeoutSecond"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> ExecuteAsync(string url, HttpMethod method, string requestString, Dictionary<string, string> dicHeaders, int timeoutSecond = 120,
|
||||
string accept = "application/json")
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient();
|
||||
if (url.IndexOf('?') > -1)
|
||||
{
|
||||
url += "&v=" + DateTime.Now.ToString("yyyyMMddhhmmss");
|
||||
}
|
||||
else
|
||||
{
|
||||
url += "?v=" + DateTime.Now.ToString("yyyyMMddhhmmss");
|
||||
}
|
||||
var request = new HttpRequestMessage(method, url)
|
||||
{
|
||||
Content = new StringContent(requestString),
|
||||
};
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
if (dicHeaders != null)
|
||||
{
|
||||
foreach (var header in dicHeaders)
|
||||
{
|
||||
request.Headers.Add(header.Key, header.Value);
|
||||
}
|
||||
}
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept) { CharSet = "utf-8" });
|
||||
var response = await client.SendAsync(request);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class CustomerHttpException : Exception
|
||||
{
|
||||
public CustomerHttpException() : base()
|
||||
{ }
|
||||
|
||||
public CustomerHttpException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
138
WaterCloud.Code/Util/JsonHelper.cs
Normal file
138
WaterCloud.Code/Util/JsonHelper.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
#region JsonHelper
|
||||
|
||||
public static class JsonHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 把数组转为逗号连接的字符串
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="Str"></param>
|
||||
/// <returns></returns>
|
||||
public static string ArrayToString(dynamic data, string Str)
|
||||
{
|
||||
string resStr = Str;
|
||||
foreach (var item in data)
|
||||
{
|
||||
if (resStr != "")
|
||||
{
|
||||
resStr += ",";
|
||||
}
|
||||
|
||||
if (item is string)
|
||||
{
|
||||
resStr += item;
|
||||
}
|
||||
else
|
||||
{
|
||||
resStr += item.Value;
|
||||
}
|
||||
}
|
||||
return resStr;
|
||||
}
|
||||
|
||||
public static object ToObject(this string Json)
|
||||
{
|
||||
return string.IsNullOrEmpty(Json) ? null : JsonConvert.DeserializeObject(Json);
|
||||
}
|
||||
|
||||
public static T ToObject<T>(this string Json)
|
||||
{
|
||||
Json = Json.Replace(" ", "");
|
||||
return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
|
||||
}
|
||||
|
||||
public static JObject ToJObject(this string Json)
|
||||
{
|
||||
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
|
||||
}
|
||||
|
||||
public static List<T> ToList<T>(this string Json)
|
||||
{
|
||||
return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
|
||||
}
|
||||
|
||||
public static string ToJson(this object obj, string dateFormat = "yyyy/MM/dd HH:mm:ss")
|
||||
{
|
||||
return obj == null ? string.Empty : JsonConvert.SerializeObject(obj, new IsoDateTimeConverter { DateTimeFormat = dateFormat });
|
||||
}
|
||||
}
|
||||
|
||||
#endregion JsonHelper
|
||||
|
||||
#region JsonConverter
|
||||
|
||||
/// <summary>
|
||||
/// Json数据返回到前端js的时候,把数值很大的long类型转成字符串
|
||||
/// </summary>
|
||||
public class StringJsonConverter : JsonConverter
|
||||
{
|
||||
public StringJsonConverter()
|
||||
{ }
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
return reader.Value.ToLong();
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
return;
|
||||
}
|
||||
string sValue = value.ToString();
|
||||
writer.WriteValue(sValue);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DateTime类型序列化的时候,转成指定的格式
|
||||
/// </summary>
|
||||
public class DateTimeJsonConverter : JsonConverter
|
||||
{
|
||||
public DateTimeJsonConverter()
|
||||
{ }
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
return reader.Value.ParseToString().ToDate();
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
return;
|
||||
}
|
||||
DateTime? dt = value as DateTime?;
|
||||
if (dt == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
return;
|
||||
}
|
||||
writer.WriteValue(dt.Value.ToString("yyyy/MM/dd HH:mm:ss"));
|
||||
}
|
||||
}
|
||||
|
||||
#endregion JsonConverter
|
||||
}
|
||||
252
WaterCloud.Code/Util/LogHelper.cs
Normal file
252
WaterCloud.Code/Util/LogHelper.cs
Normal file
@@ -0,0 +1,252 @@
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class LogHelper
|
||||
{
|
||||
private static object lockHelper = new object();
|
||||
|
||||
#region 写文本日志
|
||||
|
||||
/// <summary>
|
||||
/// 写日志 异步
|
||||
/// 默认路径:根目录/Log/yyyy-MM/
|
||||
/// 默认文件:yyyy-MM-dd.log
|
||||
/// </summary>
|
||||
/// <param name="logContent">日志内容 自动附加时间</param>
|
||||
public static void Write(string logContent)
|
||||
{
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
|
||||
public static void WriteWithTime(string logContent)
|
||||
{
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
logContent = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine + logContent;
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
|
||||
#endregion 写文本日志
|
||||
|
||||
#region 写异常日志
|
||||
|
||||
/// <summary>
|
||||
/// 写异常日志
|
||||
/// </summary>
|
||||
/// <param name="ex"></param>
|
||||
public static void Write(Exception ex)
|
||||
{
|
||||
string logContent = string.Empty;
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
logContent += GetExceptionMessage(ex);
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
|
||||
public static void WriteWithTime(Exception ex)
|
||||
{
|
||||
string logContent = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine;
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
logContent += GetExceptionMessage(ex);
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
|
||||
public static void WriteWithTime(ExceptionContext ex)
|
||||
{
|
||||
if (ex == null)
|
||||
return;
|
||||
string logContent = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine;
|
||||
logContent += "程序异常" + Environment.NewLine;
|
||||
string logPath = DateTime.Now.ToString("yyyy-MM");
|
||||
Exception Error = ex.Exception;
|
||||
LogMessage logMessage = new LogMessage();
|
||||
logMessage.OperationTime = DateTime.Now;
|
||||
logMessage.Url = ex.HttpContext.Request.GetDisplayUrl();
|
||||
if (ex.ActionDescriptor != null)
|
||||
{
|
||||
logMessage.Class = ex.ActionDescriptor.DisplayName;
|
||||
}
|
||||
else
|
||||
{
|
||||
logMessage.Class = "服务器配置问题";
|
||||
}
|
||||
logMessage.Ip = WebHelper.Ip;
|
||||
logMessage.Host = ex.HttpContext.Request.Host.ToString();
|
||||
var current = OperatorProvider.Provider.GetCurrent();
|
||||
if (current != null)
|
||||
{
|
||||
logMessage.UserName = current.UserCode + "(" + current.UserName + ")";
|
||||
}
|
||||
var err = Error.GetOriginalException();
|
||||
logMessage.ExceptionInfo = err.Message;
|
||||
logMessage.ExceptionSource = err.Source;
|
||||
logMessage.ExceptionRemark = err.StackTrace;
|
||||
logContent += ExceptionFormat(logMessage);
|
||||
Write(logPath, logContent);
|
||||
}
|
||||
|
||||
private static string GetExceptionMessage(Exception ex)
|
||||
{
|
||||
string message = string.Empty;
|
||||
if (ex != null)
|
||||
{
|
||||
message += ex.Message;
|
||||
message += Environment.NewLine;
|
||||
Exception originalException = ex.GetOriginalException();
|
||||
if (originalException != null)
|
||||
{
|
||||
if (originalException.Message != ex.Message)
|
||||
{
|
||||
message += originalException.Message;
|
||||
message += Environment.NewLine;
|
||||
}
|
||||
}
|
||||
message += ex.StackTrace;
|
||||
message += Environment.NewLine;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
#endregion 写异常日志
|
||||
|
||||
#region 写日志到指定路径
|
||||
|
||||
/// <summary>
|
||||
/// 写日志 异步
|
||||
/// 默认文件:yyyy-MM-dd.log
|
||||
/// </summary>
|
||||
/// <param name="logPath">日志目录[默认程序根目录\Log\下添加,故使用相对路径,如:营销任务]</param>
|
||||
/// <param name="logContent">日志内容 自动附加时间</param>
|
||||
public static void Write(string logPath, string logContent)
|
||||
{
|
||||
string logFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
|
||||
Write(logPath, logFileName, logContent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写日志 异步
|
||||
/// </summary>
|
||||
/// <param name="logPath">日志目录</param>
|
||||
/// <param name="logFileName">日志文件名</param>
|
||||
/// <param name="logContent">日志内容 自动附加时间</param>
|
||||
public static void Write(string logPath, string logFileName, string logContent)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(logContent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(logPath))
|
||||
{
|
||||
logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", DateTime.Now.ToString("yyyy-MM"));
|
||||
}
|
||||
else
|
||||
{
|
||||
logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", logPath.Trim('\\'));
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(logFileName))
|
||||
{
|
||||
logFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
|
||||
}
|
||||
if (!Directory.Exists(logPath))
|
||||
{
|
||||
Directory.CreateDirectory(logPath);
|
||||
}
|
||||
string fileName = Path.Combine(logPath, logFileName);
|
||||
Action taskAction = () =>
|
||||
{
|
||||
lock (lockHelper)
|
||||
{
|
||||
using (StreamWriter sw = File.AppendText(fileName))
|
||||
{
|
||||
sw.WriteLine(logContent + Environment.NewLine);
|
||||
sw.Flush();
|
||||
sw.Close();
|
||||
}
|
||||
}
|
||||
};
|
||||
Task task = new Task(taskAction);
|
||||
task.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成异常信息
|
||||
/// </summary>
|
||||
/// <param name="logMessage">对象</param>
|
||||
/// <returns></returns>
|
||||
public static string ExceptionFormat(LogMessage logMessage)
|
||||
{
|
||||
StringBuilder strInfo = new StringBuilder();
|
||||
strInfo.Append("1. 调试: >> 操作时间: " + logMessage.OperationTime + " 操作人: " + logMessage.UserName + " \r\n");
|
||||
strInfo.Append("2. 地址: " + logMessage.Url + " \r\n");
|
||||
strInfo.Append("3. 类名: " + logMessage.Class + " \r\n");
|
||||
strInfo.Append("4. 主机: " + logMessage.Host + " Ip : " + logMessage.Ip + " \r\n");
|
||||
strInfo.Append("5. 异常: " + logMessage.ExceptionInfo + "\r\n");
|
||||
strInfo.Append("6. 来源: " + logMessage.ExceptionSource + "\r\n");
|
||||
strInfo.Append("7. 实例: " + logMessage.ExceptionRemark + "\r\n");
|
||||
strInfo.Append("-----------------------------------------------------------------------------------------------------------------------------\r\n");
|
||||
return strInfo.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 格式化异常信息
|
||||
/// </summary>
|
||||
/// <param name="logMessage">对象</param>
|
||||
/// <returns></returns>
|
||||
public static string ExMsgFormat(string message)
|
||||
{
|
||||
//数据库异常
|
||||
if (message.Contains("An exception occurred while executing DbCommand."))
|
||||
{
|
||||
if (message.Contains("Duplicate entry '") && message.Contains("key"))
|
||||
{
|
||||
message = "数据违反唯一约束,请检查";
|
||||
}
|
||||
else if (message.Contains("Data too long for column"))
|
||||
{
|
||||
message = "数据长度过长,请检查";
|
||||
}
|
||||
else
|
||||
{
|
||||
message = "数据操作异常,请联系管理员";
|
||||
}
|
||||
}
|
||||
//其他异常
|
||||
else
|
||||
{
|
||||
if (message.Contains("Object reference not set to an instance of an object."))
|
||||
{
|
||||
message = "操作对象为空,请联系管理员";
|
||||
}
|
||||
else if (message.Contains("Value cannot be null"))
|
||||
{
|
||||
message = "值为空,请联系管理员";
|
||||
}
|
||||
}
|
||||
if (!IsHasCHZN(message))
|
||||
{
|
||||
message = "程序内部异常,请联系管理员";
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测是否有中文字符
|
||||
/// </summary>
|
||||
/// <param name="inputData"></param>
|
||||
/// <returns></returns>
|
||||
private static bool IsHasCHZN(string inputData)
|
||||
{
|
||||
Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
|
||||
Match m = RegCHZN.Match(inputData);
|
||||
return m.Success;
|
||||
}
|
||||
|
||||
#endregion 写日志到指定路径
|
||||
}
|
||||
}
|
||||
57
WaterCloud.Code/Util/LogMessage.cs
Normal file
57
WaterCloud.Code/Util/LogMessage.cs
Normal file
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class LogMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// 操作时间
|
||||
/// </summary>
|
||||
public DateTime OperationTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Url地址
|
||||
/// </summary>
|
||||
public string Url { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 类名
|
||||
/// </summary>
|
||||
public string Class { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// IP
|
||||
/// </summary>
|
||||
public string Ip { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 主机
|
||||
/// </summary>
|
||||
public string Host { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 操作人
|
||||
/// </summary>
|
||||
public string UserName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 内容
|
||||
/// </summary>
|
||||
public string Content { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 异常信息
|
||||
/// </summary>
|
||||
public string ExceptionInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 异常来源
|
||||
/// </summary>
|
||||
public string ExceptionSource { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 异常信息备注
|
||||
/// </summary>
|
||||
public string ExceptionRemark { get; set; }
|
||||
}
|
||||
}
|
||||
236
WaterCloud.Code/Util/MimeMapping.cs
Normal file
236
WaterCloud.Code/Util/MimeMapping.cs
Normal file
@@ -0,0 +1,236 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
// 通过自己定义一个静态类
|
||||
// 将所有的Content Type都扔进去吧
|
||||
// 调用的时候直接调用静态方法即可。
|
||||
public static class MimeMapping
|
||||
{
|
||||
private static Hashtable _mimeMappingTable;
|
||||
|
||||
private static void AddMimeMapping(string extension, string MimeType)
|
||||
{
|
||||
MimeMapping._mimeMappingTable.Add(extension, MimeType);
|
||||
}
|
||||
|
||||
public static string GetMimeMapping(string FileName)
|
||||
{
|
||||
string text = null;
|
||||
int num = FileName.LastIndexOf('.');
|
||||
if (0 < num && num > FileName.LastIndexOf('\\'))
|
||||
{
|
||||
text = (string)MimeMapping._mimeMappingTable[FileName.Substring(num)];
|
||||
}
|
||||
if (text == null)
|
||||
{
|
||||
text = (string)MimeMapping._mimeMappingTable[".*"];
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
static MimeMapping()
|
||||
{
|
||||
MimeMapping._mimeMappingTable = new Hashtable(190, StringComparer.CurrentCultureIgnoreCase);
|
||||
MimeMapping.AddMimeMapping(".323", "text/h323");
|
||||
MimeMapping.AddMimeMapping(".asx", "video/x-ms-asf");
|
||||
MimeMapping.AddMimeMapping(".acx", "application/internet-property-stream");
|
||||
MimeMapping.AddMimeMapping(".ai", "application/postscript");
|
||||
MimeMapping.AddMimeMapping(".aif", "audio/x-aiff");
|
||||
MimeMapping.AddMimeMapping(".aiff", "audio/aiff");
|
||||
MimeMapping.AddMimeMapping(".axs", "application/olescript");
|
||||
MimeMapping.AddMimeMapping(".aifc", "audio/aiff");
|
||||
MimeMapping.AddMimeMapping(".asr", "video/x-ms-asf");
|
||||
MimeMapping.AddMimeMapping(".avi", "video/x-msvideo");
|
||||
MimeMapping.AddMimeMapping(".asf", "video/x-ms-asf");
|
||||
MimeMapping.AddMimeMapping(".au", "audio/basic");
|
||||
MimeMapping.AddMimeMapping(".application", "application/x-ms-application");
|
||||
MimeMapping.AddMimeMapping(".bin", "application/octet-stream");
|
||||
MimeMapping.AddMimeMapping(".bas", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".bcpio", "application/x-bcpio");
|
||||
MimeMapping.AddMimeMapping(".bmp", "image/bmp");
|
||||
MimeMapping.AddMimeMapping(".cdf", "application/x-cdf");
|
||||
MimeMapping.AddMimeMapping(".cat", "application/vndms-pkiseccat");
|
||||
MimeMapping.AddMimeMapping(".crt", "application/x-x509-ca-cert");
|
||||
MimeMapping.AddMimeMapping(".c", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".css", "text/css");
|
||||
MimeMapping.AddMimeMapping(".cer", "application/x-x509-ca-cert");
|
||||
MimeMapping.AddMimeMapping(".crl", "application/pkix-crl");
|
||||
MimeMapping.AddMimeMapping(".cmx", "image/x-cmx");
|
||||
MimeMapping.AddMimeMapping(".csh", "application/x-csh");
|
||||
MimeMapping.AddMimeMapping(".cod", "image/cis-cod");
|
||||
MimeMapping.AddMimeMapping(".cpio", "application/x-cpio");
|
||||
MimeMapping.AddMimeMapping(".clp", "application/x-msclip");
|
||||
MimeMapping.AddMimeMapping(".crd", "application/x-mscardfile");
|
||||
MimeMapping.AddMimeMapping(".deploy", "application/octet-stream");
|
||||
MimeMapping.AddMimeMapping(".dll", "application/x-msdownload");
|
||||
MimeMapping.AddMimeMapping(".dot", "application/msword");
|
||||
MimeMapping.AddMimeMapping(".doc", "application/msword");
|
||||
MimeMapping.AddMimeMapping(".dvi", "application/x-dvi");
|
||||
MimeMapping.AddMimeMapping(".dir", "application/x-director");
|
||||
MimeMapping.AddMimeMapping(".dxr", "application/x-director");
|
||||
MimeMapping.AddMimeMapping(".der", "application/x-x509-ca-cert");
|
||||
MimeMapping.AddMimeMapping(".dib", "image/bmp");
|
||||
MimeMapping.AddMimeMapping(".dcr", "application/x-director");
|
||||
MimeMapping.AddMimeMapping(".disco", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".exe", "application/octet-stream");
|
||||
MimeMapping.AddMimeMapping(".etx", "text/x-setext");
|
||||
MimeMapping.AddMimeMapping(".evy", "application/envoy");
|
||||
MimeMapping.AddMimeMapping(".eml", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".eps", "application/postscript");
|
||||
MimeMapping.AddMimeMapping(".flr", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".fif", "application/fractals");
|
||||
MimeMapping.AddMimeMapping(".gtar", "application/x-gtar");
|
||||
MimeMapping.AddMimeMapping(".gif", "image/gif");
|
||||
MimeMapping.AddMimeMapping(".gz", "application/x-gzip");
|
||||
MimeMapping.AddMimeMapping(".hta", "application/hta");
|
||||
MimeMapping.AddMimeMapping(".htc", "text/x-component");
|
||||
MimeMapping.AddMimeMapping(".htt", "text/webviewhtml");
|
||||
MimeMapping.AddMimeMapping(".h", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".hdf", "application/x-hdf");
|
||||
MimeMapping.AddMimeMapping(".hlp", "application/winhlp");
|
||||
MimeMapping.AddMimeMapping(".html", "text/html");
|
||||
MimeMapping.AddMimeMapping(".htm", "text/html");
|
||||
MimeMapping.AddMimeMapping(".hqx", "application/mac-binhex40");
|
||||
MimeMapping.AddMimeMapping(".isp", "application/x-internet-signup");
|
||||
MimeMapping.AddMimeMapping(".iii", "application/x-iphone");
|
||||
MimeMapping.AddMimeMapping(".ief", "image/ief");
|
||||
MimeMapping.AddMimeMapping(".ivf", "video/x-ivf");
|
||||
MimeMapping.AddMimeMapping(".ins", "application/x-internet-signup");
|
||||
MimeMapping.AddMimeMapping(".ico", "image/x-icon");
|
||||
MimeMapping.AddMimeMapping(".jpg", "image/jpeg");
|
||||
MimeMapping.AddMimeMapping(".jfif", "image/pjpeg");
|
||||
MimeMapping.AddMimeMapping(".jpe", "image/jpeg");
|
||||
MimeMapping.AddMimeMapping(".jpeg", "image/jpeg");
|
||||
MimeMapping.AddMimeMapping(".js", "application/x-javascript");
|
||||
MimeMapping.AddMimeMapping(".lsx", "video/x-la-asf");
|
||||
MimeMapping.AddMimeMapping(".latex", "application/x-latex");
|
||||
MimeMapping.AddMimeMapping(".lsf", "video/x-la-asf");
|
||||
MimeMapping.AddMimeMapping(".manifest", "application/x-ms-manifest");
|
||||
MimeMapping.AddMimeMapping(".mhtml", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".mny", "application/x-msmoney");
|
||||
MimeMapping.AddMimeMapping(".mht", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".mid", "audio/mid");
|
||||
MimeMapping.AddMimeMapping(".mpv2", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".man", "application/x-troff-man");
|
||||
MimeMapping.AddMimeMapping(".mvb", "application/x-msmediaview");
|
||||
MimeMapping.AddMimeMapping(".mpeg", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".m3u", "audio/x-mpegurl");
|
||||
MimeMapping.AddMimeMapping(".mdb", "application/x-msaccess");
|
||||
MimeMapping.AddMimeMapping(".mpp", "application/vnd.ms-project");
|
||||
MimeMapping.AddMimeMapping(".m1v", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mpa", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".me", "application/x-troff-me");
|
||||
MimeMapping.AddMimeMapping(".m13", "application/x-msmediaview");
|
||||
MimeMapping.AddMimeMapping(".movie", "video/x-sgi-movie");
|
||||
MimeMapping.AddMimeMapping(".m14", "application/x-msmediaview");
|
||||
MimeMapping.AddMimeMapping(".mpe", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mp2", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mov", "video/quicktime");
|
||||
MimeMapping.AddMimeMapping(".mp3", "audio/mpeg");
|
||||
MimeMapping.AddMimeMapping(".mpg", "video/mpeg");
|
||||
MimeMapping.AddMimeMapping(".ms", "application/x-troff-ms");
|
||||
MimeMapping.AddMimeMapping(".nc", "application/x-netcdf");
|
||||
MimeMapping.AddMimeMapping(".nws", "message/rfc822");
|
||||
MimeMapping.AddMimeMapping(".oda", "application/oda");
|
||||
MimeMapping.AddMimeMapping(".ods", "application/oleobject");
|
||||
MimeMapping.AddMimeMapping(".pmc", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp");
|
||||
MimeMapping.AddMimeMapping(".p7b", "application/x-pkcs7-certificates");
|
||||
MimeMapping.AddMimeMapping(".p7s", "application/pkcs7-signature");
|
||||
MimeMapping.AddMimeMapping(".pmw", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".ps", "application/postscript");
|
||||
MimeMapping.AddMimeMapping(".p7c", "application/pkcs7-mime");
|
||||
MimeMapping.AddMimeMapping(".pbm", "image/x-portable-bitmap");
|
||||
MimeMapping.AddMimeMapping(".ppm", "image/x-portable-pixmap");
|
||||
MimeMapping.AddMimeMapping(".pub", "application/x-mspublisher");
|
||||
MimeMapping.AddMimeMapping(".pnm", "image/x-portable-anymap");
|
||||
MimeMapping.AddMimeMapping(".png", "image/png");
|
||||
MimeMapping.AddMimeMapping(".pml", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".p10", "application/pkcs10");
|
||||
MimeMapping.AddMimeMapping(".pfx", "application/x-pkcs12");
|
||||
MimeMapping.AddMimeMapping(".p12", "application/x-pkcs12");
|
||||
MimeMapping.AddMimeMapping(".pdf", "application/pdf");
|
||||
MimeMapping.AddMimeMapping(".pps", "application/vnd.ms-powerpoint");
|
||||
MimeMapping.AddMimeMapping(".p7m", "application/pkcs7-mime");
|
||||
MimeMapping.AddMimeMapping(".pko", "application/vndms-pkipko");
|
||||
MimeMapping.AddMimeMapping(".ppt", "application/vnd.ms-powerpoint");
|
||||
MimeMapping.AddMimeMapping(".pmr", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".pma", "application/x-perfmon");
|
||||
MimeMapping.AddMimeMapping(".pot", "application/vnd.ms-powerpoint");
|
||||
MimeMapping.AddMimeMapping(".prf", "application/pics-rules");
|
||||
MimeMapping.AddMimeMapping(".pgm", "image/x-portable-graymap");
|
||||
MimeMapping.AddMimeMapping(".qt", "video/quicktime");
|
||||
MimeMapping.AddMimeMapping(".ra", "audio/x-pn-realaudio");
|
||||
MimeMapping.AddMimeMapping(".rgb", "image/x-rgb");
|
||||
MimeMapping.AddMimeMapping(".ram", "audio/x-pn-realaudio");
|
||||
MimeMapping.AddMimeMapping(".rmi", "audio/mid");
|
||||
MimeMapping.AddMimeMapping(".ras", "image/x-cmu-raster");
|
||||
MimeMapping.AddMimeMapping(".roff", "application/x-troff");
|
||||
MimeMapping.AddMimeMapping(".rtf", "application/rtf");
|
||||
MimeMapping.AddMimeMapping(".rtx", "text/richtext");
|
||||
MimeMapping.AddMimeMapping(".sv4crc", "application/x-sv4crc");
|
||||
MimeMapping.AddMimeMapping(".spc", "application/x-pkcs7-certificates");
|
||||
MimeMapping.AddMimeMapping(".setreg", "application/set-registration-initiation");
|
||||
MimeMapping.AddMimeMapping(".snd", "audio/basic");
|
||||
MimeMapping.AddMimeMapping(".stl", "application/vndms-pkistl");
|
||||
MimeMapping.AddMimeMapping(".setpay", "application/set-payment-initiation");
|
||||
MimeMapping.AddMimeMapping(".stm", "text/html");
|
||||
MimeMapping.AddMimeMapping(".shar", "application/x-shar");
|
||||
MimeMapping.AddMimeMapping(".sh", "application/x-sh");
|
||||
MimeMapping.AddMimeMapping(".sit", "application/x-stuffit");
|
||||
MimeMapping.AddMimeMapping(".spl", "application/futuresplash");
|
||||
MimeMapping.AddMimeMapping(".sct", "text/scriptlet");
|
||||
MimeMapping.AddMimeMapping(".scd", "application/x-msschedule");
|
||||
MimeMapping.AddMimeMapping(".sst", "application/vndms-pkicertstore");
|
||||
MimeMapping.AddMimeMapping(".src", "application/x-wais-source");
|
||||
MimeMapping.AddMimeMapping(".sv4cpio", "application/x-sv4cpio");
|
||||
MimeMapping.AddMimeMapping(".tex", "application/x-tex");
|
||||
MimeMapping.AddMimeMapping(".tgz", "application/x-compressed");
|
||||
MimeMapping.AddMimeMapping(".t", "application/x-troff");
|
||||
MimeMapping.AddMimeMapping(".tar", "application/x-tar");
|
||||
MimeMapping.AddMimeMapping(".tr", "application/x-troff");
|
||||
MimeMapping.AddMimeMapping(".tif", "image/tiff");
|
||||
MimeMapping.AddMimeMapping(".txt", "text/plain");
|
||||
MimeMapping.AddMimeMapping(".texinfo", "application/x-texinfo");
|
||||
MimeMapping.AddMimeMapping(".trm", "application/x-msterminal");
|
||||
MimeMapping.AddMimeMapping(".tiff", "image/tiff");
|
||||
MimeMapping.AddMimeMapping(".tcl", "application/x-tcl");
|
||||
MimeMapping.AddMimeMapping(".texi", "application/x-texinfo");
|
||||
MimeMapping.AddMimeMapping(".tsv", "text/tab-separated-values");
|
||||
MimeMapping.AddMimeMapping(".ustar", "application/x-ustar");
|
||||
MimeMapping.AddMimeMapping(".uls", "text/iuls");
|
||||
MimeMapping.AddMimeMapping(".vcf", "text/x-vcard");
|
||||
MimeMapping.AddMimeMapping(".wps", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wav", "audio/wav");
|
||||
MimeMapping.AddMimeMapping(".wrz", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".wri", "application/x-mswrite");
|
||||
MimeMapping.AddMimeMapping(".wks", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wmf", "application/x-msmetafile");
|
||||
MimeMapping.AddMimeMapping(".wcm", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wrl", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".wdb", "application/vnd.ms-works");
|
||||
MimeMapping.AddMimeMapping(".wsdl", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".xap", "application/x-silverlight-app");
|
||||
MimeMapping.AddMimeMapping(".xml", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".xlm", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xaf", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".xla", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xls", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xof", "x-world/x-vrml");
|
||||
MimeMapping.AddMimeMapping(".xlt", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xlc", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xsl", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".xbm", "image/x-xbitmap");
|
||||
MimeMapping.AddMimeMapping(".xlw", "application/vnd.ms-excel");
|
||||
MimeMapping.AddMimeMapping(".xpm", "image/x-xpixmap");
|
||||
MimeMapping.AddMimeMapping(".xwd", "image/x-xwindowdump");
|
||||
MimeMapping.AddMimeMapping(".xsd", "text/xml");
|
||||
MimeMapping.AddMimeMapping(".z", "application/x-compress");
|
||||
MimeMapping.AddMimeMapping(".zip", "application/x-zip-compressed");
|
||||
MimeMapping.AddMimeMapping(".*", "application/octet-stream");
|
||||
MimeMapping.AddMimeMapping(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
}
|
||||
}
|
||||
}
|
||||
58
WaterCloud.Code/Util/PdfHelper.cs
Normal file
58
WaterCloud.Code/Util/PdfHelper.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using iTextSharp.text;
|
||||
using iTextSharp.text.pdf;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class PdfHelper
|
||||
{
|
||||
}
|
||||
|
||||
public class PDFFooter : PdfPageEventHelper
|
||||
{
|
||||
// write on top of document
|
||||
public override void OnOpenDocument(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnOpenDocument(writer, document);
|
||||
PdfPTable tabFot = new PdfPTable(new float[] { 1F });
|
||||
tabFot.SpacingAfter = 10F;
|
||||
PdfPCell cell;
|
||||
tabFot.TotalWidth = 300F;
|
||||
cell = new PdfPCell(new Phrase("Header"));
|
||||
tabFot.AddCell(cell);
|
||||
tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
|
||||
}
|
||||
|
||||
// write on start of each page
|
||||
public override void OnStartPage(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnStartPage(writer, document);
|
||||
}
|
||||
|
||||
// write on end of each page
|
||||
public override void OnEndPage(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnEndPage(writer, document);
|
||||
//PdfPTable tabFot = new PdfPTable(new float[] { 1F });
|
||||
//tabFot.TotalWidth = 700f;
|
||||
//tabFot.DefaultCell.Border = 0;
|
||||
//// var footFont = FontFactory.GetFont("Lato", 12 * 0.667f, new Color(60, 60, 60));
|
||||
//string fontpath = HttpContext.Current.Server.MapPath("~/App_Data");
|
||||
//BaseFont customfont = BaseFont.CreateFont(fontpath + "\\Lato-Regular.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
|
||||
//var footFont = new Font(customfont, 12 * 0.667f, Font.NORMAL, new Color(170, 170, 170));
|
||||
|
||||
//PdfPCell cell;
|
||||
//cell = new PdfPCell(new Phrase("@ 2016 . All Rights Reserved", footFont));
|
||||
//cell.VerticalAlignment = Element.ALIGN_CENTER;
|
||||
//cell.Border = 0;
|
||||
//cell.PaddingLeft = 100f;
|
||||
//tabFot.AddCell(cell);
|
||||
//tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
|
||||
}
|
||||
|
||||
//write on close of document
|
||||
public override void OnCloseDocument(PdfWriter writer, Document document)
|
||||
{
|
||||
base.OnCloseDocument(writer, document);
|
||||
}
|
||||
}
|
||||
}
|
||||
162
WaterCloud.Code/Util/QueueHelper.cs
Normal file
162
WaterCloud.Code/Util/QueueHelper.cs
Normal file
@@ -0,0 +1,162 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
/// <summary>
|
||||
/// 队列工具类,用于另起线程处理执行类型数据
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class QueueHelper<T> : IDisposable
|
||||
{
|
||||
#region Private Field
|
||||
|
||||
/// <summary>
|
||||
/// The inner queue.
|
||||
/// </summary>
|
||||
private readonly ConcurrentQueue<T> _innerQueue;
|
||||
|
||||
/// <summary>
|
||||
/// The deal task.
|
||||
/// </summary>
|
||||
private readonly Task _dealTask;
|
||||
|
||||
/// <summary>
|
||||
/// The flag for end thread.
|
||||
/// </summary>
|
||||
private bool _endThreadFlag = false;
|
||||
|
||||
/// <summary>
|
||||
/// The auto reset event.
|
||||
/// </summary>
|
||||
private readonly AutoResetEvent _autoResetEvent = new(true);
|
||||
|
||||
#endregion Private Field
|
||||
|
||||
#region Public Property
|
||||
|
||||
/// <summary>
|
||||
/// The deal action.
|
||||
/// </summary>
|
||||
public Action<T> DealAction { get; set; }
|
||||
|
||||
#endregion Public Property
|
||||
|
||||
#region Constructor
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the QueueHelper`1 class.
|
||||
/// </summary>
|
||||
public QueueHelper()
|
||||
{
|
||||
this._innerQueue = new();
|
||||
this._dealTask = Task.Run(() => this.DealQueue());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the QueueHelper<T> class.
|
||||
/// </summary>
|
||||
/// <param name="DealAction">The deal action.</param>
|
||||
public QueueHelper(Action<T> DealAction)
|
||||
{
|
||||
this.DealAction = DealAction;
|
||||
this._innerQueue = new();
|
||||
this._dealTask = Task.Run(() => this.DealQueue());
|
||||
}
|
||||
|
||||
#endregion Constructor
|
||||
|
||||
#region Public Method
|
||||
|
||||
/// <summary>
|
||||
/// Save entity to Queue.
|
||||
/// </summary>
|
||||
/// <param name="entity">The entity what will be deal.</param>
|
||||
public bool Enqueue(T entity)
|
||||
{
|
||||
if (!this._endThreadFlag)
|
||||
{
|
||||
this._innerQueue.Enqueue(entity);
|
||||
this._autoResetEvent.Set();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes current instance, end the deal thread and inner queue.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (!this._endThreadFlag)
|
||||
{
|
||||
this._endThreadFlag = true;
|
||||
this._innerQueue.Enqueue(default);
|
||||
this._autoResetEvent.Set();
|
||||
|
||||
if (!this._dealTask.IsCompleted)
|
||||
this._dealTask.Wait();
|
||||
|
||||
this._dealTask.Dispose();
|
||||
|
||||
this._autoResetEvent.Dispose();
|
||||
this._autoResetEvent.Close();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Public Method
|
||||
|
||||
#region Private Method
|
||||
|
||||
/// <summary>
|
||||
/// Out Queue.
|
||||
/// </summary>
|
||||
/// <param name="entity">The init entity.</param>
|
||||
/// <returns>The entity what will be deal.</returns>
|
||||
private bool Dequeue(out T entity)
|
||||
{
|
||||
return this._innerQueue.TryDequeue(out entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deal entity in Queue.
|
||||
/// </summary>
|
||||
private void DealQueue()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
if (this.Dequeue(out T entity))
|
||||
{
|
||||
if (this._endThreadFlag && Equals(entity, default(T)))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
this.DealAction?.Invoke(entity);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Write(ex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this._autoResetEvent.WaitOne();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.Write(ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion Private Method
|
||||
}
|
||||
}
|
||||
2066
WaterCloud.Code/Util/RabbitMqHelper.cs
Normal file
2066
WaterCloud.Code/Util/RabbitMqHelper.cs
Normal file
File diff suppressed because it is too large
Load Diff
120
WaterCloud.Code/Util/ReflectionHelper.cs
Normal file
120
WaterCloud.Code/Util/ReflectionHelper.cs
Normal file
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ReflectionHelper
|
||||
{
|
||||
private static ConcurrentDictionary<string, object> dictCache = new ConcurrentDictionary<string, object>();
|
||||
private static List<string> exceptionList = new List<string> { "BaseService", "BaseController" };
|
||||
|
||||
#region 得到类里面的属性集合
|
||||
|
||||
/// <summary>
|
||||
/// 得到类里面的属性集合
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="columns"></param>
|
||||
/// <returns></returns>
|
||||
public static PropertyInfo[] GetProperties(Type type, string[] columns = null)
|
||||
{
|
||||
PropertyInfo[] properties = null;
|
||||
if (dictCache.ContainsKey(type.FullName))
|
||||
{
|
||||
properties = dictCache[type.FullName] as PropertyInfo[];
|
||||
}
|
||||
else
|
||||
{
|
||||
properties = type.GetProperties();
|
||||
dictCache.TryAdd(type.FullName, properties);
|
||||
}
|
||||
|
||||
if (columns != null && columns.Length > 0)
|
||||
{
|
||||
// 按columns顺序返回属性
|
||||
var columnPropertyList = new List<PropertyInfo>();
|
||||
foreach (var column in columns)
|
||||
{
|
||||
var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault();
|
||||
if (columnProperty != null)
|
||||
{
|
||||
columnPropertyList.Add(columnProperty);
|
||||
}
|
||||
}
|
||||
return columnPropertyList.ToArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
|
||||
public static object GetObjectPropertyValue<T>(T t, string propertyname)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
PropertyInfo property = type.GetProperty(propertyname);
|
||||
if (property == null) return string.Empty;
|
||||
object o = property.GetValue(t, null);
|
||||
if (o == null) return string.Empty;
|
||||
return o;
|
||||
}
|
||||
|
||||
#endregion 得到类里面的属性集合
|
||||
|
||||
/// <summary>
|
||||
/// StackTrace获取名称
|
||||
/// </summary>
|
||||
/// <param name="count">搜索层级</param>
|
||||
/// <param name="prefix">前缀</param>
|
||||
/// <returns></returns>
|
||||
public static string GetModuleName(int count = 10, bool isReplace = true, string prefix = "Service")
|
||||
{
|
||||
try
|
||||
{
|
||||
string moduleName = "";
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(moduleName))
|
||||
{
|
||||
break;
|
||||
}
|
||||
string className = new StackFrame(i, true).GetMethod().DeclaringType.FullName;
|
||||
className = className.Split('+')[0];
|
||||
className = className.Split('.').LastOrDefault();
|
||||
bool skip = false;
|
||||
foreach (var item in exceptionList)
|
||||
{
|
||||
if (className.Contains(item))
|
||||
{
|
||||
skip = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (skip)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (className.IndexOf(prefix) > -1)
|
||||
{
|
||||
moduleName = className;
|
||||
if (isReplace)
|
||||
{
|
||||
moduleName = moduleName.Replace(prefix, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
return moduleName;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
44
WaterCloud.Code/Util/ShellHelper.cs
Normal file
44
WaterCloud.Code/Util/ShellHelper.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class ShellHelper
|
||||
{
|
||||
public static string Bash(string command)
|
||||
{
|
||||
var escapedArgs = command.Replace("\"", "\\\"");
|
||||
var process = new Process()
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = "/bin/bash",
|
||||
Arguments = $"-c \"{escapedArgs}\"",
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
}
|
||||
};
|
||||
process.Start();
|
||||
string result = process.StandardOutput.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
process.Dispose();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string Cmd(string fileName, string args)
|
||||
{
|
||||
string output = string.Empty;
|
||||
|
||||
var info = new ProcessStartInfo();
|
||||
info.FileName = fileName;
|
||||
info.Arguments = args;
|
||||
info.RedirectStandardOutput = true;
|
||||
|
||||
using (var process = Process.Start(info))
|
||||
{
|
||||
output = process.StandardOutput.ReadToEnd();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
85
WaterCloud.Code/Util/TextHelper.cs
Normal file
85
WaterCloud.Code/Util/TextHelper.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class TextHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取默认值
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetCustomValue(string value, string defaultValue)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 截取指定长度的字符串
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="length"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetSubString(string value, int length, bool ellipsis = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
if (value.Length > length)
|
||||
{
|
||||
value = value.Substring(0, length);
|
||||
if (ellipsis)
|
||||
{
|
||||
value += "...";
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 字符串转指定类型数组
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="split"></param>
|
||||
/// <returns></returns>
|
||||
public static T[] SplitToArray<T>(string value, char split)
|
||||
{
|
||||
T[] arr = value.Split(new string[] { split.ToString() }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
|
||||
return arr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否有交集
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="list1"></param>
|
||||
/// <param name="list2"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsArrayIntersection<T>(List<T> list1, List<T> list2)
|
||||
{
|
||||
List<T> t = list1.Distinct().ToList();
|
||||
|
||||
var exceptArr = t.Except(list2).ToList();
|
||||
|
||||
if (exceptArr.Count < t.Count)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
37
WaterCloud.Code/Util/Utils.cs
Normal file
37
WaterCloud.Code/Util/Utils.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class Utils
|
||||
{
|
||||
#region 自动生成编号
|
||||
|
||||
/// <summary>
|
||||
/// 表示全局唯一标识符 (GUID)。
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GuId()
|
||||
{
|
||||
return IDGen.NextID().ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动生成编号 201008251145409865
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string CreateNo()
|
||||
{
|
||||
Random random = new Random();
|
||||
string strRandom = random.Next(1000, 10000).ToString(); //生成编号
|
||||
string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
|
||||
return code;
|
||||
}
|
||||
|
||||
#endregion 自动生成编号
|
||||
|
||||
public static string GetGuid()
|
||||
{
|
||||
return IDGen.NextID().ToString().Replace("-", string.Empty).ToLower();
|
||||
}
|
||||
}
|
||||
}
|
||||
379
WaterCloud.Code/Util/ValidatorHelper.cs
Normal file
379
WaterCloud.Code/Util/ValidatorHelper.cs
Normal file
@@ -0,0 +1,379 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public static class ValidatorHelper
|
||||
{
|
||||
#region 验证输入字符串为数字(带小数)
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串为带小数点正数
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsNumber(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, "^([0]|([1-9]+\\d{0,}?))(.[\\d]+)?$");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串为带小数点正负数
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsNumberic(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, "^-?\\d+$|^(-?\\d+)(\\.\\d+)?$");
|
||||
}
|
||||
|
||||
#endregion 验证输入字符串为数字(带小数)
|
||||
|
||||
#region 验证中国电话格式是否有效,格式010-85849685
|
||||
|
||||
/// <summary>
|
||||
/// 验证中国电话格式是否有效,格式010-85849685
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsTel(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
#endregion 验证中国电话格式是否有效,格式010-85849685
|
||||
|
||||
#region 验证输入字符串为电话号码
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串为电话号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsPhone(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"(^(\d{2,4}[-_-—]?)?\d{3,8}([-_-—]?\d{3,8})?([-_-—]?\d{1,7})?$)|(^0?1[35]\d{9}$)");
|
||||
//弱一点的验证: @"\d{3,4}-\d{7,8}"
|
||||
}
|
||||
|
||||
#endregion 验证输入字符串为电话号码
|
||||
|
||||
#region 验证是否是有效传真号码
|
||||
|
||||
/// <summary>
|
||||
/// 验证是否是有效传真号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsFax(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$");
|
||||
}
|
||||
|
||||
#endregion 验证是否是有效传真号码
|
||||
|
||||
#region 验证手机号是否合法
|
||||
|
||||
/// <summary>
|
||||
/// 验证手机号是否合法 号段为13,14,15,16,17,18,19 0,86开头将自动识别
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsMobile(this string str)
|
||||
{
|
||||
if (!str.StartsWith("1"))
|
||||
{
|
||||
str = str.TrimStart(new char[] { '8', '6', }).TrimStart('0');
|
||||
}
|
||||
return Regex.IsMatch(str, @"^(13|14|15|16|17|18|19)\d{9}$");
|
||||
}
|
||||
|
||||
#endregion 验证手机号是否合法
|
||||
|
||||
#region 验证身份证是否有效
|
||||
|
||||
/// <summary>
|
||||
/// 验证身份证是否有效
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsIDCard(this string str)
|
||||
{
|
||||
switch (str.Length)
|
||||
{
|
||||
case 18:
|
||||
{
|
||||
return str.IsIDCard18();
|
||||
}
|
||||
case 15:
|
||||
{
|
||||
return str.IsIDCard15();
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串为18位的身份证号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsIDCard18(this string str)
|
||||
{
|
||||
long n = 0;
|
||||
if (long.TryParse(str.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(str.Replace('x', '0').Replace('X', '0'), out n) == false)
|
||||
{
|
||||
return false;//数字验证
|
||||
}
|
||||
const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
|
||||
if (address.IndexOf(str.Remove(2), StringComparison.Ordinal) == -1)
|
||||
{
|
||||
return false;//省份验证
|
||||
}
|
||||
string birth = str.Substring(6, 8).Insert(6, "-").Insert(4, "-");
|
||||
DateTime time;
|
||||
if (DateTime.TryParse(birth, out time) == false)
|
||||
{
|
||||
return false;//生日验证
|
||||
}
|
||||
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
|
||||
string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
|
||||
char[] ai = str.Remove(17).ToCharArray();
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 17; i++)
|
||||
{
|
||||
sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
|
||||
}
|
||||
int y = -1;
|
||||
Math.DivRem(sum, 11, out y);
|
||||
return arrVarifyCode[y] == str.Substring(17, 1).ToLower();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串为15位的身份证号码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsIDCard15(this string str)
|
||||
{
|
||||
long n = 0;
|
||||
if (long.TryParse(str, out n) == false || n < Math.Pow(10, 14))
|
||||
{
|
||||
return false;//数字验证
|
||||
}
|
||||
const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
|
||||
if (address.IndexOf(str.Remove(2), StringComparison.Ordinal) == -1)
|
||||
{
|
||||
return false;//省份验证
|
||||
}
|
||||
string birth = str.Substring(6, 6).Insert(4, "-").Insert(2, "-");
|
||||
DateTime time;
|
||||
return DateTime.TryParse(birth, out time) != false;
|
||||
}
|
||||
|
||||
#endregion 验证身份证是否有效
|
||||
|
||||
#region 验证是否是有效邮箱地址
|
||||
|
||||
/// <summary>
|
||||
/// 验证是否是有效邮箱地址
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsEmail(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
|
||||
}
|
||||
|
||||
#endregion 验证是否是有效邮箱地址
|
||||
|
||||
#region 验证是否只含有汉字
|
||||
|
||||
/// <summary>
|
||||
/// 验证是否只含有汉字
|
||||
/// </summary>
|
||||
/// <param name="strln">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsOnlyChinese(this string strln)
|
||||
{
|
||||
return Regex.IsMatch(strln, @"^[\u4e00-\u9fa5]+$");
|
||||
}
|
||||
|
||||
#endregion 验证是否只含有汉字
|
||||
|
||||
#region 是否有多余的字符 防止SQL注入
|
||||
|
||||
/// <summary>
|
||||
/// 是否有多余的字符 防止SQL注入
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsBadString(this string str)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
return false;
|
||||
//列举一些特殊字符串
|
||||
const string badChars = "@,*,#,$,!,+,',=,--,%,^,&,?,(,), <,>,[,],{,},/,\\,;,:,\",\"\",delete,update,drop,alert,select";
|
||||
var arraryBadChar = badChars.Split(',');
|
||||
return arraryBadChar.Any(t => !str.Contains(t));
|
||||
}
|
||||
|
||||
#endregion 是否有多余的字符 防止SQL注入
|
||||
|
||||
#region 是否由数字、26个英文字母或者下划线組成的字串
|
||||
|
||||
/// <summary>
|
||||
/// 是否由数字、26个英文字母或者下划线組成的字串
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsNzx(this string str)
|
||||
{
|
||||
return Regex.Match(str, "^[0-9a-zA-Z_]+$").Success;
|
||||
}
|
||||
|
||||
#endregion 是否由数字、26个英文字母或者下划线組成的字串
|
||||
|
||||
#region 由数字、26个英文字母、汉字組成的字串
|
||||
|
||||
/// <summary>
|
||||
/// 由数字、26个英文字母、汉字組成的字串
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsSzzmChinese(this string str)
|
||||
{
|
||||
return Regex.Match(str, @"^[0-9a-zA-Z\u4e00-\u9fa5]+$").Success;
|
||||
}
|
||||
|
||||
#endregion 由数字、26个英文字母、汉字組成的字串
|
||||
|
||||
#region 由数字、26个英文字母組成的字串
|
||||
|
||||
/// <summary>
|
||||
/// 是否由数字、26个英文字母組成的字串
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsSzzm(this string str)
|
||||
{
|
||||
return Regex.Match(str, @"^[0-9a-zA-Z]+$").Success;
|
||||
}
|
||||
|
||||
#endregion 由数字、26个英文字母組成的字串
|
||||
|
||||
#region 验证输入字符串为邮政编码
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串为邮政编码
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
public static bool IsPostCode(this string str)
|
||||
{
|
||||
return Regex.IsMatch(str, @"\d{6}");
|
||||
}
|
||||
|
||||
#endregion 验证输入字符串为邮政编码
|
||||
|
||||
#region 检查对象的输入长度
|
||||
|
||||
/// <summary>
|
||||
/// 检查对象的输入长度
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <param name="length">指定的长度</param>
|
||||
/// <returns>false 太长,true -太短</returns>
|
||||
public static bool CheckLength(this string str, int length)
|
||||
{
|
||||
if (str.Length > length)
|
||||
{
|
||||
return false;//长度太长
|
||||
}
|
||||
return str.Length >= length;
|
||||
}
|
||||
|
||||
#endregion 检查对象的输入长度
|
||||
|
||||
#region 判断用户输入是否为日期
|
||||
|
||||
/// <summary>
|
||||
/// 判断用户输入是否为日期
|
||||
/// </summary>
|
||||
/// <param name="str">输入字符</param>
|
||||
/// <returns>返回一个bool类型的值</returns>
|
||||
/// <remarks>
|
||||
/// 可判断格式如下(其中-可替换为/,不影响验证)
|
||||
/// YYYY | YYYY-MM | YYYY-MM-DD | YYYY-MM-DD HH:MM:SS | YYYY-MM-DD HH:MM:SS.FFF
|
||||
/// </remarks>
|
||||
public static bool IsDateTime(this string str)
|
||||
{
|
||||
if (null == str)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
const string regexDate = @"[1-2]{1}[0-9]{3}((-|\/|\.){1}(([0]?[1-9]{1})|(1[0-2]{1}))((-|\/|\.){1}((([0]?[1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1})))( (([0-1]{1}[0-9]{1})|2[0-3]{1}):([0-5]{1}[0-9]{1}):([0-5]{1}[0-9]{1})(\.[0-9]{3})?)?)?)?$";
|
||||
if (Regex.IsMatch(str, regexDate))
|
||||
{
|
||||
//以下各月份日期验证,保证验证的完整性
|
||||
int indexY = -1;
|
||||
int indexM = -1;
|
||||
int indexD = -1;
|
||||
if (-1 != (indexY = str.IndexOf("-", StringComparison.Ordinal)))
|
||||
{
|
||||
indexM = str.IndexOf("-", indexY + 1, StringComparison.Ordinal);
|
||||
indexD = str.IndexOf(":", StringComparison.Ordinal);
|
||||
}
|
||||
else
|
||||
{
|
||||
indexY = str.IndexOf("/", StringComparison.Ordinal);
|
||||
indexM = str.IndexOf("/", indexY + 1, StringComparison.Ordinal);
|
||||
indexD = str.IndexOf(":", StringComparison.Ordinal);
|
||||
}
|
||||
//不包含日期部分,直接返回true
|
||||
if (-1 == indexM)
|
||||
return true;
|
||||
if (-1 == indexD)
|
||||
{
|
||||
indexD = str.Length + 3;
|
||||
}
|
||||
int iYear = Convert.ToInt32(str.Substring(0, indexY));
|
||||
int iMonth = Convert.ToInt32(str.Substring(indexY + 1, indexM - indexY - 1));
|
||||
int iDate = Convert.ToInt32(str.Substring(indexM + 1, indexD - indexM - 4));
|
||||
//判断月份日期
|
||||
if ((iMonth < 8 && 1 == iMonth % 2) || (iMonth > 8 && 0 == iMonth % 2))
|
||||
{
|
||||
if (iDate < 32)
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iMonth != 2)
|
||||
{
|
||||
if (iDate < 31)
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
//闰年
|
||||
if ((0 == iYear % 400) || (0 == iYear % 4 && 0 < iYear % 100))
|
||||
{
|
||||
if (iDate < 30)
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (iDate < 29)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion 判断用户输入是否为日期
|
||||
}
|
||||
}
|
||||
86
WaterCloud.Code/Util/VerifyCodeHelper.cs
Normal file
86
WaterCloud.Code/Util/VerifyCodeHelper.cs
Normal file
@@ -0,0 +1,86 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
|
||||
using System;
|
||||
using System.DrawingCore;
|
||||
using System.DrawingCore.Imaging;
|
||||
using System.IO;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class VerifyCodeHelper
|
||||
{
|
||||
public byte[] GetVerifyCode()
|
||||
{
|
||||
int codeW = 80;
|
||||
int codeH = 30;
|
||||
int fontSize = 16;
|
||||
string chkCode = string.Empty;
|
||||
//颜色列表,用于验证码、噪线、噪点
|
||||
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
|
||||
//字体列表,用于验证码
|
||||
string[] font = { "Times New Roman" };
|
||||
//验证码的字符集,去掉了一些容易混淆的字符
|
||||
char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
|
||||
Random rnd = new Random();
|
||||
//生成验证码字符串
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
chkCode += character[rnd.Next(character.Length)];
|
||||
}
|
||||
//写入Session、验证码加密
|
||||
WebHelper.WriteSession("wcloud_session_verifycode", Md5.md5(chkCode.ToLower(), 16));
|
||||
//创建画布
|
||||
Bitmap bmp = new Bitmap(codeW, codeH);
|
||||
Graphics g = Graphics.FromImage(bmp);
|
||||
g.Clear(Color.White);
|
||||
//画噪线
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
int x1 = rnd.Next(codeW);
|
||||
int y1 = rnd.Next(codeH);
|
||||
int x2 = rnd.Next(codeW);
|
||||
int y2 = rnd.Next(codeH);
|
||||
Color clr = color[rnd.Next(color.Length)];
|
||||
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
|
||||
}
|
||||
//画验证码字符串
|
||||
for (int i = 0; i < chkCode.Length; i++)
|
||||
{
|
||||
string fnt = font[rnd.Next(font.Length)];
|
||||
Font ft = new Font(fnt, fontSize);
|
||||
Color clr = color[rnd.Next(color.Length)];
|
||||
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
|
||||
}
|
||||
//将验证码图片写入内存流,并将其以 "image/Png" 格式输出
|
||||
MemoryStream ms = new MemoryStream();
|
||||
try
|
||||
{
|
||||
bmp.Save(ms, ImageFormat.Png);
|
||||
return ms.ToArray();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
g.Dispose();
|
||||
bmp.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class GetJsVesion
|
||||
{
|
||||
public static string GetVcode()
|
||||
{
|
||||
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
|
||||
return Convert.ToInt64(ts.TotalSeconds).ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
685
WaterCloud.Code/Util/WebHelper.cs
Normal file
685
WaterCloud.Code/Util/WebHelper.cs
Normal file
@@ -0,0 +1,685 @@
|
||||
/*******************************************************************************
|
||||
* Copyright © 2016 WaterCloud.Framework 版权所有
|
||||
* Author: WaterCloud
|
||||
* Description: WaterCloud快速开发平台
|
||||
* Website:
|
||||
*********************************************************************************/
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Web;
|
||||
|
||||
namespace WaterCloud.Code
|
||||
{
|
||||
public class WebHelper
|
||||
{
|
||||
#region ResolveUrl(解析相对Url)
|
||||
|
||||
/// <summary>
|
||||
/// 解析相对Url
|
||||
/// </summary>
|
||||
/// <param name="relativeUrl">相对Url</param>
|
||||
public static string ResolveUrl(string relativeUrl)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(relativeUrl))
|
||||
return string.Empty;
|
||||
relativeUrl = relativeUrl.Replace("\\", "/");
|
||||
if (relativeUrl.StartsWith("/"))
|
||||
return relativeUrl;
|
||||
if (relativeUrl.Contains("://"))
|
||||
return relativeUrl;
|
||||
return VirtualPathUtility.ToAbsolute(relativeUrl);
|
||||
}
|
||||
|
||||
#endregion ResolveUrl(解析相对Url)
|
||||
|
||||
#region HtmlEncode(对html字符串进行编码)
|
||||
|
||||
/// <summary>
|
||||
/// 对html字符串进行编码
|
||||
/// </summary>
|
||||
/// <param name="html">html字符串</param>
|
||||
public static string HtmlEncode(string html)
|
||||
{
|
||||
return HttpUtility.HtmlEncode(html);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对html字符串进行解码
|
||||
/// </summary>
|
||||
/// <param name="html">html字符串</param>
|
||||
public static string HtmlDecode(string html)
|
||||
{
|
||||
return HttpUtility.HtmlDecode(html);
|
||||
}
|
||||
|
||||
#endregion HtmlEncode(对html字符串进行编码)
|
||||
|
||||
#region UrlEncode(对Url进行编码)
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行编码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
|
||||
public static string UrlEncode(string url, bool isUpper = false)
|
||||
{
|
||||
return UrlEncode(url, Encoding.UTF8, isUpper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行编码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <param name="encoding">字符编码</param>
|
||||
/// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
|
||||
public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
|
||||
{
|
||||
var result = HttpUtility.UrlEncode(url, encoding);
|
||||
if (!isUpper)
|
||||
return result;
|
||||
return GetUpperEncode(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取大写编码字符串
|
||||
/// </summary>
|
||||
private static string GetUpperEncode(string encode)
|
||||
{
|
||||
var result = new StringBuilder();
|
||||
int index = int.MinValue;
|
||||
for (int i = 0; i < encode.Length; i++)
|
||||
{
|
||||
string character = encode[i].ToString();
|
||||
if (character == "%")
|
||||
index = i;
|
||||
if (i - index == 1 || i - index == 2)
|
||||
character = character.ToUpper();
|
||||
result.Append(character);
|
||||
}
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
#endregion UrlEncode(对Url进行编码)
|
||||
|
||||
#region UrlDecode(对Url进行解码)
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
public static string UrlDecode(string url)
|
||||
{
|
||||
return HttpUtility.UrlDecode(url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <param name="encoding">字符编码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码</param>
|
||||
public static string UrlDecode(string url, Encoding encoding)
|
||||
{
|
||||
return HttpUtility.UrlDecode(url, encoding);
|
||||
}
|
||||
|
||||
#endregion UrlDecode(对Url进行解码)
|
||||
|
||||
#region Session操作
|
||||
|
||||
/// <summary>
|
||||
/// 写Session
|
||||
/// </summary>
|
||||
/// <param name="key">Session的键名</param>
|
||||
/// <param name="value">Session的键值</param>
|
||||
public static void WriteSession(string key, string value)
|
||||
{
|
||||
if (key.IsEmpty())
|
||||
return;
|
||||
GlobalContext.HttpContext?.Session.SetString(key, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取Session的值
|
||||
/// </summary>
|
||||
/// <param name="key">Session的键名</param>
|
||||
public static string GetSession(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return GlobalContext.HttpContext?.Session.GetString(key) ?? "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除指定Session
|
||||
/// </summary>
|
||||
/// <param name="key">Session的键名</param>
|
||||
public static void RemoveSession(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
return;
|
||||
}
|
||||
GlobalContext.HttpContext?.Session.Remove(key);
|
||||
}
|
||||
|
||||
#endregion Session操作
|
||||
|
||||
#region Cookie操作
|
||||
|
||||
/// <summary>
|
||||
/// 写cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <param name="strValue">值</param>
|
||||
public static void WriteCookie(string strName, string strValue, CookieOptions option = null)
|
||||
{
|
||||
if (option == null)
|
||||
{
|
||||
option = new CookieOptions();
|
||||
option.Expires = DateTime.Now.AddDays(30);
|
||||
}
|
||||
GlobalContext.HttpContext?.Response.Cookies.Append(strName, strValue, option);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <param name="strValue">值</param>
|
||||
/// <param name="strValue">过期时间(分钟)</param>
|
||||
public static void WriteCookie(string strName, string strValue, int expires)
|
||||
{
|
||||
CookieOptions option = new CookieOptions();
|
||||
option.Expires = DateTime.Now.AddMinutes(expires);
|
||||
GlobalContext.HttpContext?.Response.Cookies.Append(strName, strValue, option);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <returns>cookie值</returns>
|
||||
public static string GetCookie(string strName)
|
||||
{
|
||||
return GlobalContext.HttpContext?.Request.Cookies[strName] ?? "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除Cookie对象
|
||||
/// </summary>
|
||||
/// <param name="CookiesName">Cookie对象名称</param>
|
||||
public static void RemoveCookie(string CookiesName)
|
||||
{
|
||||
GlobalContext.HttpContext?.Response.Cookies.Delete(CookiesName);
|
||||
}
|
||||
|
||||
#endregion Cookie操作
|
||||
|
||||
#region 去除HTML标记
|
||||
|
||||
/// <summary>
|
||||
/// 去除HTML标记
|
||||
/// </summary>
|
||||
/// <param name="NoHTML">包括HTML的源码 </param>
|
||||
/// <returns>已经去除后的文字</returns>
|
||||
public static string NoHtml(string Htmlstring)
|
||||
{
|
||||
//删除脚本
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
|
||||
//删除HTML
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"…", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"—", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"“", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring.Replace("<", "");
|
||||
Htmlstring = Regex.Replace(Htmlstring, @"”", "", RegexOptions.IgnoreCase);
|
||||
Htmlstring.Replace(">", "");
|
||||
Htmlstring.Replace("\r\n", "");
|
||||
|
||||
Htmlstring = HtmlEncoder.Default.Encode(Htmlstring).Trim();
|
||||
return Htmlstring;
|
||||
}
|
||||
|
||||
#endregion 去除HTML标记
|
||||
|
||||
#region 格式化文本(防止SQL注入)
|
||||
|
||||
/// <summary>
|
||||
/// 格式化文本(防止SQL注入)
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static string Formatstr(string html)
|
||||
{
|
||||
System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
html = regex1.Replace(html, ""); //过滤<script></script>标记
|
||||
html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
|
||||
html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
|
||||
html = regex4.Replace(html, ""); //过滤iframe
|
||||
html = regex10.Replace(html, "s_elect");
|
||||
html = regex11.Replace(html, "u_pudate");
|
||||
html = regex12.Replace(html, "d_elete");
|
||||
html = html.Replace("'", "’");
|
||||
html = html.Replace(" ", " ");
|
||||
return html;
|
||||
}
|
||||
|
||||
#endregion 格式化文本(防止SQL注入)
|
||||
|
||||
#region 当前连接
|
||||
|
||||
public static HttpContext HttpContext
|
||||
{
|
||||
get { return GlobalContext.HttpContext; }
|
||||
}
|
||||
|
||||
#endregion 当前连接
|
||||
|
||||
#region 网络信息
|
||||
|
||||
public static string Ip
|
||||
{
|
||||
get
|
||||
{
|
||||
string result = string.Empty;
|
||||
try
|
||||
{
|
||||
if (HttpContext != null)
|
||||
{
|
||||
result = GetWebClientIp();
|
||||
}
|
||||
if (string.IsNullOrEmpty(result))
|
||||
{
|
||||
result = GetLanIp();
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetWebClientIp()
|
||||
{
|
||||
try
|
||||
{
|
||||
string ip = GetWebRemoteIp();
|
||||
foreach (var hostAddress in Dns.GetHostAddresses(ip))
|
||||
{
|
||||
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
return hostAddress.ToString();
|
||||
}
|
||||
else if (hostAddress.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
return hostAddress.MapToIPv4().ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public static string GetLanIp()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
|
||||
{
|
||||
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
return hostAddress.ToString();
|
||||
}
|
||||
else if (hostAddress.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
return hostAddress.MapToIPv4().ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public static string GetWanIp()
|
||||
{
|
||||
string ip = string.Empty;
|
||||
try
|
||||
{
|
||||
string url = "http://www.net.cn/static/customercare/yourip.asp";
|
||||
string html = "";
|
||||
using (var client = new HttpClient())
|
||||
{
|
||||
var reponse = client.GetAsync(url).GetAwaiter().GetResult();
|
||||
reponse.EnsureSuccessStatusCode();
|
||||
html = reponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
if (!string.IsNullOrEmpty(html))
|
||||
{
|
||||
ip = WebHelper.Resove(html, "<h2>", "</h2>");
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
|
||||
private static string GetWebRemoteIp()
|
||||
{
|
||||
try
|
||||
{
|
||||
string ip = HttpContext?.Connection?.RemoteIpAddress.ParseToString();
|
||||
if (HttpContext != null && HttpContext.Request != null)
|
||||
{
|
||||
if (HttpContext.Request.Headers.ContainsKey("X-Real-IP"))
|
||||
{
|
||||
ip = HttpContext.Request.Headers["X-Real-IP"].ToString();
|
||||
}
|
||||
|
||||
if (HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
|
||||
{
|
||||
ip = HttpContext.Request.Headers["X-Forwarded-For"].ToString();
|
||||
}
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public static string UserAgent
|
||||
{
|
||||
get
|
||||
{
|
||||
string userAgent = string.Empty;
|
||||
try
|
||||
{
|
||||
userAgent = HttpContext?.Request?.Headers["User-Agent"];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return userAgent;
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetOSVersion()
|
||||
{
|
||||
var osVersion = string.Empty;
|
||||
try
|
||||
{
|
||||
var userAgent = UserAgent;
|
||||
if (userAgent.Contains("NT 10"))
|
||||
{
|
||||
osVersion = "Windows 10";
|
||||
}
|
||||
else if (userAgent.Contains("NT 6.3"))
|
||||
{
|
||||
osVersion = "Windows 8";
|
||||
}
|
||||
else if (userAgent.Contains("NT 6.1"))
|
||||
{
|
||||
osVersion = "Windows 7";
|
||||
}
|
||||
else if (userAgent.Contains("NT 6.0"))
|
||||
{
|
||||
osVersion = "Windows Vista/Server 2008";
|
||||
}
|
||||
else if (userAgent.Contains("NT 5.2"))
|
||||
{
|
||||
osVersion = "Windows Server 2003";
|
||||
}
|
||||
else if (userAgent.Contains("NT 5.1"))
|
||||
{
|
||||
osVersion = "Windows XP";
|
||||
}
|
||||
else if (userAgent.Contains("NT 5"))
|
||||
{
|
||||
osVersion = "Windows 2000";
|
||||
}
|
||||
else if (userAgent.Contains("NT 4"))
|
||||
{
|
||||
osVersion = "Windows NT4";
|
||||
}
|
||||
else if (userAgent.Contains("Android"))
|
||||
{
|
||||
osVersion = "Android";
|
||||
}
|
||||
else if (userAgent.Contains("Me"))
|
||||
{
|
||||
osVersion = "Windows Me";
|
||||
}
|
||||
else if (userAgent.Contains("98"))
|
||||
{
|
||||
osVersion = "Windows 98";
|
||||
}
|
||||
else if (userAgent.Contains("95"))
|
||||
{
|
||||
osVersion = "Windows 95";
|
||||
}
|
||||
else if (userAgent.Contains("Mac"))
|
||||
{
|
||||
osVersion = "Mac";
|
||||
}
|
||||
else if (userAgent.Contains("Unix"))
|
||||
{
|
||||
osVersion = "UNIX";
|
||||
}
|
||||
else if (userAgent.Contains("Linux"))
|
||||
{
|
||||
osVersion = "Linux";
|
||||
}
|
||||
else if (userAgent.Contains("SunOS"))
|
||||
{
|
||||
osVersion = "SunOS";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogHelper.WriteWithTime(ex);
|
||||
}
|
||||
return osVersion;
|
||||
}
|
||||
|
||||
#endregion 网络信息
|
||||
|
||||
#region IP位置查询
|
||||
|
||||
public static string GetIpLocation(string ipAddress)
|
||||
{
|
||||
string ipLocation = "未知";
|
||||
try
|
||||
{
|
||||
if (!IsInnerIP(ipAddress))
|
||||
{
|
||||
ipLocation = GetIpLocationFromPCOnline(ipAddress);
|
||||
}
|
||||
else
|
||||
{
|
||||
ipLocation = "本地局域网";
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return ipLocation;
|
||||
}
|
||||
return ipLocation;
|
||||
}
|
||||
|
||||
private static string GetIpLocationFromPCOnline(string ipAddress)
|
||||
{
|
||||
string ipLocation = "未知";
|
||||
try
|
||||
{
|
||||
var res = "";
|
||||
using (var client = new HttpClient())
|
||||
{
|
||||
var URL = "http://whois.pconline.com.cn/ip.jsp?ip=" + ipAddress;
|
||||
var response = client.GetAsync(URL).GetAwaiter().GetResult();
|
||||
response.EnsureSuccessStatusCode();
|
||||
res = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
if (!string.IsNullOrEmpty(res))
|
||||
{
|
||||
ipLocation = res.Trim();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
ipLocation = "未知";
|
||||
}
|
||||
return ipLocation;
|
||||
}
|
||||
|
||||
#endregion IP位置查询
|
||||
|
||||
#region 判断是否是外网IP
|
||||
|
||||
public static bool IsInnerIP(string ipAddress)
|
||||
{
|
||||
bool isInnerIp = false;
|
||||
long ipNum = GetIpNum(ipAddress);
|
||||
/**
|
||||
私有IP:A类 10.0.0.0-10.255.255.255
|
||||
B类 172.16.0.0-172.31.255.255
|
||||
C类 192.168.0.0-192.168.255.255
|
||||
当然,还有127这个网段是环回地址
|
||||
**/
|
||||
long aBegin = GetIpNum("10.0.0.0");
|
||||
long aEnd = GetIpNum("10.255.255.255");
|
||||
long bBegin = GetIpNum("172.16.0.0");
|
||||
long bEnd = GetIpNum("172.31.255.255");
|
||||
long cBegin = GetIpNum("192.168.0.0");
|
||||
long cEnd = GetIpNum("192.168.255.255");
|
||||
isInnerIp = IsInner(ipNum, aBegin, aEnd) || IsInner(ipNum, bBegin, bEnd) || IsInner(ipNum, cBegin, cEnd) || ipAddress.Equals("127.0.0.1");
|
||||
return isInnerIp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把IP地址转换为Long型数字
|
||||
/// </summary>
|
||||
/// <param name="ipAddress">IP地址字符串</param>
|
||||
/// <returns></returns>
|
||||
private static long GetIpNum(string ipAddress)
|
||||
{
|
||||
string[] ip = ipAddress.Split('.');
|
||||
long a = int.Parse(ip[0]);
|
||||
long b = int.Parse(ip[1]);
|
||||
long c = int.Parse(ip[2]);
|
||||
long d = int.Parse(ip[3]);
|
||||
|
||||
long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
|
||||
return ipNum;
|
||||
}
|
||||
|
||||
private static bool IsInner(long userIp, long begin, long end)
|
||||
{
|
||||
return (userIp >= begin) && (userIp <= end);
|
||||
}
|
||||
|
||||
#endregion 判断是否是外网IP
|
||||
|
||||
#region html处理
|
||||
|
||||
/// <summary>
|
||||
/// Get part Content from HTML by apply prefix part and subfix part
|
||||
/// </summary>
|
||||
/// <param name="html">souce html</param>
|
||||
/// <param name="prefix">prefix</param>
|
||||
/// <param name="subfix">subfix</param>
|
||||
/// <returns>part content</returns>
|
||||
public static string Resove(string html, string prefix, string subfix)
|
||||
{
|
||||
int inl = html.IndexOf(prefix);
|
||||
if (inl == -1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
inl += prefix.Length;
|
||||
int inl2 = html.IndexOf(subfix, inl);
|
||||
string s = html.Substring(inl, inl2 - inl);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static string ResoveReverse(string html, string subfix, string prefix)
|
||||
{
|
||||
int inl = html.IndexOf(subfix);
|
||||
if (inl == -1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string subString = html.Substring(0, inl);
|
||||
int inl2 = subString.LastIndexOf(prefix);
|
||||
if (inl2 == -1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
string s = subString.Substring(inl2 + prefix.Length, subString.Length - inl2 - prefix.Length);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static List<string> ResoveList(string html, string prefix, string subfix)
|
||||
{
|
||||
List<string> list = new List<string>();
|
||||
int index = prefix.Length * -1;
|
||||
do
|
||||
{
|
||||
index = html.IndexOf(prefix, index + prefix.Length);
|
||||
if (index == -1)
|
||||
{
|
||||
break;
|
||||
}
|
||||
index += prefix.Length;
|
||||
int index4 = html.IndexOf(subfix, index);
|
||||
string s78 = html.Substring(index, index4 - index);
|
||||
list.Add(s78);
|
||||
}
|
||||
while (index > -1);
|
||||
return list;
|
||||
}
|
||||
|
||||
#endregion html处理
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user