初始化项目

This commit is contained in:
2025-11-20 09:50:21 +08:00
commit 94b24e1a5d
4209 changed files with 1570805 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

68
Services/Api/Help.cs Normal file
View File

@@ -0,0 +1,68 @@
using Models;
using Models.ModelItems;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Api
{
//sql
static class Help
{
public static string Init(int keyword, params int[] appid)
{
string sql = $@"Select DISTINCT AuthotypeId, app.IsValid AppIsValid,a.HeadImg, a.Id, a.Uid, a.Pwd, a.CreateTime, b.AuthorityId, c.AuthorityName, b.HotelId, d.Name HotelName_, d.Code, d.GroupId, e.Name HotelGroupsName from UserInfo a
left join UserAuthoes b on a.Id = b.UserId
left join Authority c on b.AuthorityId = c.Id
left join Hotels d on b.HotelId = d.Id
left join HotelGroups e on d.GroupId = e.Id
left join AppAutho aa on c.id = aa.AuthorityId
left join ApplicationDomain app on aa.AppId =app.Id
where a.id = '{keyword}'
and b.AuthotypeId <> '1' and aa.AppId in ('{string.Join("','", appid)}')
and c.IsValid = 0 and app.IsValid = 0";
return sql;
}
}
public class ResData
{
public int Id { get; set; }
//public string Uid { get; set; }
//public string AppName { get; set; }
//public DateTime CreateTime { get; set; }
public int AuthorityId { get; set; }
public string AuthorityName { get; set; }
public int HotelId { get; set; }
public string HotelName { get { return HotelName_.Trim(); } set { HotelName_ = value.Trim(); } }
public string HotelName_ { get; set; } = "";
public string Code { get; set; }
public int GroupId { get; set; }
public string HotelGroupsName { get; set; }
//public int AppIsValid { get; set; }
public string HeadImg { get; set; } = "default.png";
public int AuthotypeId { get; set; }
}
/// <summary>
/// 写数据库日志
/// </summary>
public class DBlog
{
public static void WirtDB(int Count, int uid, int appid)
{
Task.Run(() =>
{
//using (AuthorityDB db = new AuthorityDB())
//{
// db.AuthoRecordes.Add(new AuthoRecord() { Userid = uid, AppId = appid, Count = Count });
// db.SaveChanges();
//}
SqlSugarBase.Db.Insertable(new AuthoRecord() { Userid = uid, AppId = appid, Count = Count }).ExecuteCommand();
//res.Data.Count();
});
}
}
}

295
Services/Api/OTApi.cs Normal file
View File

@@ -0,0 +1,295 @@
using Models;
using Models.ModelItems;
using Models.View;
using Services.Extensions;
using Services.Manager;
using Services.Tool;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using static Services.Tool.HttpRequestHelp;
using System.Security.Cryptography;
namespace Services.Api
{
public class OTApi
{
/// <summary>
/// 登录
/// </summary>
/// <param name="keyword">账号</param>
/// <param name="password">密码</param>
/// <returns></returns>
public static ReturnResult<dynamic> GetUserLoginByApi(string keyword, string password, int appid)
{
// 登录
var isdl = GetLogo(keyword, password);
var res = new ReturnResult<dynamic>();
if (isdl.Status != 200)
{
res.Message = isdl.Message;
res.Status = isdl.Status;
return res;
}
var user = isdl.Data;
// 授权
res = GetAutho(user, appid);
return res;
}
static dynamic ResData(IEnumerable<IEnumerable<IGrouping<int, ResData>>> z)
{
List<dynamic> group = new List<dynamic>();
foreach (var item in z)
{
string groupname = "";
int groupid = 0;
List<dynamic> hoteles = new List<dynamic>();
foreach (var hotel in item)
{
string hotelName = string.Empty;
string Code = "";
int hotelId = 0;
List<dynamic> autho = new List<dynamic>();
foreach (ResData au in hotel)
{
if (string.IsNullOrEmpty(hotelName))
{
hotelName = au.HotelName;
Code = au.Code;
hotelId = au.HotelId;
}
groupname = au.HotelGroupsName;
groupid = au.GroupId;
autho.Add(new { au.AuthotypeId, au.AuthorityId, au.AuthorityName });
}
hoteles.Add(new { Auth = autho, HotelName = hotelName, Code = Code, HotelId = hotelId });
}
group.Add(new
{
HotelGroupsName = groupname,
HotelGroupsId = groupid,
Hotels = hoteles
}
);
}
return group;
}
/// <summary>
/// 验证登录
/// </summary>
/// <param name="keyword"></param>
/// <param name="password"></param>
/// <param name="token">是否返回token</param>
/// <returns></returns>
private static ReturnResult<UserInfo> GetLogo(string keyword, string password)
{
var res = new ReturnResult<UserInfo>();
try
{
//using (AuthorityDB DB = new AuthorityDB())
//{
UserInfo user = SqlSugarBase.Db.Queryable<UserInfo>().First(x=>x.Uid== keyword);
if (user == null)
{
res.Status = 25;
res.Message = "账号不存在~";
return res;
}
UserInfo usernew = new UserInfo() { CreateTime = user.CreateTime, Uid = keyword, Pwd = password };
usernew = usernew.ComputePasswordHash();
if (usernew.Pwd != user.Pwd)
{
res.Status = 50;
res.Message = "密码不正确~";
return res;
}
if (user.EndTime < DateTime.Now)
{
res.Status = 750;
res.Message = "授权过期~";
return res;
}
if (user.IsValid == 1)
{
res.Status = 100;
res.Message = "账号冻结~";
return res;
}
user.Pwd = null;
user.PwdSee = null;
res.Data = user;
res.Status = 200;
//if (token)
//{
// res.Message = TokenHelper.GetToken(new Dictionary<string, object>() { { "data", user } });
//}
//}
}
catch (Exception ex)
{
res.Status = 500;
res.Data = null;
res.Message = ex.Message;
LogHelp.WriteExceptionLog(ex);
}
return res;
}
/// <summary>
/// 微信小程序 密码账号登录
/// </summary>
/// <param name="keyword"></param>
/// <param name="password"></param>
/// <param name="appid"></param>
/// <returns></returns>
public static ReturnResult<dynamic> Wxlog(string keyword, string password, int appid, UserInfo userInfo = null, bool islong = false)
{
var resdata = new ReturnResult<dynamic>();
var result = new ReturnResult<UserInfo>();
if (userInfo == null){
result = OTApi.GetLogo(keyword, password);
}
else
{
result.Status = 200;
result.Data = userInfo;
Logs.WriteTimingPlanLog("用户名:" + keyword + "密码:" + password + "登录成功:" + result.Data );
}
//判断登录
if (result.Status != 200)
{
resdata.Message = result.Message;
resdata.Status = result.Status;
Logs.WriteTimingPlanLog("用户名:" + keyword + "密码:" + password + "登录失败,信息:" +resdata.Message);
return resdata;
}
var res = OTApi.GetAutho(result.Data, appid);
//需要用到写日志
resdata.Message = res.Message;
//判断授权
if (res.Status == 500)
{
resdata.Status = res.Status;
return resdata;
}
float day = 1;
if (islong)
{
day = 30;
}
resdata.Data = new {
error = Cache.CacheHelp.cacheSysErrorInfo.Where(x=>x.userid == result.Data.Id).ToList(),
autho = res.Data,
userinfo = result.Data,
token = TokenHelper.GetToken(new Dictionary<string, object>() { { "data", result.Data } }, day)
};
resdata.Status = 200;
return resdata;
}
/// <summary>
/// 授权权限
/// </summary>
/// <param name="user"></param>
/// <param name="appid"></param>
/// <returns></returns>
private static ReturnResult<dynamic> GetAutho(UserInfo user, int appid)
{
var res = new ReturnResult<dynamic>();
try
{
var app = Cache.CacheHelp.cacheSysApp.FirstOrDefault(x => x.Id == appid);
string appname = app == null ? "" : app.AppName;
if (app == null)
throw new Exception("App不存在~");
//var db = DB.Database.SqlQuery<ResData>(Help.Init(user.Id, appid)).ToList();
var db = SqlSugarBase.Db.Ado.SqlQuery<ResData>(Help.Init(user.Id, appid)).ToList();
//var name = db.Distinct().Select(Help.Init(user.Id, appid)).ToList();
//酒店父辈分组
var s = db.GroupBy(X => X.GroupId);
//酒权限分组
var z = s.Select(x => x.GroupBy(u => u.HotelId));
res.Data = ResData(z);
//返回用户Id 头像 权限数量
res.Status = 200;
res.Message = new ArrayList { user.Id, user.HeadImg, db.Count, appname };
}
catch (Exception ex)
{
res.Status = 500;
res.Data = null;
res.Message = ex.Message;
LogHelp.WriteExceptionLog(ex);
}
return res;
}
/// <summary>
/// 微信小程序通过token登录
/// </summary>
/// <param name="token"></param>
/// <param name="appid"></param>
/// <returns></returns>
public static ReturnResult<dynamic> WxlogToken(string token,int appid,string UserAgent)
{
var app = Cache.CacheHelp.cacheSysApp.FirstOrDefault(x => x.Id == appid);
var resdata = new ReturnResult<dynamic>();
var userinfo = new UserInfo();
var chektoken = TokenHelper.CheckToken(token);
if (!string.IsNullOrEmpty(chektoken))
{
chektoken = chektoken.Replace("{{", "{").Replace("}}", "}");
userinfo = JsonConvert.DeserializeObject<UserInfo>(chektoken);
resdata = OTApi.Wxlog(userinfo.Uid, userinfo.Pwd, appid, userinfo);
}
else
{
resdata.Status = 1024;
resdata.Data = null;
resdata.Message = "token过期~";
}
var Ip = IPHelper.GetIP();
DbLog log = new DbLog() { Uid = userinfo.Uid, Ip = Ip, Client = UserAgent };
var Message = resdata.Message;
Task.Run(() =>
{
try
{
Data loc = HttpRequestHelp.GetIp($@"https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={log.Ip}&co=&resource_id=6006&oe=utf8");
if (loc != null && loc.status == 0)
{
if (loc.data.Count > 0)
{
log.location = loc.data[0].location;
}
}
DbLogServer.WriteDbLog($"{userinfo.Uid}请求应用 {(app == null ? "app[]":app.AppName)}({appid}) 授权" + (resdata.Status == 200 ? "请求成功~" : "请求失败~"), 0, log);
if (resdata.Status == 200)
DBlog.WirtDB(Message[2], Message[0], appid);
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
});
if (resdata.Status == 200)
{
resdata.Message = "请求成功~";
}
return resdata;
}
}
}

109
Services/App.config Normal file
View File

@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-8.0.29.0" newVersion="8.0.29.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.DependencyInjection.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.FileProviders.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.FileSystemGlobbing" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.FileProviders.Physical" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.4.0" newVersion="3.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Options" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Caching.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.4.0" newVersion="3.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration.Binder" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Encodings.Web" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.1" newVersion="5.0.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration.FileExtensions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.23.0" newVersion="3.1.23.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /></startup></configuration>

View File

@@ -0,0 +1,87 @@
// Services.Cache.BaseCacheHelpRedis
using System;
using System.Collections.Generic;
using Org.BouncyCastle.Utilities;
using Services.Tool;
using StackExchange.Redis;
public abstract class BaseCacheHelpRedis
{
public static T GetCache<T>(string key, Func<T> setAcrion, TimeSpan? expiry = null)
{
if (RedisHelper.CheckKey(key))
{
return RedisHelper.StringGet<T>(key);
}
T val = setAcrion();
if (val != null)
{
RedisHelper.StringSet(key, val, expiry);
}
return val;
}
public static void SetCache<T>(string key, Func<T> setAcrion, TimeSpan? expiry = null)
{
T val = setAcrion();
if (val != null)
{
RedisHelper.StringSet(key, val, expiry);
}
}
public static T GetVaue<T>(string key)
{
if (RedisHelper.CheckKey(key))
{
return RedisHelper.StringGet<T>(key);
}
return default(T);
}
public static void ClearCache(string key)
{
if (RedisHelper.CheckKey(key))
{
RedisHelper.RemoveKey(key);
}
}
public static void ClearCacheList(List<string> keyList)
{
RedisHelper.RemoveKeyList(keyList);
}
public static T GetHashCache<T>(string key, string sid, Func<T> setAcrion)
{
if (RedisHelper.HashExists(key, sid))
{
return RedisHelper.HashGet<T>(key, sid);
}
T val = setAcrion();
if (val != null)
{
RedisHelper.HashSet(key, sid, val);
}
return val;
}
public static void SetHashCache<T>(string key, string sid, T model)
{
RedisHelper.HashSet(key, sid, model);
}
public static void SetHashCache<T>(string key, Dictionary<string, T> dic)
{
RedisHelper.HashSet(key, dic);
}
public static Dictionary<string, T> GetHashAllCache<T>(string key)
{
return RedisHelper.HashGetAll<T>(key);
}
public static bool CheckKey(string key)
{
return RedisHelper.CheckKey(key);
}
}

213
Services/Cache/CacheHelp.cs Normal file
View File

@@ -0,0 +1,213 @@
using Models;
using Models.ApiModei;
using Models.ModelItems;
using Models.View;
using Org.BouncyCastle.Utilities;
using Services.Manager;
using Services.Tool;
using SqlSugar;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Services.Cache.CacheHelp;
namespace Services.Cache
{
public class CacheHelp
{
public enum syskey
{
sysAuthorityListKey,
sysHotelsListKey,
sysGsInfoListKey,
sysAuthoStatusTypeListKey,
sysOrganizationListKey,
sysOrgAuthorityListKey,
sysOrgUserListKey,
sysErrorInfoListKey,
sysUserAuthoListKey,
sysAppsListKey,
sysUserInfoListKey,
sysAppAuthoListKey,
sysHoteldGroupsListKey,
sysView_UOAListKey,
sysView_UAListKey,
sysDbLogListKey,
sysHostsListKey,
Appversions,
sysMACLogs,
sysALLqxListKey,
sysQxIfoListKey,
sysView_AppAuthoListKey,
}
private static readonly string sysHotelsListKey = "autho_sysHotelsListKey";
private static readonly string sysHostsListKey = "autho_sysHostsListKey";
private static readonly string sysHoteldGroupsListKey = "autho_sysHoteldGroupsListKey";
private static readonly string Appversions = "autho_Appversions";
private static readonly string sysView_UOAListKey = "autho_sysView_UOAListKey";
private static readonly string sysView_UAListKey = "autho_sysView_UAListKey";
private static readonly string sysView_AppAuthoListKey = "autho_sysView_AppAuthoListKey";
private static readonly string sysAuthorityLisKey = "autho_sysAuthorityListKey";
private static readonly string sysAuthoStatusTypeLisKey = "autho_sysAuthoStatusTypeListKey";
private static readonly string sysOrganizationLisKey = "autho_sysOrganizationListKey";
private static readonly string sysOrgAuthorityLisKey = "autho_sysOrgAuthorityListKey";
private static readonly string sysOrgUserLisKey = "autho_sysOrgUserListKey";
private static readonly string sysUserAuthoLisKey = "autho_sysUserAuthoListKey";
private static readonly string sysAppsListKey = "autho_sysAppsListKey";
private static readonly string sysErrorInfoListKey = "autho_sysErrorInfoListKey";
private static readonly string sysMACLogs = "autho_sysMACLogs";
private static readonly string sysView_MAClog = "autho_sysView_MAClog";
private static readonly string sysGsInfoListKey = "autho_sysGsInfoListKey";
private static readonly string sysQxIfoListKey = "autho_sysQxIfoListKey";
private static readonly string sysUserInfoListKey = "autho_sysUserInfoListKey";
private static readonly string sysAppAuthoListKey = "autho_sysAppAuthoListKey";
private static readonly string sysDbLogListKey = "autho_sysDbLogListKey";
//酒店信息
public static List<HotelGroups> gh => CacheHelp.cacheHoteldGroups.Where(x => x.ParentId == 1).ToList();
public static List<ReturnResult> HoteldGroupsinfo
{
get
{
List<ReturnResult> HoteldGroupsinfos = new List<ReturnResult>();
foreach (var item in gh)
{
var data = CacheHelp.cacheHoteldGroups.Where(x => x.ParentId == item.Id).ToList();
data.Insert(0, item);
HoteldGroupsinfos.Add(new ReturnResult()
{
Message = SyncHotelServer.FindHotel(item.Id).Count,
Status = item.Id
});
}
return HoteldGroupsinfos;
}
}
public static List<View_UserInfo> cacheView_UserInfo => GetCachesys(new View_UserInfo(), sysUserInfoListKey);
public static List<View_MAClog> cachesysMACLogs => GetCachesys(new View_MAClog(), sysMACLogs);
public static List<ErrorInfo> cacheSysErrorInfo => GetCachesys(new ErrorInfo(), sysErrorInfoListKey);
public static List<ApplicationDomain> cacheSysApp => GetCachesys(new ApplicationDomain(), sysAppsListKey);
public static List<GsInfo> cacheSysGsInfo => GetCachesys(new GsInfo(), sysGsInfoListKey, "exec Findgsall");
public static List<Authority> cacheSysAutho => GetCachesys(new Authority(), sysAuthorityLisKey);
public static List<AuthoStatusType> cacheSysAuthoStatusType => GetCachesys(new AuthoStatusType(), sysAuthoStatusTypeLisKey);
public static List<Organization> cacheSysOrganization => GetCachesys(new Organization(), sysOrganizationLisKey);
public static List<OrgAuthority> cacheSysOrgAuthority => GetCachesys(new OrgAuthority(), sysOrgAuthorityLisKey);
public static List<OrgUsers> cacheSysOrgUser => GetCachesys(new OrgUsers(), sysOrgUserLisKey);
public static ISugarQueryable<UserAuthoes> cacheSysUserAutho => SqlSugarBase.Db.Queryable<UserAuthoes>();
//GetCachesys(new UserAuthoes(), sysUserAuthoLisKey);
//从视图View_UserInfo读取信息包括人员信息和部分所属组织信息。
public static List<View_UserInfo> cacheSysUserInfo => GetCachesys(new View_UserInfo(), sysUserInfoListKey);
public static List<AppAutho> cacheSysAppAutho => GetCachesys(new AppAutho(), sysAppAuthoListKey);
public static List<View_UOA> cacheView_UOA => GetCachesys(new View_UOA(), sysView_UOAListKey);
/// <summary>
/// GetCachesys(new View_UA(), sysView_UAListKey);
/// </summary>
public static List<View_AppAutho> cacheView_AppAutho => GetCachesys(new View_AppAutho(), sysView_AppAuthoListKey);
public static List<Hotels> cacheHotels => GetCachesys(new Hotels(), sysHotelsListKey, "select * FROM Hotels ORDER BY CreateTime DESC");
public static List<Hosts> cacheHosts => GetCachesys(new Hosts(), sysHostsListKey);
public static List<HotelGroups> cacheHoteldGroups => GetCachesys(new HotelGroups(), sysHoteldGroupsListKey);
public static int cacheDbLogs => GetCachesys(new int(), sysDbLogListKey, "select count(*) FROM DbLog")[0];
public static string cacheAppversions => BaseCacheHelpRedis.GetCache<string>(Appversions, delegate
{
return DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
});
private static List<T> GetCachesys<T>(T model, string strkey, string SQL = "")
{
return BaseCacheHelpRedis.GetCache(strkey, delegate
{
List<T> result = new List<T>();
string sql = string.Empty;
try
{
var tablename = (model.GetType().Name == "UserAutho" ? "UserAuthoes" : model.GetType().Name == "OrgUser" ? "OrgUsers" : model.GetType().Name);
//模型复数 未设置 现在修改查询
sql = "select * from " + tablename;
if (!string.IsNullOrEmpty(SQL))
{
sql = SQL;
}
//authorityDB.Database.CommandTimeout = int.MaxValue;
//SqlSugarBase.Db.Ado.CommandTimeOut = int.MaxValue;
result = SqlSugarBase.Db.Ado.SqlQuery<T>(sql).ToList();
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex, sql);
}
return result;
});
}
public static void Removesys(syskey? syskeys)
{
if (syskeys != null)
{
BaseCacheHelpRedis.ClearCache("autho_" + syskeys);
}
else
{
//for (int i = 0; i <= (int)syskey.sysView_AppAuthoListKey; i++)
//{
// syskeys = (syskey)i;
// BaseCacheHelpRedis.ClearCache("autho_" + syskeys);
//}
RemovesysEnumAll();
}
}
private static void RemovesysEnumAll()
{
//取到所有枚举变量的字符串,并加前缀。
List<string> keysList = new List<string>();
syskey syskeys;
for (int i = 0; i <= (int)syskey.sysView_AppAuthoListKey; i++)
{
syskeys = (syskey)i;
keysList.Add("autho_" + syskeys);
}
BaseCacheHelpRedis.ClearCacheList(keysList);
}
public static void Removesyss(syskey? syskeys)
{
if (syskeys != null)
{
BaseCacheHelpRedis.ClearCache("authority_" + syskeys);
}
else
{
for (int i = 0; i <= (int)syskey.sysView_AppAuthoListKey; i++)
{
syskeys = (syskey)i;
BaseCacheHelpRedis.ClearCache("authority_autho_" + syskeys.ToString());
}
}
}
public static void Updatesys(syskey? syskeys)
{
//HoteldGroupsinfo = null;
Removesys(null);
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Enums
{
/// <summary>
/// 缓存的时间类别
/// </summary>
public enum CacheTimeType
{
/// <summary>
/// 按照分钟模式
/// </summary>
ByMinutes,
/// <summary>
/// 按照小时模式
/// </summary>
ByHours,
/// <summary>
/// 按照天模式
/// </summary>
ByDays,
/// <summary>
/// 按照年模式
/// </summary>
ByYears
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Enums
{
public enum LoginInfoType
{
/*
* 添加账户类型的时候枚举值为2的倍数
*
*/
/// <summary>
/// 管理人员
/// </summary>
[Description("管理人员")]
Manager = 2,
/// <summary>
/// 用户
/// </summary>
[Description("用户")]
User = 4,
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Enums
{
/// <summary>
/// 操作权限级别
/// </summary>
public enum OperationLevel
{
/// <summary>
/// 只读
/// </summary>
[Description("只读")]
ReadOnly = 10,
/// <summary>
/// 读写
/// </summary>
[Description("读写")]
ReadWrite = 20,
/// <summary>
/// 完整
/// </summary>
[Description("完整")]
Full = 30,
}
}

View File

@@ -0,0 +1,62 @@
using System.ComponentModel;
namespace Services.Enums
{
public enum OrderStatus
{
/// <summary>
/// 已下单待转内部单
/// </summary>
[Description("已下单待转M/O")]
PlaceOrder = 1,
/// <summary>
/// 已转M/O待制条码
/// </summary>
[Description("已转M/O待制条码")]
MOrder = 2,
/// <summary>
/// 已制SN待制计划
/// </summary>
[Description("已制SN待制计划")]
SnRules = 3,
/// <summary>
/// 已制计划待生产
/// </summary>
[Description("已制计划待生产")]
ProductionPlan = 4,
/// <summary>
/// 生产中
/// </summary>
[Description("生产中")]
InProduction = 5,
/// <summary>
/// 完成生产
/// </summary>
[Description("完成生产")]
CompleteProduction = 6,
/// <summary>
/// 已完成
/// </summary>
[Description("已完成")]
Completed = 7,
/// <summary>
/// 取消
/// </summary>
[Description("取消")]
Cancel = -1,
/// <summary>
/// 暂停中
/// </summary>
[Description("暂停中")]
Suspend = -2,
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Enums
{
/// <summary>
/// 短字符串版本
/// </summary>
public enum ShortStringVersion
{
/// <summary>
/// 版本1
/// </summary>
[MaxLength(6)]
[Description("版本1")]
Version_1 = 5,
/// <summary>
/// 版本2
/// </summary>
[MaxLength(8)]
[Description("版本2")]
Version_2 = 4,
/// <summary>
/// 版本3
/// </summary>
[Description("版本3")]
[MaxLength(10)]
Version_3 = 3,
/// <summary>
/// 版本4
/// </summary>
[MaxLength(15)]
[Description("版本4")]
Version_4 = 2,
/// <summary>
/// 版本5
/// </summary>
[Description("版本5")]
[MaxLength(30)]
Version_5 = 1
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Enums
{
public enum StationType
{
/// <summary>
/// 测试
/// </summary>
[Description("Test")]
Test = 100,
/// <summary>
/// 测试2
/// </summary>
[Description("Test2")]
Test2 = 120,
/// <summary>
/// 组装
/// </summary>
[Description("Assem")]
Assem = 200,
/// <summary>
/// 质量保证
/// </summary>
[Description("QA")]
QA = 300,
}
}

View File

@@ -0,0 +1,149 @@
using Services.Enums;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace Services.Extensions
{
/// <summary>
/// 缓存扩展
/// </summary>
public static class CacheExtensions
{
public static MvcHtmlString Cache(this HtmlHelper htmlHelper, string cacheName, Func<object> func, CacheTimeType cacheTimeType, int cacheTime)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, func().ToString(), cacheTimeType, cacheTime);
}
return MvcHtmlString.Create(CacheExtensions.GetCache<string>(cacheName));
}
/// <summary>
/// 检查缓存名是否存在如果存在则返回True
/// </summary>
/// <param name="cacheName">缓存的枚举类</param>
public static bool CheckCache(string cacheName)
{
return HttpRuntime.Cache[cacheName.ToString()] != null;
}
/// <summary>
/// 获取缓存,未做校验,每次取缓存的时候需要判断缓存是否存在
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheName"></param>
/// <param name="varName"></param>
/// <returns></returns>
public static T GetCache<T>(string cacheName)
{
return (T)((object)HttpRuntime.Cache[cacheName]);
}
public static T GetCacheWithSet<T>(string cacheName, Func<T> valueFunc, CacheTimeType cacheTimeType, int times)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, valueFunc(), cacheTimeType, times);
}
return CacheExtensions.GetCache<T>(cacheName);
}
public static T GetCacheWithSet<T>(string cacheName, Func<T> valueFunc)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, valueFunc());
}
return CacheExtensions.GetCache<T>(cacheName);
}
/// <summary>
/// 获取缓存集合,未做校验,每次取缓存的时候需要判断缓存是否存在
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheName"></param>
/// <param name="varName"></param>
/// <returns></returns>
public static List<T> GetCacheList<T>(string cacheName)
{
return (List<T>)HttpRuntime.Cache[cacheName];
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="cacheName"></param>
/// <param name="value"></param>
/// <param name="cacheTimeType"></param>
/// <param name="cacheTime"></param>
public static void SetCache(string cacheName, object value, CacheTimeType cacheTimeType, int cacheTime)
{
switch (cacheTimeType)
{
case CacheTimeType.ByMinutes:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddMinutes((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByHours:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddHours((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByDays:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddDays((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByYears:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddYears(cacheTime), TimeSpan.Zero);
return;
default:
return;
}
}
public static void SetCache(string cacheName, object value)
{
HttpRuntime.Cache.Insert(cacheName, value);
}
public static List<string> GetAllCache()
{
List<string> list = new List<string>();
IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add(enumerator.Key.ToString());
}
return list;
}
/// <summary>
/// 清除指定缓存
/// </summary>
/// <param name="cacheName"></param>
public static void ClearCache(string cacheName)
{
if (CacheExtensions.CheckCache(cacheName))
{
HttpRuntime.Cache.Remove(cacheName);
}
}
/// <summary>
/// 重置缓存
/// </summary>
/// <param name="cacheName"></param>
/// <param name="value"></param>
public static void RestCache(string cacheName, object value)
{
if (CacheExtensions.CheckCache(cacheName))
{
HttpRuntime.Cache[cacheName] = value;
return;
}
CacheExtensions.SetCache(cacheName, value);
}
}
}

View File

@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Services.Extensions
{
/// <summary>
/// cookie扩展
/// </summary>
public static class CookieExtensions
{
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string strValue)
{
HttpCookie httpCookie = HttpContext.Current.Request.Cookies[strName];
if (httpCookie == null)
{
httpCookie = new HttpCookie(strName);
}
httpCookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(httpCookie);
}
/// <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)
{
HttpCookie httpCookie = HttpContext.Current.Request.Cookies[strName];
if (httpCookie == null)
{
httpCookie = new HttpCookie(strName);
}
httpCookie.Value = strValue;
httpCookie.Expires = DateTime.Now.AddMinutes((double)expires);
HttpContext.Current.Response.AppendCookie(httpCookie);
}
/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
/// <summary>
/// 检查Cookie,如果存在则为true
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
public static bool CheckCookie(string strName)
{
return HttpContext.Current.Request.Cookies[strName] != null;
}
/// <summary>
/// 删除Cookie
/// </summary>
/// <param name="strName"></param>
public static void RemoveCookie(string strName)
{
HttpContext.Current.Request.Cookies.Remove(strName);
}
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 异常扩展
/// </summary>
public class CustomException : ApplicationException
{
//记录异常的类型
private CustomExceptionType exceptionType;
public CustomException(CustomExceptionType type) : base()
{
this.exceptionType = type;
}
public CustomException(CustomExceptionType type, string message) : base(message)
{
this.exceptionType = type;
}
public CustomException(string message) : base(message)
{
this.exceptionType = CustomExceptionType.InputValidation;
}
//序列化
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
//重写message方法,以让它显示相应异常提示信息
public override string Message
{
get
{
//根据异常类型从message.xml中读取相应异常提示信息
return base.Message;
//return string.Format(XmlMessageManager.GetXmlMessage((int)exceptionType), base.Message);
}
}
}
public enum CustomExceptionType
{
InputValidation = 1,
hint = 2,
Warning = 3,
Unknown = 8
}
}

View File

@@ -0,0 +1,130 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 枚举扩展
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// 对枚举器的每个元素执行指定的操作
/// </summary>
/// <typeparam name="T">枚举器类型参数</typeparam>
/// <param name="source">枚举器</param>
/// <param name="action">要对枚举器的每个元素执行的委托</param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source.IsNullOrEmpty<T>() || action == null)
{
return;
}
foreach (T obj in source)
{
action(obj);
}
}
/// <summary>
/// 指示指定的枚举器是null还是没有任何元素
/// </summary>
/// <typeparam name="T">枚举器类型参数</typeparam>
/// <param name="source">要测试的枚举器</param>
/// <returns>true:枚举器是null或者没有任何元素 false:枚举器不为null并且包含至少一个元素</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
return source == null || !source.Any<T>();
}
/// <summary>
/// 得到枚举中文备注
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static string GetEnumDesc(this System.Enum enumValue)
{
string value = enumValue.ToString();
System.Reflection.FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length == 0) //当描述属性没有时,直接返回名称
return value;
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}
public static string GetEnumDesc(this Type enumType, object val)
{
string enumvalue = Enum.GetName(enumType, val);
if (string.IsNullOrEmpty(enumvalue))
{
return "";
}
FieldInfo finfo = enumType.GetField(enumvalue);
object[] enumAttr = finfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (enumAttr.Length > 0)
{
DescriptionAttribute desc = (DescriptionAttribute)enumAttr[0];
if (desc != null)
{
return desc.Description;
}
}
return enumvalue;
}
/// <summary>
/// 获取所有的枚举描述和值
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static List<EnumDto> GetEnumListItem(this Type type)
{
List<EnumDto> list = new List<EnumDto>();
// 循环枚举获取所有的Fields
foreach (var field in type.GetFields())
{
// 如果是枚举类型
if (field.FieldType.IsEnum)
{
object tmp = field.GetValue(null);
Enum enumValue = (Enum)tmp;
int intValue = Convert.ToInt32(enumValue);
string showName = enumValue.GetEnumDesc(); // 获取描述和排序
list.Add(new EnumDto { Value = intValue, Description = showName });
}
}
//返回
return list;
}
public class EnumDto
{
/// <summary>
/// 枚举code
/// </summary>
public string Code { get; set; }
/// <summary>
/// 值
/// </summary>
public int Value { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
}
}
}

View File

@@ -0,0 +1,469 @@
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Linq
{
public static class LinqExtensions
{
/// <summary>通过页面控件动态构建查询</summary>
public static IQueryable<TSource> WhereDynamic<TSource>(this IQueryable<TSource> source,
NameValueCollection nameValues) where TSource : class
{
if (nameValues.Count > 0)
{
//构建 c=>Body中的c
ParameterExpression param = Expression.Parameter(typeof(TSource), "c");
//构建c=>Body中的Body
var body = GetExpressoinBody(param, nameValues);
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, param);
//传到Where中当做参数类型为Expression<Func<T,bool>>
return source.Where(expression);
}
}
return source;
}
/// <summary>构建body</summary>
private static Expression GetExpressoinBody(ParameterExpression param, NameValueCollection nameValues)
{
var list = new List<Expression>();
if (nameValues.Count > 0)
{
var plist = param.Type.GetRuntimeProperties().ToDictionary(z => z.Name);//可以加缓存改善性能
foreach (var item in nameValues.AllKeys)
if (item.EndsWith(">") || item.EndsWith(">="))//可能大小查询
{
bool isEqual = item.EndsWith(">=");
string key = isEqual ? item.TrimEnd('=').TrimEnd('>') : item.TrimEnd('>');
if (!plist.ContainsKey(key) || nameValues[item].Length <= 0) continue;
var rType = plist[key].GetMethod.ReturnType;
if (rType == typeof(string)) continue;
var e1 = Expression.Property(param, key);
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
//list.Add(Expression.GreaterThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(dValue, rType), isEqual));
else if (plist[key].GetMethod.ReturnType.GenericTypeArguments.Count() > 0 && TryParser(nameValues[item], plist[key].GetMethod.ReturnType.GenericTypeArguments[0], out dValue))
//list.Add(Expression.GreaterThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(dValue, rType), isEqual));
else if (rType == typeof(DateTime?))
{
DateTime enddate = nameValues[item].ToDateTime().GetValueOrDefault();
//list.Add(Expression.GreaterThan(e1, Expression.Constant(enddate, typeof(DateTime?))));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(enddate, typeof(DateTime?)), isEqual));
}
}
else if (item.EndsWith("<") || item.EndsWith("<="))//可能大小查询
{
bool isEqual = item.EndsWith("<=");
string key = isEqual ? item.TrimEnd('=').TrimEnd('<') : item.TrimEnd('<');
if (!plist.ContainsKey(key) || nameValues[item].Length <= 0) continue;
var rType = plist[key].GetMethod.ReturnType;
if (rType == typeof(string)) continue;
var e1 = Expression.Property(param, key);
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
{
if (rType == typeof(DateTime)) dValue = ((DateTime)dValue).AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterLessThan(e1, Expression.Constant(dValue, rType), isEqual));
}
else if (plist[key].GetMethod.ReturnType.GenericTypeArguments.Count() > 0 && TryParser(nameValues[item], plist[key].GetMethod.ReturnType.GenericTypeArguments[0], out dValue))
{
if (plist[key].GetMethod.ReturnType.GenericTypeArguments[0] == typeof(DateTime)) dValue = ((DateTime)dValue).AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterLessThan(e1, Expression.Constant(dValue, rType), isEqual));
}
else if (rType == typeof(DateTime?))
{
DateTime enddate = nameValues[item].ToDateTime().GetValueOrDefault().AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(enddate, typeof(DateTime?))));
list.Add(AddGreaterLessThan(e1, Expression.Constant(enddate, typeof(DateTime?)), isEqual));
}
}
else if (plist.ContainsKey(item) && nameValues[item].Length > 0)
{
var e1 = Expression.Property(param, item);
var rType = plist[item].GetMethod.ReturnType;
if (rType == typeof(string))//可能是like查询
{
var value = nameValues[item].Trim('%');
var e2 = Expression.Constant(value, rType);
if (nameValues[item].StartsWith("%") && nameValues[item].EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (nameValues[item].StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (nameValues[item].EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
else if (nameValues[item].IndexOf(",") > 0)//可能是in查询
{
if (rType == typeof(short))
{
var searchList = TryParser<short>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
else if (rType == typeof(int))
{
var searchList = TryParser<int>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
else if (rType == typeof(long))
{
var searchList = TryParser<long>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
}
else
{
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
list.Add(Expression.Equal(e1, Expression.Constant(dValue, rType)));
}
}
}
return list.Count > 0 ? list.Aggregate(Expression.AndAlso) : null;
}
private static List<T> TryParser<T>(string value)
{
string[] searchArray = value.Split(',');
List<T> dList = new List<T>();
foreach (var l in searchArray)
{
try
{
T dValue = (T)Convert.ChangeType(l, typeof(T));
dList.Add(dValue);
}
catch { }
}
return dList;
}
private static bool TryParser(string value, Type outType, out object dValue)
{
try
{
dValue = Convert.ChangeType(value, outType);
return true;
}
catch
{
dValue = null;
return false;
}
}
//大于
private static Expression AddGreaterGreaterThan(Expression exleft, Expression exright, bool Equal)
{
if (Equal)
{
return Expression.GreaterThanOrEqual(exleft, exright);
}
else
{
return Expression.GreaterThan(exleft, exright);
}
}
//大于
private static Expression AddGreaterLessThan(Expression exleft, Expression exright, bool Equal)
{
if (Equal)
{
return Expression.LessThanOrEqual(exleft, exright);
}
else
{
return Expression.LessThan(exleft, exright);
}
}
/// <summary>
/// 从 System.Collections.Generic.IQueryable`1 创建一个 System.Collections.Generic.List`1。并在集合末尾添加一个默认值为空的TSource实例
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">要从其创建 System.Collections.Generic.List`1 的 System.Collections.Generic.IEnumerable`1。</param>
/// <returns>一个包含输入序列中元素的 System.Collections.Generic.List`1。</returns>
public static List<TSource> ToListAndAddEmpty<TSource>(this IQueryable<TSource> source) where TSource : class
{
List<TSource> list = source.ToList();
TSource addmodel = Activator.CreateInstance<TSource>();
list.Add(addmodel);
return list;
}
/// <summary>
/// 从 System.Collections.Generic.IEnumerable`1 创建一个 System.Collections.Generic.List`1。并在集合末尾添加一个默认值为空的TSource实例
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">要从其创建 System.Collections.Generic.List`1 的 System.Collections.Generic.IEnumerable`1。</param>
/// <returns>一个包含输入序列中元素的 System.Collections.Generic.List`1。</returns>
public static List<TSource> ToListAndAddEmpty<TSource>(this IEnumerable<TSource> source) where TSource : class
{
List<TSource> list = source.ToList();
TSource addmodel = Activator.CreateInstance<TSource>();
list.Add(addmodel);
return list;
}
/// <summary>
/// 动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <typeparam name="TKey">由 keySelector 表示的函数返回的键类型。</typeparam>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiled">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource, TKey>(this IQueryable<TSource> source, string keyword, params Expression<Func<TSource, TKey>>[] keySelector)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keySelector)
{
string[] paramKs = item.Body.ToString().Split('.');
var e1 = Expression.Property(paramT, paramKs[1]);//c.user
for (int i = 2; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiled">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource>(this IQueryable<TSource> source, string keyword, params string[] keyfiled)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keyfiled)
{
string[] paramKs = item.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 外键表动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <typeparam name="TKey">由 keySelector 表示的函数返回的键类型。</typeparam>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiledn">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource, TKey>(this IQueryable<TSource> source, string keyword, string keyfiled, params Expression<Func<TSource, TKey>>[] keySelector)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keySelector)
{
string[] paramKs = item.Body.ToString().Split('.');
var e1 = Expression.Property(paramT, paramKs[1]);//c.user
for (int i = 2; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
e1 = Expression.Property(e1, keyfiled);//c.user.ID
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态排序
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要排序查找的值序列。</param>
/// <param name="keyfiled">排序字段</param>
/// <param name="type">排序类型0不排序1升序2降序</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> OrderByQueryable<TSource>(this IQueryable<TSource> source, string keyfiled, int type)
{
try
{
if (type == 0) return source;//不排序
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
string[] paramKs = keyfiled.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
dynamic expression = Expression.Lambda(e1, paramT);
switch (type)
{
case 1:
source = Queryable.OrderBy(source, expression);
break;
case 2:
source = Queryable.OrderByDescending(source, expression);
break;
default:
break;
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态排序
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要排序查找的值序列。</param>
/// <param name="keyfiled">排序字段</param>
/// <param name="type">排序类型0不排序1升序2降序</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IEnumerable<TSource> OrderByQueryable<TSource>(this IEnumerable<TSource> source, string keyfiled, int type)
{
try
{
if (type == 0) return source;//不排序
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
string[] paramKs = keyfiled.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
dynamic expression = Expression.Lambda(e1, paramT);
switch (type)
{
case 1:
source = Queryable.OrderBy(source.AsQueryable(), expression);
break;
case 2:
source = Queryable.OrderByDescending(source.AsQueryable(), expression);
break;
default:
break;
}
}
catch
{
}
return source;
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 对象扩展
/// </summary>
public static class ModelExtensions
{
/// <summary>
/// 创建一个新的类型的对象,并将现有对象的属性值赋给新对象相同名称的属性
/// </summary>
/// <typeparam name="T">新对象的类型</typeparam>
/// <param name="source">现有对象</param>
/// <returns>新的对象</returns>
public static T ToModel<T>(this object source) where T : new()
{
if (source == null)
{
return default(T);
}
return Activator.CreateInstance<T>().UpdateFrom(source, new string[0]);
}
/// <summary>
/// 将源对象的属性值赋给目标对象相同名称的属性
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="target">目标对象</param>
/// <param name="source">源对象</param>
/// <param name="copyPropertyName">需要复制的属性名,为空时表示复制全部</param>
/// <returns>目标类型</returns>
public static T UpdateFrom<T>(this T target, object source, params string[] copyPropertyName)
{
if (target == null)
{
return default(T);
}
if (source == null)
{
return target;
}
Type typeFromHandle = typeof(T);
foreach (PropertyInfo obj in source.GetType().GetProperties())
{
//PropertyDescriptor propertyDescriptor = (PropertyDescriptor)obj;
if (copyPropertyName == null || copyPropertyName.Length == 0 || copyPropertyName.Contains(obj.Name))
{
PropertyInfo property = typeFromHandle.GetProperty(obj.Name, BindingFlags.Instance | BindingFlags.Public);
if (property != null && property.CanWrite)
{
property.SetValue(target, obj.GetValue(source, null), null);
}
}
}
return target;
}
}
}

View File

@@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System
{
/// <summary>
/// 字符串转换扩展
/// </summary>
public static class SafeInputExtensions
{
/// <summary>
/// 将字符串转换成Int类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static short ToShort(this object str)
{
short result = 0;
if (str != null)
{
short.TryParse(str.ToString(), out result);
}
return result;
}
/// <summary>
/// 将字符串转换成Int类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int ToInt(this object str)
{
int result = 0;
if (str != null)
{
int.TryParse(str.ToString(), out result);
}
return result;
}
/// <summary>
/// 将字符串转换成decimal类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static double ToDouble(this object str)
{
double result = 0.0;
if (str != null)
{
double.TryParse(str.ToString(), out result);
}
return result;
}
public static decimal ToDecimal(this object str)
{
decimal result = 0m;
if (str != null)
{
decimal.TryParse(str.ToString(), out result);
}
return result;
}
public static string ToNone(this object str, string extStr)
{
if (str != null && !string.IsNullOrEmpty(str.ToString()))
{
return str + " " + extStr;
}
return "";
}
/// <summary>
/// 将字符串转换成真假
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool ToBool(this object str)
{
return str != null && str.ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// 将字符串转换成GUID出错则为Guid.NewGuid()
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Guid ToGuid(this object str)
{
Guid result = Guid.NewGuid();
if (str != null)
{
Guid.TryParse(str.ToString(), out result);
}
return result;
}
public static DateTime ToDateTime(this object str)
{
DateTime now = DateTime.Now;
if (str != null)
{
DateTime.TryParse(str.ToString(), out now);
}
return now;
}
public static string ToDateTimeRandom()
{
return DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(9999).ToString();
}
public static string ToDateString()
{
return DateTime.Now.ToString("yyyyMMdd");
}
public static string ToBr(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return str.Replace("\r\n", "<br>");
}
return str;
}
}
}

View File

@@ -0,0 +1,402 @@
using Services.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing.Imaging;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 字符串扩展函数工具类
/// </summary>
public static class StringExtensions
{
/// <summary>
/// 将\r\n替换成BR
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToSafeBR(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return str.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
}
return str;
}
/// <summary>
/// 得到父部门的ID
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetDepartmentFatherID(this string str)
{
if (!string.IsNullOrEmpty(str) && str.Length > 2)
{
str = str.Substring(0, str.Length - 3);
}
return str;
}
/// <summary>
/// 截取字符串,超过部分用...代替
/// </summary>
/// <param name="source"></param>
/// <param name="len"></param>
/// <returns></returns>
public static string Substr(this string source, int len)
{
return source.Substr(len, "...");
}
/// <summary>
/// 截取字符串,超过部分用自定义代替
/// </summary>
/// <param name="source"></param>
/// <param name="len"></param>
/// <param name="att"></param>
/// <returns></returns>
public static string Substr(this string source, int len, string att)
{
if (string.IsNullOrEmpty(source))
{
return string.Empty;
}
att = (att ?? string.Empty);
Regex regex = new Regex("[\\u4e00-\\u9fa5]");
Regex regex2 = new Regex("^[A-Za-z0-9]+$");
if (regex.IsMatch(source))
{
if (source.Length <= len)
{
return source;
}
return source.Substring(0, len) + att;
}
else if (regex2.IsMatch(source))
{
if (source.Length <= len * 2)
{
return source;
}
return source.Substring(0, len * 2) + att;
}
else
{
if (source.Length <= len)
{
return source;
}
return source.Substring(0, len) + att;
}
}
public static string InputStr(this string source)
{
if (!string.IsNullOrEmpty(source))
{
Regex regex = new Regex("[\\u4e00-\\u9fa5]");
Regex regex2 = new Regex("^[A-Za-z0-9]+$");
if (regex.IsMatch(source))
{
if (source.Length < 3)
{
return string.Format("{0}**", source[0]);
}
if (source.Length == 3)
{
return string.Format("{0}*{1}", source[0], source[source.Length - 1]);
}
if (source.Length > 3)
{
return string.Format("{0}**{1}", source[0], source[source.Length - 1]);
}
}
else
{
if (!regex2.IsMatch(source))
{
return string.Format("{0}**", source.Substring(0, 2));
}
if (source.Length < 6)
{
return string.Format("{0}**", source.Substring(0, 2));
}
return string.Format("{0}****{1}", source.Substring(0, 2), source.Substring(source.Length - 3, 2));
}
}
return string.Empty;
}
/// <summary>
/// 移除掉所有的Html代码
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string RemoveHtml(this string strHtml)
{
Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
strHtml = regex.Replace(strHtml, "");
strHtml = strHtml.Replace("&nbsp;", "");
return strHtml;
}
/// <summary>
/// 生成0-9随机数
/// </summary>
/// <param name="VcodeNum">生成长度</param>
/// <returns></returns>
public static string RndNum(int VcodeNum)
{
StringBuilder stringBuilder = new StringBuilder(VcodeNum);
Random random = new Random();
for (int i = 1; i < VcodeNum + 1; i++)
{
int num = random.Next(9);
stringBuilder.AppendFormat("{0}", num);
}
return stringBuilder.ToString();
}
/// <summary>
/// 返回星号的加密
/// </summary>
/// <param name="items"></param>
/// <param name="mask"></param>
/// <returns></returns>
public static string MaskStar(Dictionary<string, string> items, bool mask)
{
StringBuilder stringBuilder = new StringBuilder();
if (mask)
{
foreach (KeyValuePair<string, string> keyValuePair in items)
{
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair.Key,
"').attr('name', '",
keyValuePair.Key,
"mask');"
}));
}
stringBuilder.Append("$('.maskstar').attr('disabled', true);");
stringBuilder.Append("$('.maskstar').val('***');");
}
else
{
foreach (KeyValuePair<string, string> keyValuePair2 in items)
{
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair2.Key,
"').attr('name', '",
keyValuePair2.Key,
"');"
}));
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair2.Key,
"').val('",
keyValuePair2.Value,
"');"
}));
}
stringBuilder.Append("$('.maskstar').attr('disabled', false);");
}
return stringBuilder.ToString();
}
/// <summary>
/// 给自动填充使用
/// </summary>
/// <param name="str1"></param>
/// <param name="str2"></param>
/// <returns></returns>
public static string ToAutoComplate(this string str1, string str2)
{
if (!string.IsNullOrEmpty(str1) && !string.IsNullOrEmpty(str2))
{
return str1 + "," + str2;
}
return "";
}
/// <summary>
/// 返回红色字体
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToRedColor(this int value)
{
if (value != 0)
{
return "<font color='red'>" + value.ToString() + "</font>";
}
return value.ToString();
}
/// <summary>
/// 返回安全的字符串类型如果为NULL则返回空
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToSafeString(this object value)
{
if (value == null)
{
return "";
}
return value.ToString();
}
/// <summary>
/// 将中文转换成Unicode编码主要用在URL传递中文
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GB2Unicode(this string str)
{
string text = "";
Encoding encoding = Encoding.GetEncoding("GB2312");
Encoding unicode = Encoding.Unicode;
byte[] bytes = encoding.GetBytes(str);
for (int i = 0; i < bytes.Length; i++)
{
string str2 = "%" + bytes[i].ToString("x");
text += str2;
}
return text;
}
/// <summary>
/// 将字符串转换成为大写的MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToMD5(this string str)
{
MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider();
byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
StringBuilder stringBuilder = new StringBuilder();
foreach (byte b in array)
{
stringBuilder.Append(b.ToString("x2"));
}
return stringBuilder.ToString().ToUpper();
}
/// <summary>
/// 字节码长度转可读字符串 00000000 bytes 0.0GB
/// </summary>
/// <param name="KSize"></param>
/// <returns></returns>
public static string ByteSizeToString(this long KSize)
{
if (KSize > 0L)
{
string[] array = new string[]
{
"B",
"KB",
"MB",
"GB",
"TB"
};
double num = 0.0;
int num2 = array.Length - 1;
while (num2 >= 0 && (num = Math.Round((double)KSize / Math.Pow(1024.0, (double)num2), 2)) < 1.0)
{
num2--;
}
return string.Format("{0}{1}", num, array[num2]);
}
return string.Empty;
}
/// <summary>
/// 将图片的字节码数组转成 base64 字符串
/// </summary>
/// <param name="img"></param>
/// <param name="format"></param>
/// <returns></returns>
public static string GetImgBase64String(this byte[] img, ImageFormat format)
{
return string.Format("data:image/{0};base64,{1}", format.ToString(), Convert.ToBase64String(img));
}
/// <summary>
/// 将字符串转换成为大写的MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string GetMD5Code(this string str)
{
StringBuilder stringBuilder = new StringBuilder();
using (MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider())
{
byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
foreach (byte b in array)
{
stringBuilder.Append(b.ToString("x2"));
}
}
return stringBuilder.ToString();
}
/// <summary>
/// 转码成短字符串
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="version">制码版本</param>
/// <returns>短码数组</returns>
public static string[] EncodeShortString(this string str, ShortStringVersion version)
{
string text = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int length = text.Length;
string md5Code = str.GetMD5Code();
string[] array = new string[4];
FieldInfo field = typeof(ShortStringVersion).GetField(version.ToString());
MaxLengthAttribute maxLengthAttribute = ((MaxLengthAttribute[])field.GetCustomAttributes(typeof(MaxLengthAttribute), false))[0];
int num = 0;
while (num < 4 && text.Length > 0)
{
int i = 1073741823 & Convert.ToInt32("0x" + md5Code.Substring(num * 8, 8), 16);
string text2 = string.Empty;
int index = 61 & i;
while (i > 0)
{
text2 += text[index];
i >>= (int)version;
index = (61 & i);
}
while (text2.Length < maxLengthAttribute.Length)
{
text2 += text[num];
}
array[num] = text2;
num++;
}
return array;
}
/// <summary>
/// 转码成短字符串
/// </summary>
/// <param name="str">源字符串</param>
/// <returns>短码数组</returns>
public static string[] EncodeShortString(this string str)
{
return str.EncodeShortString(ShortStringVersion.Version_1);
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System
{
public static class TimeExtensions
{
public static DateTime? ToDateTime(this string timeStamp)
{
long ticks = 0L;
if (long.TryParse(timeStamp, out ticks))
{
DateTime dateTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan value = new TimeSpan(ticks);
return new DateTime?(dateTime.Add(value));
}
DateTime now = DateTime.Now;
if (DateTime.TryParse(timeStamp, out now))
{
return new DateTime?(now);
}
return null;
}
}
}

View File

@@ -0,0 +1,252 @@
using Models;
using Models.ModelItems;
using Services.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Services.Manager
{
public class AppServer
{
/// <summary>
/// 查询 app 不查询禁用的权限
/// </summary>
/// <param name="id"></param>
/// <param name="IsValid"></param>
/// <returns></returns>
#region App权限信息
private static dynamic GetAppInfo(int id,int IsValid = 10,bool reauthorities = true)
{
ApplicationDomain app = Cache.CacheHelp.cacheSysApp.FirstOrDefault(x=>x.Id == id);
if(app == null)
return null;
List<AppAutho> autho = Cache.CacheHelp.cacheSysAppAutho.Where(x => x.AppId == id).ToList();
List<Authority> authorities = new List<Authority>();
if(reauthorities)
authorities = Cache.CacheHelp.cacheSysAutho.Where(x=> autho.FirstOrDefault(y=>y.AuthorityId == x.Id)!=null && x.IsValid != IsValid).ToList();
return new
{
data = authorities,
AppName = app.AppName,
AppId = app.Id,
Desc = app.Desc,
app.WebSite,
app.AppType,
app.Version,
app.ReleaseDate,
app.Icon,
app.DowSum
};
}
#endregion
#region App权限信息
/// <summary>
/// 所有正常App权限信息 查询所有就默认值即可 查询正常的权限 输入1 查询关闭的权限 输入 0
/// </summary>
/// <param name="IsValid"></param>
/// <param name="reauthorities">是否返回权限信息</param>
/// <returns></returns>
public static List<dynamic> GetAppInfo( int appid = 0, int appIsValid = 0 ,int IsValid = 0,bool reauthorities = true)
{
List<dynamic> res = new List<dynamic>();
foreach (var app in CacheHelp.cacheSysApp.Where(x =>( x.IsValid == appIsValid || appIsValid == -1) && (appid == x.Id || appid == 0)).ToList())
{
res.Add(GetAppInfo(app.Id, IsValid,reauthorities));
}
return res;
}
#endregion
#region App名是否存
public static bool CheckName(string name)
{
return Cache.CacheHelp.cacheSysApp.FirstOrDefault(x=>x.AppName == name && x.IsValid == 0) == null;
}
#endregion
#region App
public static int? AddApp(string name, string Desc = "", string uid = "", string Version = "1.0", string appicon = null, DateTime ReleaseDate = default, string WebSite = "",int AppType =0)
{
if (CacheHelp.cacheSysApp.FirstOrDefault(u => u.AppName == name && u.IsValid == 0) != null)
return null;
ApplicationDomain app = new ApplicationDomain {
AppName = name,
Desc = Desc,
CreatedBy = uid,
ReleaseDate = ReleaseDate,
WebSite = WebSite,
Version = Version,
AppType = AppType,
CreateTime = DateTime.Now,
Icon = appicon
};
int id= SqlSugarBase.Db.Insertable(app).ExecuteReturnIdentity();
DbLogServer.WriteDbLog($"添加了应用{app.AppName}{id})");
CacheHelp.Removesys(CacheHelp.syskey.sysAppsListKey);
return id;
}
#endregion
#region
public static bool DelApp(int appid,int IsValid, string uid = null)
{
try
{
ApplicationDomain app = SqlSugarBase.Db.Queryable<ApplicationDomain>().First(x => x.Id == appid);
if (app == null)
return false;
app.IsValid = IsValid;
app.CreatedBy = uid;
SqlSugarBase.Db.Updateable(app).ExecuteCommand();
if (IsValid!=0)
DbLogServer.WriteDbLog($"删除了应用{app.AppName}{app.Id})",2);
else
DbLogServer.WriteDbLog($"恢复了应用{app.AppName}{app.Id})", 1);
CacheHelp.Removesys(CacheHelp.syskey.sysAppsListKey);
return true;
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
return false;
}
finally
{
CacheHelp.Removesys(CacheHelp.syskey.Appversions);
}
}
#endregion
#region
public static bool Checkautho(int AppId, string AuthoNmae)
{
var au = CacheHelp.cacheView_AppAutho.FirstOrDefault(x => x.AppId == AppId && x.AuthorityName == AuthoNmae);
if (au == null)
return true;
else
return false;
}
#endregion
#region
public static int? Addautho(int AppId, string AuthoNmae, string Desc = "", string uid = null, string authoStatusTypeId = null)
{
try {
dynamic au = CacheHelp.cacheView_AppAutho.FirstOrDefault(x => x.AppId == AppId && x.AuthorityName == AuthoNmae);
if (au != null)
return null;
au = CacheHelp.cacheSysApp.FirstOrDefault(x => x.Id == AppId);
if (au == null)
return null;
Authority authority = new Authority { AuthorityName = AuthoNmae, Desc = Desc,CreatedBy = uid, AuthoStatusTypeId = authoStatusTypeId };
int id= SqlSugarBase.Db.Insertable(new Authority { AuthorityName = AuthoNmae, Desc = Desc, CreatedBy = uid, AuthoStatusTypeId = authoStatusTypeId }).ExecuteReturnIdentity();
SqlSugarBase.Db.Insertable(new AppAutho() { AppId = AppId, AuthorityId = id, CreatedBy = uid }).ExecuteCommand();
DbLogServer.WriteDbLog($"给应用{au.AppName}{au.Id})添加了权限'{AuthoNmae}({id})'",0);
CacheHelp.Removesys(CacheHelp.syskey.sysView_AppAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAuthorityListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAppAuthoListKey);
return id;
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
return null;
}
finally
{
CacheHelp.Removesys(CacheHelp.syskey.Appversions);
}
}
#endregion
#region
public static bool Delautho(int authoId, int status = 0, string uid = null)
{
var au = CacheHelp.cacheSysAutho.FirstOrDefault(x=>x.Id == authoId);
var app = CacheHelp.cacheView_AppAutho.FirstOrDefault(x=>x.AuthorityId == authoId);
if (au == null || app == null)
return false;
var autho = SqlSugarBase.Db.Queryable<Authority>().First(x => x.Id == authoId);
autho.IsValid = status;
SqlSugarBase.Db.Updateable(autho).ExecuteCommand();
if(status==1)
DbLogServer.WriteDbLog($"禁用了应用{app.AppName}({app.AppId})权限{au.AuthorityName}({au.Id}).",2);
else
DbLogServer.WriteDbLog( $"恢复了应用{app.AppName}({app.AppId})权限{au.AuthorityName}({au.Id}).", 2);
CacheHelp.Removesys(CacheHelp.syskey.sysView_AppAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAuthorityListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAppAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAppAuthoListKey);
return true;
}
#endregion
#region
public static bool Editautho(Authority authority, string uid)
{
try {
if (authority.Id <= 0)
return false;
var auc = CacheHelp.cacheSysAutho.FirstOrDefault(x => x.Id == authority.Id);
var app = CacheHelp.cacheView_AppAutho.FirstOrDefault(x => x.AuthorityId == authority.Id);
if (auc == null || app == null)
return false;
var au = SqlSugarBase.Db.Queryable<Authority>().First(x => x.Id == authority.Id);
au.Desc = authority.Desc ?? au.Desc;
au.AuthoStatusTypeId = authority.AuthoStatusTypeId ?? au.AuthoStatusTypeId;
au.AuthorityName = authority.AuthorityName ?? au.AuthorityName;
SqlSugarBase.Db.Updateable(au).ExecuteCommand();
DbLogServer.WriteDbLog( $"修改了{app.AuthorityName} ({app.AppId})权限{au.AuthorityName}({au.Id}).修改后为:" + JsonConvert.SerializeObject(au), 1);
CacheHelp.Removesys(CacheHelp.syskey.sysView_AppAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAuthorityListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAppAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysAppAuthoListKey);
return true;
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
return false;
}
finally
{
CacheHelp.Removesys(CacheHelp.syskey.Appversions);
}
}
#endregion
#region
public static bool AddDown( int AppId,int sum = 1)
{
try
{
var app = SqlSugarBase.Db.Queryable<ApplicationDomain>().First(x => x.Id == AppId);
app.DowSum+=sum;
return SqlSugarBase.Db.Updateable(app).ExecuteCommand()>0;
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
return false;
}finally
{
CacheHelp.Removesys( CacheHelp.syskey.Appversions);
CacheHelp.Removesys( CacheHelp.syskey.sysAppsListKey);
}
}
#endregion
}
}

View File

@@ -0,0 +1,25 @@
using Models;
using Models.ModelItems;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Manager
{
public class AuthoStatusServer
{
public static AuthoStatusType AddAuthoStatus(string Name,string desc)
{
AuthoStatusType authoStatus = Cache.CacheHelp.cacheSysAuthoStatusType.FirstOrDefault(x => x.Name == Name);
if (authoStatus != null)
return null;
authoStatus = new AuthoStatusType() {Name = Name ,Desc = desc };
SqlSugarBase.Db.Insertable(authoStatus).ExecuteCommand();
Cache.CacheHelp.Removesys(Cache.CacheHelp.syskey.sysAuthoStatusTypeListKey);
return authoStatus;
}
}
}

View File

@@ -0,0 +1,64 @@
using Models;
using Models.ModelItems;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace Services.Manager
{
public class DbLogServer
{
/// <summary>
/// 写日志
/// </summary>
/// <param name="uid">操作者</param>
/// <param name="content">内容</param>
/// <param name="type">0 新增 1 更新 2 删除</param>
public static void WriteDbLog(string content, int type = 0, DbLog logs = null)
{
try
{
//从Session拷贝一个模板过来
DbLog log = new DbLog();
log = logs != null ? logs : HttpContext.Current.Session["log"] as DbLog;
if(logs != null)
{
log = logs;
}
else
{
DbLog tmpSessionLog = HttpContext.Current.Session["log"] as DbLog;
if(tmpSessionLog != null)
{
log = tmpSessionLog;
}
else
{
log.location = "";
log.Ip = "";
log.Client = "";
log.Uid = "";
}
}
//除了content, type, 其他的全部用模板的值
DbLog dlog = new DbLog
{
location = log.location,
Ip = log.Ip,
Client = log.Client,
CreateTime = DateTime.Now,
Uid = log.Uid,
Type = type,
Content = content
};
SqlSugarBase.Db.Insertable(dlog).ExecuteCommand();
}
catch (Exception EX)
{
LogHelp.WriteExceptionLog(EX);
};
}
}
}

View File

@@ -0,0 +1,259 @@
using Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Models.ModelItems;
using Services.Tool;
using static Services.Tool.HttpRequestHelp;
using SqlSugar;
using UI.Lib;
namespace Services.Manager
{
public class FaceServer
{
public static List<Hosts> CheckfaceSNHosts(string faceSN)
{
var RES = CheckfaceSN(faceSN);
List<Hosts> RESDATA = new List<Hosts>();
List<Hosts> HOS = new List<Hosts>();
if (RES == null)
{
return null;
}
else
{
foreach (var item in RES)
{
int HOTELID = 0;
int RoomId = 0;
if (!int.TryParse(item.HotelCode, out HOTELID))
{
HOTELID = 0;
};
RoomId = int.Parse(item.RoomId == null ? 0.ToString() : item.RoomId.ToString());
// 已经分配酒店
if (HOTELID > 0 )
{
//未分配房间
if (RoomId == 0)
{
RESDATA.Add(new Hosts { Id = RoomId,HotelID = HOTELID,HotelName = Cache.CacheHelp.cacheHotels.Single(x=> x.Id == HOTELID ).Name,RoomNumber = "暂无绑定房间" });
}
else
{
var TEMP = HOS.FirstOrDefault(X => X.Id == RoomId);
if (TEMP == null)
{
HOS.AddRange(HttpRequestHelp.GetHosts(int.Parse(item.HotelCode)));
var str = JsonConvert.SerializeObject(HOS.Select(x=>x.Id));
TEMP = HOS.FirstOrDefault(X => X.Id == RoomId);
}
if (TEMP != null)
RESDATA.Add(TEMP);
else
{
RESDATA.Add(new Hosts { Id = RoomId, HotelID = HOTELID, HotelName = Cache.CacheHelp.cacheHotels.Single(x => x.Id == HOTELID).Name, RoomNumber = "绑定房间已经被删除" });
// 绑定的房间被删除了
//throw new Exception("人脸机绑定的房间ID没有在房间列表找到 ~");
}
//return null;
}
}
}
}
return RESDATA;
}
/// <summary>
/// 检查人脸机是否已经被绑定的
/// </summary>
/// <param name="faceSN"></param>
/// <returns></returns>
public static List<DeviceManage> CheckfaceSN(string faceSN)
{
return Test_Feac.Db.Queryable<DeviceManage>().Where(X=>X.SerialNo == faceSN).ToList();
//($"select * from DeviceManage WHERE SerialNo = '{faceSN}'").ToList();
}
public static DeviceManage SelfaceSN_RoomId(int RoomId)
{
return Test_Feac.Db.Queryable<DeviceManage>().Where(X => X.RoomId == RoomId).First();
}
public static List<DeviceManage> SelfaceSN_HotelID(int HotelID)
{
return Test_Feac.Db.Queryable<DeviceManage>().Where(X => X.HotelCode == HotelID+"").ToList();
//using (AuthorityDB DB = new AuthorityDB())
//{
// SqlSugarBase.Db.Queryable<DeviceManage>()
// return DB.Database.SqlQuery<DeviceManage>($"select * from Face.DBO.DeviceManage WHERE HotelCode = @HotelID", new SqlParameter("@HotelID", HotelID)).ToList();
//}
}
/// <summary>
/// 根据房间号绑定人脸机 往人脸机表添加字段
/// RETURN
/// 0 成功
/// 1 已经注册已经绑定酒店
/// 2 已经注册更新失败
/// 3 未注册为分配酒店 添加注册 添加酒店是啊比
/// 4 未能预计的结果--
/// 5 数据不符合
/// 6 解绑失败
/// </summary>
/// <param name="faceSN"></param>
/// <param name="roomNumber"></param>
/// <param name="hotelID"></param>
/// <returns></returns>
public static int GetfaceSN(UserInfo userinfo = null, string faceSN = "", string roomNumber = "", int hotelID = 0, string faceAddress = "",string roomID = "", bool isjb = false)
{
int RES = 5;
// 如果传入 酒店房间号 就是绑定 判断是否已经绑定
if (!isjb)
{
var olddata = CheckfaceSN(faceSN);
//已经注册已经绑定酒店
if (olddata != null && olddata.Count > 0 && olddata[0].HotelCode != "0" && olddata[0].RoomId > 0)
{
//已经绑定 房间
RES = 1;
}
else
{
Test_Feac.Db.Ado.ExecuteCommand($"UPDATE DeviceManage SET bindingStatus = 0, RoomId = '0',faceAddress = @faceAddress, HotelCode = 0 WHERE RoomId = @roomID and HotelCode = @hotelID; ", new SugarParameter("@SerialNo", faceSN), new SugarParameter("@roomID", roomID), new SugarParameter("@hotelID", hotelID), new SugarParameter("@faceAddress", faceAddress));
//AuthorityDB DB = new AuthorityDB();
////如果之前有 SN 绑定房间 直接解绑
//DB.Database.ExecuteSqlCommand($"UPDATE Face.DBO.DeviceManage SET bindingStatus = 'false', RoomId = '0',faceAddress = @faceAddress, HotelCode = 0 WHERE RoomId = @roomID and HotelCode = @hotelID; ", new SqlParameter("@SerialNo", faceSN), new SqlParameter("@roomID", roomID), new SqlParameter("@hotelID", hotelID), new SqlParameter("@faceAddress", faceAddress));
//已经注册
if (olddata != null && olddata.Count > 0)
{
if (Test_Feac.Db.Ado.ExecuteCommand($"UPDATE DeviceManage SET bindingStatus = 1,RoomId = @roomID ,faceAddress = @faceAddress, HotelCode = @hotelID WHERE SerialNo = @SerialNo", new SugarParameter("@SerialNo", faceSN), new SugarParameter("@roomID", roomID), new SugarParameter("@hotelID", hotelID), new SugarParameter("@faceAddress", faceAddress)) > 0)
{
RES = 0;
}
else
{
RES = 2;
}
}
else
{
//未注册为分配酒店 添加注册 添加酒店 [Status], faceAddress, bindingStatus) values('6926895501368', 2, '968', 'false',
if (olddata == null || olddata.Count <= 0)
{
if (Test_Feac.Db.Ado.ExecuteCommand($"insert DeviceManage(SerialNo, HotelCode, RoomId,`Status`, faceAddress, bindingStatus) values(@SerialNo, @hotelID, @roomID,0, @faceAddress, 1); ", new SugarParameter("@SerialNo", faceSN), new SugarParameter("@roomID", roomID), new SugarParameter("@hotelID", hotelID), new SugarParameter("@faceAddress", faceAddress)) > 0)
{
RES = 0;
}
else
{
RES = 3;
}
}
else
{
LogHelp.WriteExceptionLog(new Exception("未能预计的结果--" + JsonConvert.SerializeObject(olddata)));
RES = 4;
}
}
};
}
else
{
//执行解绑
if (!string.IsNullOrEmpty(faceSN) && roomID != "0" && hotelID != 0)
{
//using (AuthorityDB DB = new AuthorityDB())
//{
if (Test_Feac.Db.Ado.ExecuteCommand($"UPDATE DeviceManage SET RoomId = '0' ,faceAddress = @faceAddress, HotelCode ='0' WHERE SerialNo = @SerialNo and HotelCode = @hotelID and RoomId = @roomID", new SugarParameter("@SerialNo", faceSN), new SugarParameter("@roomID", roomID), new SugarParameter("@hotelID", hotelID), new SugarParameter("@faceAddress", faceAddress)) >= 0)
{
RES = 0;
}
else
{
RES = 6;
}
//}
}
}
if (RES == 0)
{
List<MACLogs> logs = new List<MACLogs>();
var Ip = IPHelper.GetIP();
logs.Add(new MACLogs()
{
HotelID = hotelID,
MAC = faceSN,
roomNumber = roomNumber,
userid = userinfo.Id,
roomID = roomID,
AppType = 1,
type = isjb? 1 : 0
});
Task.Run(() =>
{
try
{
if (faceAddress == null)
{
Data locs = HttpRequestHelp.GetIp($@"https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={Ip}&co=&resource_id=6006&oe=utf8");
if (locs != null && locs.status == 0)
{
if (locs.data.Count > 0)
{
faceAddress = locs.data[0].location;
}
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex, "日志错误");
}
finally
{
try
{
lock (HostsServer.LOCK)
{
var maclogs = SqlSugarBase.Db.Queryable<MACLogs>().Select(x => x.ActionId).ToList();
int ActionId = (maclogs.Count > 0 ? maclogs.Max() : 0) + 1;
foreach (var item in logs)
{
item.Ip = Ip;
item.location = faceAddress;
item.ActionId = ActionId;
item.createtime = DateTime.Now;
item.Status = 0;
SqlSugarBase.Db.Insertable(item).ExecuteCommand();
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
}
});
}
return RES;
}
}
}

View File

@@ -0,0 +1,166 @@
using Models;
using Models.ModelItems;
using Services.Tool;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Services.Tool.HttpRequestHelp;
namespace Services.Manager
{
public class HostsServer
{
public static object LOCK = new object();
static string macsql = "select TOP 1 MAC,Id,RoomStatusID,HotelID,[RoomNumber],[Status] = convert(int, convert(nvarchar(50),[Status])) ,[Desc] = [remark],[CreateTime] =[registerdate] from BLW.CRICS.[dbo].tb_Hosts where MAC = @MAC";
static string macup = @"
--参数 @MAC 新的MAC @ID 为需要更新mac的id
begin tran
DECLARE @HostsId int;
DECLARE @oldmac nvarchar(50);
DECLARE @HostsIdoldmac nvarchar(50);
SET @HostsId = -1;
SET @oldmac = '-1';
SET @HostsIdoldmac = '-1';
SELECT TOP 1 @HostsId = id, @oldmac= MAC FROM tb_Hosts where MAC = @MAC
SELECT TOP 1 @HostsIdoldmac = MAC FROM tb_Hosts where Id = @ID and mac is not null and mac!=''
PRINT convert(varchar,@HostsId) +'&'+ @oldmac+'&'+@HostsIdoldmac
update tb_Hosts set MAC='' where id = @HostsId
update tb_Hosts set MAC=@MAC where Id = @ID
if @@ERROR>0
begin
rollback tran
end
ELSE
BEGIN
COMMIT TRAN
END
";
static string sql = " select MAC,Id,RoomStatusID,HotelID,[RoomNumber],[Status] = convert(int, convert(nvarchar(50),[Status])) ,[Desc] = [remark],[CreateTime] =[registerdate] from BLW.CRICS.[dbo].tb_Hosts where HotelID = @HotelID";
/// <summary>
/// 获取房间信息
/// </summary>
/// <param name="HotelID">酒点id</param>
/// <returns></returns>
public static List<HostsAdd> GetHostsInfo(int HotelID)
{
return HttpRequestHelp.GetHosts(HotelID);
}
/// <summary>
/// 检查MAC是否已经绑定
/// </summary>
/// <param name="MAC">MAC</param>
/// <returns></returns>
public static List<Hosts> CheckMAC(string MAC = "")
{
string newmac = string.Empty;
for (int i = 0; i < MAC.Length; i += 2)
{
newmac += MAC.Substring(i, 2) + "-";
}
newmac = newmac.Substring(0, newmac.Length - 1);
var res = new List<Hosts>();
res = HttpRequestHelp.GetHostByMAC(newmac);
if (res.Count == 0)
return null;
else
return res;
}
public static bool GetMAC(string MAC = "", int HotelID = 0, string roomID = "", string roomNumber = "", UserInfo userinfo = null, string loc = null)
{
var Ip = IPHelper.GetIP();
string newmac = string.Empty;
if (!string.IsNullOrEmpty(MAC)) {
for (int i = 0; i < MAC.Length; i += 2)
{
newmac += MAC.Substring(i, 2) + "-";
}
newmac = newmac.Substring(0, newmac.Length - 1);
}
List<MACLogs> logs = new List<MACLogs>();
logs.Add(new MACLogs()
{
AppType = 1,
HotelID = HotelID,
MAC = newmac,
roomNumber = roomNumber,
roomID = roomID,
userid = userinfo.Id,
type = MAC==""?1:0
});
int Status = 0;
if (HttpRequestHelp.SetHostMAC(HotelID, newmac, roomNumber)) { Status = 1; };
Task.Run(() =>
{
try
{
if (loc == null)
{
Data locs = HttpRequestHelp.GetIp($@"https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={Ip}&co=&resource_id=6006&oe=utf8");
if (locs != null && locs.status == 0)
{
if (locs.data.Count > 0)
{
loc = locs.data[0].location;
}
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex, "日志错误");
}
finally
{
lock (LOCK)
{
try
{
var maclogs = SqlSugarBase.Db.Queryable<MACLogs>().Select(x => x.ActionId).ToList();
int ActionId = (maclogs.Count > 0 ? maclogs.Max():0) + 1;
foreach (var item in logs)
{
item.Ip = Ip;
item.location = loc;
item.ActionId = ActionId;
item.createtime = DateTime.Now;
item.Status = Status;
SqlSugarBase.Db.Insertable(item).ExecuteCommand();
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
}
}
});
return Status == 1;
}
/// <summary>
/// 写入用户反馈的错误
/// </summary>
public static bool AddErrorInfo(int userid, string MAC, int HotelID, int type,string roomNumber)
{
try
{
SqlSugarBase.Db.Insertable(new ErrorInfo() { createtime = DateTime.Now, type = type, status = 0, userid = userid, roomNumber = roomNumber, HotelID = HotelID, MAC = MAC }).ExecuteCommand();
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex, "反馈信息错误");
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,173 @@
using Models;
using Models.ModelItems;
using Models.View;
using Services.Cache;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using static Services.Cache.CacheHelp;
using SqlSugar;
namespace Services.Manager
{
public class HotelServer
{
//键值对存储酒店的最高就酒店组 如果存在就不需要查找
public static Dictionary<int, int> keyValues = new Dictionary<int, int>();
#region
public static bool CheckGroupName(string Name, int ParentId)
{
var au = CacheHelp.cacheHoteldGroups.FirstOrDefault(x => x.ParentId == ParentId && x.Name == Name);
if (au == null)
return true;
else
return false;
}
#endregion
#region
public static int? AddGroupName(string Name, int ParentId, string Desc)
{
var au = CacheHelp.cacheHoteldGroups.FirstOrDefault(x => x.ParentId == ParentId && x.Name == Name);
if (au != null)
return null;
HotelGroups groups = new HotelGroups() { Name = Name, ParentId = ParentId, Desc = Desc };
SqlSugarBase.Db.Insertable(groups).ExecuteCommand();
CacheHelp.Removesys(syskey.sysHoteldGroupsListKey);
return groups.Id;
}
#endregion
#region
public static bool CheckHotelName(string Name, int ParentId)
{
var au = CacheHelp.cacheHotels.FirstOrDefault(x => x.GroupId == ParentId && x.Name == Name);
if (au == null)
return true;
else
return false;
}
#endregion
#region
public static int? AddHotel(string Name, int ParentId, string Desc)
{
var au = CacheHelp.cacheHotels.FirstOrDefault(x => x.GroupId == ParentId && x.Name == Name);
if (au != null)
return null;
Hotels hotels = new Hotels() { Name = Name, GroupId = ParentId, Desc = Desc };
SqlSugarBase.Db.Insertable(hotels).ExecuteCommand();
CacheHelp.Removesys(syskey.sysHotelsListKey);
return hotels.Id;
}
#endregion
//返回酒店下面的人员信息 权限数量
#region
public static dynamic FindUserinfo()
{
dynamic resdata;
var res = new List<dynamic>();
var data = UserInfoServer.GetUserInfo(null);
foreach (var item in data)
{
foreach (var tump in item.HotelInfo)
{
res.Add(new
{
hotelId = tump.id,
Id = item.Id,
Uid = item.Uid,
sum = tump.sum
});
}
}
resdata = res.GroupBy(x => x.hotelId).ToList();
return resdata;
}
#endregion
#region
public static dynamic FindUserinfoGs(View_UserInfo u)
{
try
{
if (u.Company != null)
{
return new
{
//0 宝来威 1 住好 2 卓豪
Id = u.Company,
name = u.Company == 0?"宝来威":(u.Company == 1? "住好" : "卓豪")
};
}
//if(u.Company)
var S = 2;
if (u.IsImport > 0)
{
if (u.HotelGroupID > 0)
S = FindRoot(u.HotelGroupID);
else
{
if (u.HotelID > 1)
S = FindRoot_(u.HotelID);
}
}
S -= 2;
if (S < 0)
{
throw new Exception("用户没有找到对应的公司"+u.Id.ToString());
}
// S 2 "宝来威" 3 住好
UserInfo info = new UserInfo();
info.Id = u.Id;
info.Company = S;
var result = SqlSugarBase.Db.Updateable(info).UpdateColumns(it => new { it.Company }).ExecuteCommand();
Task.Run(() =>{
Cache.CacheHelp.Removesys(syskey.sysUserInfoListKey);
});
return new
{
Id = S,
name = S == 0 ? "宝来威" : (u.Company == 1 ? "住好" : "卓豪")
};
}
catch (Exception ex)
{
Logs.WriteTimingUDPLog("参入参数:"+JsonConvert.SerializeObject( u));
LogHelp.WriteExceptionLog(ex);
return new
{
Id = 0,
name = "宝来威"
};
}
}
#endregion
static dynamic FindRoot(int? group)
{
if (group == null)
return 0;
var groupinfo = cacheHoteldGroups.FirstOrDefault(x => x.Id == group);
if (groupinfo == null)
throw new Exception("group未找到");
if (groupinfo.ParentId <= 1)
return groupinfo.Id;
return FindRoot(groupinfo.ParentId);
}
static dynamic FindRoot_(int? id)
{
if (id == null)
return 0;
var groupinfo = cacheHotels.First(x => x.Id == id);
return FindRoot(groupinfo.GroupId);
}
}
}

360
Services/Manager/Logs.cs Normal file
View File

@@ -0,0 +1,360 @@
using LogServer;
using Newtonsoft.Json;
using Services.Tool;
using System;
using System.Data.Entity.Validation;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
namespace Services.Manager
{
/// <summary>
/// 日志类
/// </summary>
public partial class Logs
{
/// <summary>
/// 锁1 路径/App_Data/Log/
/// </summary>
private static readonly object _lock = new object();
/// <summary>
/// 锁2 路径/App_Data/TimingPlan/
/// </summary>
private static readonly object _lock1 = new object();
/// <summary>
/// 锁3 路径/App_Data/UDPlog/
/// </summary>
private static readonly object _lockUdp = new object();
public static void WriteErrorLog(Exception ex)
{
try
{
if (ex != null)
{
string content = "类型:错误代码\r\n";
content += "时间:" + DateTime.Now.ToString() + "\r\n";
content += "来源:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "内容:" + ex.Message + "\r\n";
Page page = new Page();
HttpServerUtility server = page.Server;
string dir = server.MapPath("/App_Data/Log/");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StreamWriter FileWriter = new StreamWriter(path, true, System.Text.Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
//}
}
}
catch (Exception)
{
throw;
}
}
public static void WriteLog(string msg)
{
try
{
if (!string.IsNullOrEmpty(msg))
{
string content = "类型:调试日志\r\n";
content += "时间:" + DateTime.Now.ToString() + "\r\n";
content += "内容:" + msg + "\r\n";
Page page = new Page();
HttpServerUtility server = page.Server;
string dir = server.MapPath("/App_Data/Log/");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StreamWriter FileWriter = new StreamWriter(path, true, System.Text.Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
//}
}
}
catch (Exception ex)
{
}
}
public static void WriteErrorLog(string errsrc, Exception ex)
{
try
{
string errtxt = "";
string exname = ex.GetType().ToString();
if (exname == "System.Data.Entity.Validation.DbEntityValidationException")
{
foreach (var item in ((DbEntityValidationException)ex).EntityValidationErrors)
{
foreach (var err in item.ValidationErrors)
{
errtxt += "EntityValidationErrors >>>>>> “" + err.PropertyName + "”字段" + err.ErrorMessage + "\r\n";
}
}
}
string content = (!string.IsNullOrEmpty(errsrc) ? "来自页面:" + errsrc : "") + "\r\n";
content += "发生时间:" + DateTime.Now.ToString() + "\r\n";
content += "异常对像:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "错误追踪:" + ex.StackTrace + "\r\n";
content += "错误提示:" + ex.Message + "\r\n" + errtxt;
if (ex.InnerException != null && ex.InnerException.InnerException != null)
content += ex.InnerException.InnerException.Message + "\r\n";
//if (BaseConfigs.GetLogInDB == 1)
//{
//TSysLog log = new TSysLog();
//log.Content = content;
//log.Type = "系统日志";
//log.CreateTime = DateTime.Now;
//DataAccess.CreateSysLog().Add(log);
//}
//if (BaseConfigs.GetLogInFile == 1)
//{
Page page = new Page();
HttpServerUtility server = page.Server;
string dir = server.MapPath("/App_Data/Log/");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StreamWriter FileWriter = new StreamWriter(path, true, System.Text.Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
//}
}
catch (Exception)
{
throw;
}
}
public static void WriteTimingPlanLog(string msg)
{
try
{
if (!string.IsNullOrEmpty(msg))
{
string content = "类型:调试日志 ";
content += "时间:" + DateTime.Now.ToString() + " ";
content += "内容:" + msg + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/TimingPlan/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lock1)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
//FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
}
public static void WriteUserinfo(dynamic msgs)
{
try
{
string msg = JsonConvert.SerializeObject(msgs);
if (!string.IsNullOrEmpty(msg))
{
string content = "类型:调试日志 ";
content += "时间:" + DateTime.Now.ToString() + " ";
content += "内容:" + msg + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Userinfo/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lock1)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
//FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
}
public static void WriteErrorTimingPlanLog(string errsrc, Exception ex)
{
try
{
if (ex != null)
{
string content = (!string.IsNullOrEmpty(errsrc) ? "来自作业线程:" + errsrc : "") + "\r\n";
content += "发生时间:" + DateTime.Now.ToString() + "\r\n";
content += "异常对像:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "错误追踪:" + ex.StackTrace + "\r\n";
content += "错误提示:" + ex.Message + "\r\n";
if (ex.InnerException != null && ex.InnerException.InnerException != null)
content += ex.InnerException.InnerException.Message + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/TimingPlan/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lock1)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception exl)
{
LogHelp.WriteExceptionLog(ex);
LogHelp.WriteExceptionLog(exl);
}
}
public static void WriteTimingUDPLog(string msg)
{
try
{
if (!string.IsNullOrEmpty(msg))
{
string content = "类型:调试日志 ";
content += "时间:" + DateTime.Now.ToString() + " ";
content += "内容:" + msg + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/UDPLog/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lockUdp)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
//FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
}
public static void WriteErrorTimingUDPLog(string errsrc, Exception ex)
{
try
{
if (ex != null)
{
string content = (!string.IsNullOrEmpty(errsrc) ? "来自作业线程:" + errsrc : "") + "\r\n";
content += "发生时间:" + DateTime.Now.ToString() + "\r\n";
content += "异常对像:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "错误追踪:" + ex.StackTrace + "\r\n";
content += "错误提示:" + ex.Message + "\r\n";
if (ex.InnerException != null && ex.InnerException.InnerException != null)
content += ex.InnerException.InnerException.Message + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/UDPLog/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lockUdp)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception exl)
{
LogHelp.WriteExceptionLog(exl);
}
}
}
public static class LogHelp
{
/// <summary>
/// 写入日志
/// </summary>
/// <param name="ex">异常对象</param>
/// <param name="operationer">操作人</param>
/// <param name="actionName">功能站点名称</param>
public static void WriteExceptionLog(Exception ex, string actionName = "", string operationer = "")
{
if (HttpContext.Current == null)
{
ExceptionLogHelper.Log(new ExceptionLogMessage() { ActionName = actionName, exception = ex, Header = "", Url = "线程", Operationer = "线程", IP = "" });
}
else
{
ExceptionLogHelper.Log(new ExceptionLogMessage() { ActionName = actionName, exception = ex, Header = HttpContext.Current.Request.Headers.ToString(), Url = HttpContext.Current.Request.Url.ToString(), Operationer = operationer, IP = IPHelper.GetIP() });
}
}
}
}

View File

@@ -0,0 +1,101 @@
using Models;
using Models.ModelItems;
using Services.Cache;
using Services.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Manager
{
public class OrgAuthoServer
{
#region
public static bool EditAuthoType(int OrgId, int type, int authorityid,int hotels,string CreatedBy)
{
try
{
Organization org = CacheHelp.cacheSysOrganization.FirstOrDefault(x => x.Id == OrgId && x.IsValid ==0);
//OrgAuthority autho = db.OrgAuthorities.FirstOrDefault(x => x.OrgId == OrgId && x.AuthorityId == authorityid && x.HotelId == hotels);
OrgAuthority autho= SqlSugarBase.Db.Queryable<OrgAuthority>().First(x => x.OrgId == OrgId && x.AuthorityId == authorityid && x.HotelId == hotels);
Hotels hotels1 = CacheHelp.cacheHotels.FirstOrDefault(x=>x.Id == hotels);
Authority authority = CacheHelp.cacheSysAutho.FirstOrDefault(x => x.Id == authorityid);
AuthoStatusType statusType = CacheHelp.cacheSysAuthoStatusType.FirstOrDefault(x=>x.Id == type);
if (autho == null)
{
OrgAuthority authos = new OrgAuthority() { AuthorityId = authorityid,OrgId = OrgId,AuthotypeId = type,HotelId = hotels};
DbLogServer.WriteDbLog($"新增了用户组{org.OrganizationName }对{hotels1.Name}({hotels})酒店的{authority.AuthorityName}({authority.Id})权限'{authority.AuthorityName }({authority.Id})':无 => {statusType.Name}");
SqlSugarBase.Db.Insertable(authos).ExecuteCommand();
}
else
{
AuthoStatusType statusTypeold = CacheHelp.cacheSysAuthoStatusType.FirstOrDefault(x => x.Id == autho.AuthotypeId);
DbLogServer.WriteDbLog($"更改了用户组{org.OrganizationName }({org.Id})对{hotels1.Name}({hotels})酒店的{authority.AuthorityName}({authority.Id})权限'{authority.AuthorityName }({authority.Id})':{statusTypeold} => {statusType.Name}", 1);
autho.AuthotypeId = type;
autho.CreatedBy = CreatedBy;
SqlSugarBase.Db.Updateable(autho).ExecuteCommand();
}
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CacheHelp.Removesys(CacheHelp.syskey.sysUserAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysView_UAListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysUserInfoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysOrgAuthorityListKey);
}
}
#endregion
#region
public static bool DelOrg(int OrgId,string CreatedBy = null)
{
Organization org = SqlSugarBase.Db.Queryable<Organization>().First(x => x.Id == OrgId);
//Organization org = db.Organizations.FirstOrDefault(x =>x.Id == OrgId);
//List<OrgUser> OrgUser = CacheHelp.cacheSysOrgUser.Where(x => ).ToList();
if (org == null)
return false;
org.IsValid = 1;
SqlSugarBase.Db.Deleteable<OrgUsers>().Where(x => x.OrgId == org.Id);
//db.OrgUsers.RemoveRange(db.OrgUsers.Where(x => x.OrgId == org.Id));
//将没有用户组的用户添加到默认用户组
//db.Database.ExecuteSqlCommand($"insert into OrgUsers select 1,Id,'{DateTime.Now.ToString("G")}','{CreatedBy}' from UserInfo where id not in (select UserId from OrgUsers)");
SqlSugarBase.Db.Ado.ExecuteCommand($"insert into OrgUsers select 1,Id,'{DateTime.Now.ToString("G")}','{CreatedBy}' from UserInfo where id not in (select UserId from OrgUsers)");
//db.SaveChanges();
DbLogServer.WriteDbLog( $"删除了用户组{org.OrganizationName }({org.Id})",2);
CacheHelp.Removesys(null);
return true;
}
#endregion
#region
public static bool CheckName(string name)
{
if (CacheHelp.cacheSysOrganization.FirstOrDefault(u => u.OrganizationName == name) == null)
return true;
else
return false;
}
#endregion
#region
public static int? AddOrg(string name,string Desc = "", string CreatedBy = null)
{
if (CacheHelp.cacheSysOrganization.FirstOrDefault(u => u.OrganizationName == name) != null)
return null;
//AuthorityDB db = new AuthorityDB();
Organization organization = new Organization() { OrganizationName = name , Desc = Desc,CreatedBy = CreatedBy };
int id= SqlSugarBase.Db.Insertable(organization).ExecuteReturnIdentity();
//db.Organizations.Add(organization);
//db.SaveChanges();
CacheHelp.Removesys(CacheHelp.syskey.sysOrganizationListKey);
DbLogServer.WriteDbLog($"添加了用户组{organization.OrganizationName }({id})");
return id;
}
#endregion
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Manager
{
//同步酒店信息
public class SyncData
{
public static bool UpDate()
{
return true;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,379 @@
// Services.Manager.UserInfoServer
using Models;
using Models.ModelItems;
using Models.View;
using Services.Cache;
using Services.Extensions;
using Services.Manager;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using System.Threading;
using UH_CENTER;
public class UserInfoServer
{
//普通用户信息
#region
public static dynamic GetUserInfo( Func<dynamic,bool> func = null)
{
//取得普通用户信息
var res = CacheHelp.cacheSysUserInfo.OrderByDescending(u => u.CreateTime).Select((View_UserInfo u) =>
{
var hoteles = SyncHotelServer.FindUHotelInfo(u);
return new
{
Id = u.Id,
IsValid = u.IsValid,
Age = u.Age,
Uid = u.Uid,
sex = ((u.Sex == 0) ? "男" : ((u.Sex == 1) ? "女" : "未知")),
Sex = u.Sex,
OrganizationName = u.OrganizationName,
Authoncount = u.Authoncount,
isValid = (u.IsValid == 1) ? "冻结" : (u.IsValid >= 2 ? "管理" : "正常"),
u.HeadImg,
u.EndTime,
u.Desc,
u.CreateTime,
u.IsImport,
Gs = HotelServer.FindUserinfoGs(u),
HotelInfo = hoteles,
Hoteles = hoteles.Select(x=>x.id).ToArray()
};
}).Where(X=> func == null || func(X)).ToList();
return res;
}
#endregion
#region
public static bool EditIsValid(string uid, int isvalid, string CreatedBy)
{
try
{
//UserInfo userInfo = authorityDB.UserInfos.FirstOrDefault((UserInfo x) => x.Uid == uid);
UserInfo userInfo =SqlSugarBase.Db.Queryable<UserInfo>().First((UserInfo x) => x.Uid == uid);
if (CacheHelp.cacheSysUserInfo.FirstOrDefault(X => X.Uid == CreatedBy).IsValid <= userInfo.IsValid && CreatedBy.ToLower() != "adminblv")
return false;
if (userInfo == null)
{
throw new CustomException("未查找到" + uid + "!");
}
userInfo.IsValid = isvalid;
SqlSugarBase.Db.Updateable(userInfo).ExecuteCommand();
//authorityDB.SaveChanges();
DbLogServer.WriteDbLog((isvalid == 0 ? $"激活了用户{userInfo.Uid}({userInfo.Id })" : $"冻结了用户{userInfo.Id }({userInfo.Uid})"), 1);
CacheHelp.Removesys(CacheHelp.syskey.sysUserInfoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysView_UAListKey);
return true;
}
catch (CustomException ex)
{
throw ex;
}
}
#endregion
#region
public static List<View_UOA> GetUOA(string uid)
{
// 目前这些功能并未使用 可以直接 返回 [];
return new List<View_UOA>();
return CacheHelp.cacheView_UOA.Where(X => X.Uid == uid).ToList();
}
#endregion
#region
public static dynamic GetUA(string uid)
{
var RES = SqlSugarBase.Db.Queryable<View_UA>().Where(X => X.Uid == uid && X.AuthotypeId != 1).Select(X=>new{HotelId=X.HotelId,AuthorityId = X.AuthorityId, AuthotypeId = X.AuthotypeId, AuthorityName = X.AuthorityName }).ToArray();
return RES;
}
#endregion
#region
public static bool EditAuthoType(string uid, int type, int authorityid, int hotels, string CreatedBy)
{
try
{
Hotels hotels1 = CacheHelp.cacheHotels.FirstOrDefault(x => x.Id == hotels);
Authority authority = CacheHelp.cacheSysAutho.FirstOrDefault(x => x.Id == authorityid);
AuthoStatusType statusType = CacheHelp.cacheSysAuthoStatusType.FirstOrDefault(x => x.Id == type);
var uinfo = CacheHelp.cacheSysUserInfo.FirstOrDefault(x => x.Uid.ToLower() == uid.ToLower());
if (uinfo == null)
{
Logs.WriteTimingUDPLog("模型验证失败~");
return false;
}
if (CreatedBy.ToLower() != uid.ToLower() && CacheHelp.cacheSysUserInfo.FirstOrDefault(X => X.Uid == CreatedBy).IsValid <= uinfo.IsValid && CreatedBy.ToLower() != "adminblv")
{
Logs.WriteTimingUDPLog("权限不足~");
return false;
}
//UserAutho autho = db.UserAuthos.FirstOrDefault(x => x.UserId == uinfo.Id && x.AuthorityId == authorityid && x.HotelId == hotels);
UserAuthoes autho = SqlSugarBase.Db.Queryable<UserAuthoes>().First(x => x.UserId == uinfo.Id && x.AuthorityId == authorityid && x.HotelId == hotels);
if (autho == null)
{
DbLogServer.WriteDbLog($"新增了用户{uinfo.Uid }({uinfo.Id})对{hotels1.Name}({hotels})酒店的{authority.AuthorityName}({authority.Id})权限:无 => {statusType.Name}");
//db.UserAuthos.Add(new UserAutho() { AuthotypeId = type, UserId = uinfo.Id, AuthorityId = authorityid, HotelId = hotels, CreatedBy = CreatedBy });
SqlSugarBase.Db.Insertable(new UserAuthoes() { AuthotypeId = type, UserId = uinfo.Id, AuthorityId = authorityid, HotelId = hotels, CreatedBy = CreatedBy }).ExecuteCommand();
}
else
{
AuthoStatusType statusTypeold = CacheHelp.cacheSysAuthoStatusType.FirstOrDefault(x => x.Id == autho.AuthotypeId);
DbLogServer.WriteDbLog($"更改了用户{uinfo.Uid }({uinfo.Id})对{hotels1.Name}({hotels})酒店的{authority.AuthorityName}({authority.Id})权限:{statusTypeold.Name} => {statusType.Name}", 1);
autho.AuthotypeId = type;
autho.CreatedBy = CreatedBy;
SqlSugarBase.Db.Updateable(autho).ExecuteCommand();
}
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CacheHelp.Removesys(CacheHelp.syskey.sysUserAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysView_UAListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysUserInfoListKey);
}
}
#endregion
#region uid是否可用
public static bool CheckUid(string uid)
{
if (CacheHelp.cacheSysUserInfo.FirstOrDefault(u => u.Uid.ToLower() == uid.ToLower()) == null)
return true;
else
return false;
}
#endregion
#region
public static bool AddUserinfo(View_UserInfo userInfo, string uid, int type = 0)
{
try
{
int ID=-1;
OrgUsers orgUser = new OrgUsers();
UserInfo user = new UserInfo();
if (type != 0)
{
user = SqlSugarBase.Db.Queryable<UserInfo>().First(x => x.Id == userInfo.Id) ?? null;
orgUser = SqlSugarBase.Db.Queryable<OrgUsers>().First(x => x.UserId == user.Id) ?? null;
if (user == null)
return false;
if (orgUser == null)
return false;
int? orgid = userInfo.OrgId;
orgUser.OrgId = int.Parse(orgid.ToString());
SqlSugarBase.Db.Updateable(orgUser).ExecuteCommand();
if (user.Uid.ToLower() != uid.ToLower() && CacheHelp.cacheSysUserInfo.FirstOrDefault(X => X.Uid == uid).IsValid <= user.IsValid && uid.ToLower() != "adminblv")
return false;
}
user.Age = userInfo.Age;
user.Uid = userInfo.Uid.ToLower();
user.HeadImg = userInfo.HeadImg;
user.Sex = userInfo.Sex;
user.Desc = userInfo.Desc;
user.IsValid = userInfo.IsValid;
user.CreatedBy = uid;
user.Company = userInfo.Company;
user.EndTime =DateTime.Now.AddYears(200);/* userInfo.EndTime*/
if (!string.IsNullOrEmpty(userInfo.Pwd))
{
user.Pwd = userInfo.Pwd;
Services.Tool.RSA rSA = HttpContext.Current.Session["ras"] as Services.Tool.RSA ?? throw new Exception();
string pwd = rSA.DecodeOrNull(user.Pwd) ?? throw new CustomException("出错!");
user.Pwd = user.PwdSee = pwd;
user = user.ComputePasswordHash();
}
if (user.Uid.ToLower() != uid.ToLower() && CacheHelp.cacheSysUserInfo.FirstOrDefault(X => X.Uid == uid).IsValid < user.IsValid && uid.ToLower() != "adminblv")
return false;
Logs.WriteUserinfo(user);
if (type == 0)
{
ID= SqlSugarBase.Db.Insertable(user).ExecuteReturnIdentity();
}
if (type == 0)
{
orgUser = new OrgUsers();
orgUser.OrgId = userInfo.OrgId ?? 1;
orgUser.UserId = ID;
SqlSugarBase.Db.Insertable(orgUser).ExecuteCommand();
DbLogServer.WriteDbLog($"添加了用户信息{user.Uid}({ID})");
}
else
{
SqlSugarBase.Db.Updateable(user).ExecuteCommand();
DbLogServer.WriteDbLog($"修改了用户信息{user.Uid}({ID})");
}
}
catch (Exception ex)
{
throw new CustomException(ex.ToString());
}
finally
{
CacheHelp.Removesys(CacheHelp.syskey.sysUserAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysView_UAListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysUserInfoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysView_UOAListKey);
}
return true;
}
#endregion
#region
public static bool DelUserinfo(int id, string uid)
{
UserInfo user = new UserInfo();
try
{
using (AuthorityDB db = new AuthorityDB())
{
user = db.UserInfos.FirstOrDefault(x => x.Id == id);
if (user.Uid.ToLower() != uid.ToLower() && CacheHelp.cacheSysUserInfo.FirstOrDefault(X => X.Uid == uid).IsValid <= user.IsValid && uid.ToLower() != "adminblv")
return false;
if (user == null)
{
DbLogServer.WriteDbLog($"删除用户{id}失败!");
return false;
}
db.OrgUsers.Remove(db.OrgUsers.FirstOrDefault(x => x.UserId == id));
db.UserAuthos.RemoveRange(db.UserAuthos.Where(x => x.UserId == id));
db.UserInfos.Remove(user);
db.SaveChanges();
}
}
catch (Exception ex)
{
DbLogServer.WriteDbLog($"删除用户{id}失败!");
throw new CustomException(ex.ToString());
}
finally
{
CacheHelp.Removesys(CacheHelp.syskey.sysUserAuthoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysView_UAListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysUserInfoListKey);
CacheHelp.Removesys(CacheHelp.syskey.sysView_UOAListKey);
}
DbLogServer.WriteDbLog($"删除用户{user.Uid}({user.Id})成功!");
return true;
}
#endregion
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="start"></param>
/// <param name="length"></param>
/// <param name="draw"></param>
/// <param name="gs"></param>
/// <param name="IsImport"></param>
/// <param name="search"></param>
/// <returns></returns>
public static dynamic GetUserinfoView(int start, int length, int draw, int gs = -1, int IsImport = -1, Dictionary<string, string> search = null)
{
var data = CacheHelp.cacheView_UserInfo.OrderByDescending(X=>X.CreateTime).ToList();
string searchstr = string.Empty;
if(search != null && search["value"].Length>0)
{
int s = search["value"].Length;
searchstr = $"uid like '%{search["value"].ToUpper()}%'";
data = data.Where(x=>x.Uid.Trim().ToUpper().Contains(search["value"].ToUpper())).ToList();
}
if (gs!=-1)
{
data= data.Where(x => x.Company == gs).ToList();
if (searchstr == string.Empty)
{
searchstr = $"Company = '{gs}'";
}
else
{
searchstr += $" and Company = '{gs}' ";
}
}
if (IsImport != -1)
{
data = data.Where(x => x.IsImport == IsImport).ToList();
if (searchstr == string.Empty)
{
searchstr = $"IsImport = '{IsImport}'";
}
else
{
searchstr += $" and IsImport = '{IsImport}' ";
}
}
if (searchstr == string.Empty)
{
searchstr = $" 1 = 1 ";
}
int recordsFiltered = 0;
string sqlsum = $"select count(*) from View_UserInfo where {searchstr}";
//recordsFiltered = db.Database.SqlQuery<int>(sqlsum).ToList()[0];
// recordsFiltered = SqlSugarBase.Db.Ado.SqlQuery<int>(sqlsum).ToList()[0]; 推荐使用
recordsFiltered = data.Count();
//if (start == -10)
//{
// searchstr += $@" and id not in (select
// id from View_UserInfo where { searchstr}
// order by CreateTime desc LIMIT 1,{ start}) ";
//}
List <dynamic> res = null;
bool SX = false;
res = new List<dynamic>();
string sql = $"select * from View_UserInfo where {searchstr} order by CreateTime desc LIMIT {start},{ length}";
res.AddRange(
data.Skip(start).Take(length).Select((View_UserInfo u) =>
{
var hoteles = UH_CENTER_Help.Sel_Hotel(u);
// 上面的操作会刷新数据 这里刷新缓存 架构 问题
if (string.IsNullOrEmpty(u.Hotel_Data))
SX = true;
return new
{
Id = u.Id,
IsValid = u.IsValid,
Age = u.Age,
Uid = u.Uid,
sex = ((u.Sex == 0) ? "男" : ((u.Sex == 1) ? "女" : "未知")),
Sex = u.Sex,
OrganizationName = u.OrganizationName,
Authoncount = u.Authoncount,
isValid = (u.IsValid == 1 ? "冻结" :
(u.IsValid == 0 ? "正常" :
(u.IsValid == 2 ? "管理" :
(u.IsValid == 3 ? "超管" : "其他")))),
u.HeadImg,
u.EndTime,
u.Desc,
u.CreateTime,
u.IsImport,
Gs = HotelServer.FindUserinfoGs(u),
Hoteles = hoteles.Select(X=>X.id).ToArray(),
HotelInfo = hoteles
};
}
));
if(SX)
CacheHelp.Removesys(CacheHelp.syskey.sysUserInfoListKey);
return new
{
draw,
recordsTotal = CacheHelp.cacheSysUserInfo.Count(),
recordsFiltered = recordsFiltered,
data = res
};
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Services")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("56438f1c-ba3a-4272-964e-c6739ae0b4ec")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

378
Services/Services.csproj Normal file
View File

@@ -0,0 +1,378 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{56438F1C-BA3A-4272-964E-C6739AE0B4EC}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Services</RootNamespace>
<AssemblyName>Services</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Crypto, Version=1.8.5.0, Culture=neutral, PublicKeyToken=0e99375e54769942">
<HintPath>..\packages\BouncyCastle.1.8.5\lib\BouncyCastle.Crypto.dll</HintPath>
</Reference>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
</Reference>
<Reference Include="Google.Protobuf, Version=3.19.4.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
<HintPath>..\packages\Google.Protobuf.3.19.4\lib\net45\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="JWT, Version=8.0.0.0, Culture=neutral, PublicKeyToken=6f98bca0f40f2ecf, processorArchitecture=MSIL">
<HintPath>..\packages\JWT.8.6.0\lib\net46\JWT.dll</HintPath>
</Reference>
<Reference Include="K4os.Compression.LZ4, Version=1.2.6.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Compression.LZ4.1.2.6\lib\net46\K4os.Compression.LZ4.dll</HintPath>
</Reference>
<Reference Include="K4os.Compression.LZ4.Streams, Version=1.2.6.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Compression.LZ4.Streams.1.2.6\lib\net46\K4os.Compression.LZ4.Streams.dll</HintPath>
</Reference>
<Reference Include="K4os.Hash.xxHash, Version=1.0.6.0, Culture=neutral, PublicKeyToken=32cd54395057cec3, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Hash.xxHash.1.0.6\lib\net46\K4os.Hash.xxHash.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authentication.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication.Core, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authentication.Core.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authorization, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authorization.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authorization.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authorization.Policy, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Authorization.Policy.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Authorization.Policy.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Hosting.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Hosting.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Hosting.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Hosting.Server.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Hosting.Server.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Http.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Http.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Extensions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Http.Extensions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Features, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Http.Features.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Features.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Mvc.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Mvc.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Mvc.Core, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Mvc.Core.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Mvc.DataAnnotations, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Mvc.DataAnnotations.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.DataAnnotations.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.ResponseCaching.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.ResponseCaching.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.ResponseCaching.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Routing, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Routing.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Routing.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Routing.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.Routing.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Routing.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.WebUtilities, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNetCore.WebUtilities.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.WebUtilities.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.1.1.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.DotNet.PlatformAbstractions, Version=2.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.DotNet.PlatformAbstractions.2.1.0\lib\net45\Microsoft.DotNet.PlatformAbstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Caching.Abstractions, Version=3.1.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Caching.Abstractions.3.1.4\lib\netstandard2.0\Microsoft.Extensions.Caching.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Caching.Memory, Version=3.1.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Caching.Memory.3.1.4\lib\netstandard2.0\Microsoft.Extensions.Caching.Memory.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Binder, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Binder.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.EnvironmentVariables, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.EnvironmentVariables.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Configuration.EnvironmentVariables.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.FileExtensions, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.FileExtensions.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Configuration.FileExtensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Json, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Json.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Configuration.Json.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.2.2.0\lib\net461\Microsoft.Extensions.DependencyInjection.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.3.1.23\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyModel, Version=2.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.DependencyModel.2.1.0\lib\net451\Microsoft.Extensions.DependencyModel.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Abstractions, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.FileProviders.Abstractions.3.1.23\lib\netstandard2.0\Microsoft.Extensions.FileProviders.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Physical, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.FileProviders.Physical.3.1.23\lib\netstandard2.0\Microsoft.Extensions.FileProviders.Physical.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileSystemGlobbing, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.FileSystemGlobbing.3.1.23\lib\netstandard2.0\Microsoft.Extensions.FileSystemGlobbing.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Hosting.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Hosting.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Hosting.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Localization, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Localization.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Localization.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Localization.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Localization.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Localization.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=3.1.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Logging.Abstractions.3.1.4\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.ObjectPool, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.ObjectPool.2.2.0\lib\netstandard2.0\Microsoft.Extensions.ObjectPool.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Options.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Options.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options.ConfigurationExtensions, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Options.ConfigurationExtensions.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Options.ConfigurationExtensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=3.1.23.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Primitives.3.1.23\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Net.Http.Headers, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Net.Http.Headers.2.2.0\lib\netstandard2.0\Microsoft.Net.Http.Headers.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="MySql.Data, Version=8.0.29.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.8.0.29\lib\net452\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="MySqlConnector, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d33d3e53aa5f8c92, processorArchitecture=MSIL">
<HintPath>..\packages\MySqlConnector.2.1.10\lib\net461\MySqlConnector.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="SqlSugar, Version=5.0.9.0, Culture=neutral, PublicKeyToken=null" />
<Reference Include="StackExchange.Redis, Version=1.2.6.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\StackExchange.Redis.1.2.6\lib\net46\StackExchange.Redis.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel" />
<Reference Include="System.ComponentModel.Annotations, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.ComponentModel.Annotations.4.7.0\lib\net461\System.ComponentModel.Annotations.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Configuration.ConfigurationManager.4.7.0\lib\net461\System.Configuration.ConfigurationManager.dll</HintPath>
</Reference>
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Data.OracleClient" />
<Reference Include="System.Diagnostics.DiagnosticSource, Version=5.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.DiagnosticSource.5.0.1\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Drawing.Common, Version=4.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Drawing.Common.4.7.0\lib\net461\System.Drawing.Common.dll</HintPath>
</Reference>
<Reference Include="System.IO.Compression" />
<Reference Include="System.Management" />
<Reference Include="System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Net" />
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.0.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
<Private>True</Private>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Security.AccessControl, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.AccessControl.4.7.0\lib\net461\System.Security.AccessControl.dll</HintPath>
</Reference>
<Reference Include="System.Security.Permissions, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Permissions.4.7.0\lib\net461\System.Security.Permissions.dll</HintPath>
</Reference>
<Reference Include="System.Security.Principal.Windows, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Principal.Windows.4.7.0\lib\net461\System.Security.Principal.Windows.dll</HintPath>
</Reference>
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Text.Encoding.CodePages, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encoding.CodePages.5.0.0\lib\net461\System.Text.Encoding.CodePages.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encodings.Web.4.7.1\lib\net461\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Text.Json, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Json.4.7.2\lib\net461\System.Text.Json.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Transactions" />
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.4\lib\net45\System.Web.Helpers.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.4\lib\net45\System.Web.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Razor.3.2.4\lib\net45\System.Web.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.4\lib\net45\System.Web.WebPages.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Deployment, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.4\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.4\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="Ubiety.Dns.Core, Version=2.2.1.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.8.0.29\lib\net452\Ubiety.Dns.Core.dll</HintPath>
</Reference>
<Reference Include="UtilsSharp, Version=2.5.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\UtilsSharp.2.5.0\lib\netstandard2.0\UtilsSharp.dll</HintPath>
</Reference>
<Reference Include="UtilsSharp.Shared, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\UtilsSharp.Shared.1.0.0\lib\netstandard2.0\UtilsSharp.Shared.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="ZstdNet, Version=1.4.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.8.0.29\lib\net452\ZstdNet.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Api\Help.cs" />
<Compile Include="Cache\BaseCacheHelpRedis.cs" />
<Compile Include="Cache\CacheHelp.cs" />
<Compile Include="Enums\CacheTimeType.cs" />
<Compile Include="Enums\LoginInfoType.cs" />
<Compile Include="Enums\OperationLevel.cs" />
<Compile Include="Enums\OrderStatus.cs" />
<Compile Include="Enums\ShortStringVersion.cs" />
<Compile Include="Enums\StationType.cs" />
<Compile Include="Extensions\CacheExtensions.cs" />
<Compile Include="Extensions\CookieExtensions.cs" />
<Compile Include="Extensions\CustomException.cs" />
<Compile Include="Extensions\EnumerableExtensions.cs" />
<Compile Include="Extensions\LinqExtensions.cs" />
<Compile Include="Extensions\ModelExtensions.cs" />
<Compile Include="Extensions\SafeInputExtensions.cs" />
<Compile Include="Extensions\StringExtensions.cs" />
<Compile Include="Extensions\TimeExtensions.cs" />
<Compile Include="Manager\AppServer.cs" />
<Compile Include="Manager\AuthoStatusServer.cs" />
<Compile Include="Manager\DbLogServer.cs" />
<Compile Include="Manager\FaceServer.cs" />
<Compile Include="Manager\HostsServer.cs" />
<Compile Include="Manager\HotelServer.cs" />
<Compile Include="Manager\Logs.cs" />
<Compile Include="Manager\OrgAuthoServer.cs" />
<Compile Include="Api\OTApi.cs" />
<Compile Include="Manager\SyncHotelServer.cs" />
<Compile Include="Manager\UserInfoServer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Tool\DateTimeDiff.cs" />
<Compile Include="Tool\HttpRequestHelp.cs" />
<Compile Include="Tool\ModelHelper.cs" />
<Compile Include="Tool\RSAPwd.cs" />
<Compile Include="Tool\System\ComputerHelp.cs" />
<Compile Include="Tool\System\ConfigHelper.cs" />
<Compile Include="Tool\System\EnumHelper.cs" />
<Compile Include="Tool\System\IPHelper.cs" />
<Compile Include="Tool\RedisHelper.cs" />
<Compile Include="Tool\System\StringHelp.cs" />
<Compile Include="Tool\TokenHelper.cs" />
<Compile Include="UserLoginHelper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LogServer\LogServer.csproj">
<Project>{B2171304-2FB0-4043-9C92-619E91462146}</Project>
<Name>LogServer</Name>
</ProjectReference>
<ProjectReference Include="..\Models\Models.csproj">
<Project>{8C60AE21-34FD-4C98-BC52-68CEEF63B5E1}</Project>
<Name>Models</Name>
</ProjectReference>
<ProjectReference Include="..\UH_CENTER\UH_CENTER.csproj">
<Project>{d0f758e7-f93d-4ac6-950f-7a34522116f7}</Project>
<Name>UH_CENTER</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -0,0 +1,306 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Tool
{
public class DateTimeDiff
{
public DateTimeDiff()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 把秒转换成分钟
/// </summary>
/// <returns></returns>
public static int SecondToMinute(int Second)
{
decimal mm = (decimal)((decimal)Second / (decimal)60);
return Convert.ToInt32(Math.Ceiling(mm));
}
/// <summary>
/// 计算两个时间的时间间隔
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <param name="DateTimeNew">较后的日期和时间</param>
/// <returns></returns>
public static string DateDiff(DateTime DateTimeOld, DateTime DateTimeNew)
{
string dateDiff = "";
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTimeNew.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int day = ts.Days;
int hou = ts.Hours;
int minu = ts.Minutes;
int sec = ts.Seconds;
if (day > 0)
{
if (day > 30)
{
if (day > 364)
{
dateDiff += day / 365 + "年";
}
else
{
dateDiff += day / 30 + "个月";
}
}
else
{
dateDiff += day.ToString() + "天";
}
}
else
{
if (hou > 0)
{
dateDiff += hou.ToString() + "小时";
}
else
{
if (minu > 0)
{
dateDiff += minu.ToString() + "分钟";
}
else
{
if (sec > 0)
{
dateDiff += sec.ToString() + "秒";
}
else
{
dateDiff += "0秒";
}
}
}
}
if (DateTimeNew.CompareTo(DateTimeOld) > 0)
{
dateDiff += "前";
}
else
{
dateDiff += "后";
}
return dateDiff;
}
/// <summary>
/// 返回两个日期之间的时间间隔y年份间隔、M月份间隔、d天数间隔、h小时间隔、m分钟间隔、s秒钟间隔、ms微秒间隔
/// </summary>
/// <param name="Date1">开始日期</param>
/// <param name="Date2">结束日期</param>
/// <param name="Interval">间隔标志</param>
/// <returns>返回间隔标志指定的时间间隔</returns>
public static int DateDiff(System.DateTime Date1, System.DateTime Date2, string Interval)
{
double dblYearLen = 365;//年的长度365天
double dblMonthLen = (365 / 12);//每个月平均的天数
System.TimeSpan objT;
objT = Date2.Subtract(Date1);
switch (Interval)
{
case "y"://返回日期的年份间隔
return System.Convert.ToInt32(objT.Days / dblYearLen);
case "M"://返回日期的月份间隔
return System.Convert.ToInt32(objT.Days / dblMonthLen);
case "d"://返回日期的天数间隔
return objT.Days;
case "h"://返回日期的小时间隔
return objT.Hours;
case "m"://返回日期的分钟间隔
return objT.Minutes;
case "s"://返回日期的秒钟间隔
return objT.Seconds;
case "ms"://返回时间的微秒间隔
return objT.Milliseconds;
default:
break;
}
return 0;
}
/// <summary>
///判断是否于1分钟之前
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static bool DateDiff_minu(DateTime DateTimeOld)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Minutes;
if (minu > 1)
{
return true;
}
else
{
return false;
}
}
/// <summary>
///判断是否于m分钟之前
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static bool DateDiff_minu(DateTime DateTimeOld, int m)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Minutes;
if (minu > m)
{
return true;
}
else
{
return false;
}
}
public static bool DateDiff_1minu(DateTime DateTimeOld)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Seconds;
if (minu > 10)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 与当前时间比较,重载时间比较函数,只有一个参数
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static string DateDiff(DateTime DateTimeOld)
{
return DateDiff(DateTimeOld, DateTime.Now);
}
/// <summary>
/// 日期比较,返回精确的几分几秒
/// </summary>
/// <param name="DateTime1">较早的日期和时间</param>
/// <param name="DateTime2">较迟的日期和时间</param>
/// <returns></returns>
public static string DateDiff_full(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "时" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒";
return dateDiff;
}
/// <summary>
/// 时间比较,返回精确的几秒
/// </summary>
/// <param name="DateTime1">较早的日期和时间</param>
/// <param name="DateTime2">较迟的日期和时间</param>
/// <returns></returns>
public static int DateDiff_Sec(DateTime DateTime1, DateTime DateTime2)
{
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int dateDiff = ts.Days * 86400 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
return dateDiff;
}
/// <summary>
/// 日期比较
/// </summary>
/// <param name="today">当前日期</param>
/// <param name="writeDate">输入日期</param>
/// <param name="n">比较天数</param>
/// <returns>大于天数返回true小于返回false</returns>
public static bool CompareDate(string today, string writeDate, int n)
{
DateTime Today = Convert.ToDateTime(today);
DateTime WriteDate = Convert.ToDateTime(writeDate);
WriteDate = WriteDate.AddDays(n);
if (Today >= WriteDate)
return false;
else
return true;
}
public static string FormatProgress(DateTime StartTime, DateTime EndTime)
{
if (DateTime.Now > DateTime.Parse(EndTime.ToShortDateString() + " 23:59:59"))
return "活动结束";
else if (DateTime.Now < DateTime.Parse(StartTime.ToShortDateString() + " 0:0:0"))
return "即将开始";
else
{
int totalDay = DateTimeDiff.DateDiff(StartTime, EndTime, "d");
int inDay = DateTimeDiff.DateDiff(StartTime, DateTime.Now, "d");
if ((float)inDay / (float)totalDay < 0.2f)
return "刚刚开始";
else if ((float)inDay / (float)totalDay >= 0.2f && (float)inDay / (float)totalDay < 0.4)
return "正在进行";
else if ((float)inDay / (float)totalDay >= 0.4 && (float)inDay / (float)totalDay < 0.6)
return "活动过半";
else if ((float)inDay / (float)totalDay > 0.6 && (float)inDay / (float)totalDay <= 0.8)
return "进入尾声";
else
return "即将结束";
}
}
// 时间戳转为C#格式时间
public static DateTime StampToDateTime(string timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
// DateTime时间格式转换为Unix时间戳格式
public static double DateTimeToStamp(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (time - startTime).TotalMilliseconds;
}
/// <summary>
///判断是否于多少分钟之前
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static bool allDateDiff_minu(DateTime DateTimeOld, int m)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Minutes;
if (minu > m)
{
return true;
}
else
{
return false;
}
}
}
}

View File

@@ -0,0 +1,336 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Models;
using Models.ApiModei;
using Models.ModelItems;
using Newtonsoft.Json;
using Services.Manager;
namespace Services.Tool
{
public class HttpRequestHelp
{
//巫工Api
static string Url = "https://www.boonlive-rcu.com/api/"; // 注释掉巫工API 改为宝来威 "https://pms.boonlive-rcu.com/api/";
static string Key = "blw_ws@2015";
/// <summary>
/// 根据MAC获取主机
/// </summary>
/// <param name="Mac"></param>
/// <returns></returns>
public static List<Hosts> GetHostByMAC(string Mac)
{
if (string.IsNullOrEmpty(Mac))
return null;
var res = new Dictionary<string, dynamic>();
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key, mac = Mac }));
var resdata = Post<ReturnData<List<HostsAsync>>>(Url + "GetHostByMAC", res);
if (resdata != null && resdata.IsSuccess)
{
List<Hosts> newdata = new List<Hosts>();
foreach (var item in resdata.Result)
{
newdata.Add(new Hosts()
{
Id = item.ID,
HotelID = item.HotelID,
Status = item.Status?1:0,
HotelName = item.HotelName,
Desc = item.Remark,
RoomNumber = item.RoomNumber,
RoomStatusID = item.RoomStatusID,
MAC = item.MAC,
});
}
return newdata;
}
else
{
Logs.WriteTimingUDPLog(JsonConvert.SerializeObject(resdata));
return null;
}
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <returns></returns>
public static List<UserInfo> GetUserList()
{
var res = new Dictionary<string, dynamic>();
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key}));
var resdata = Post<ReturnData<List<UserInfoAsync>>>(Url + "GetUserList", res);
if (resdata != null && resdata.IsSuccess)
{
List<UserInfo> newdata = new List<UserInfo>();
foreach (var item in resdata.Result)
{
var s = 2;
if(!int.TryParse(item.Sex,out s))
{
if(item.Sex == "男")
{
s = 0;
}
else
{
if (item.Sex == "女")
s = 1;
else
s = 2;
}
}
if (newdata.FirstOrDefault(x => x.Uid.ToLower() == item.Account.ToLower())!= null) {
continue;
}
newdata.Add(new UserInfo()
{
OldId = item.ID,
IsImport = 1,
IsValid = item.ActiveIndicator?0:1,
HotelGroupID = item.SysHotelGroupID,
HotelID = item.HotelID,
CreateTime = item.CreatedDate,
Desc = item.Remark,
Sex = s,
Uid = item.Account,
Pwd = item.Password,
EndTime = item.CreatedDate.AddMonths(2)
});
}
return newdata;
}else
{
return null;
}
}
/// <summary>
/// 写入mac地址
/// </summary>
/// <param name="hotels"></param>
/// <param name="Mac"></param>
/// <param name="roomNumber"></param>
/// <returns></returns>
public static bool SetHostMAC(int hotelsid, string Mac,string roomNumber)
{
// code”“酒店编码我司提供例如1001”, “creatDate”“日期我司提供例如2016 - 09 - 05”, “roomNumber”“房号8888”
//深圳市宝来威智能科技有限公司 第 20页 共 22页 “mac”“mac 地址34 - D0 - B8 - 1F - 02 - 15”
var hotels = new Hotels();
hotels = SqlSugarBase.Db.Queryable<Hotels>().First(x => x.Id == hotelsid);
if (hotels == null)
return false;
var res = new Dictionary<string, dynamic>();
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key, roomNumber= roomNumber, mac = Mac, code = hotels.Code, creatDate = hotels.CreateTime.ToString("yyyy-MM-dd") }));
var resdata = Post<ReturnData<string>>(Url + "SetHostMAC", res);
if (resdata == null)
return false;
return resdata.IsSuccess && resdata.Result.Contains("成功");
}
/// <summary>
/// 房间表主机表信息
/// </summary>
/// <returns></returns>
public static List<HostsAdd> GetHosts(int hotelsid)
{
var hotels = new Hotels();
hotels = SqlSugarBase.Db.Queryable<Hotels>().First(x=>x.Id == hotelsid);
if (hotels == null || hotels == default(Hotels))
return null;
var res = new Dictionary<string, dynamic>();
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key, code = hotels.Code, creatDate = hotels.CreateTime.ToString("yyyy-MM-dd")}));
try
{
var resdata = Post<ReturnData<List<HostsAsync>>>(Url + "GetHostList", res);
if (resdata != null && resdata.IsSuccess)
{
List<HostsAdd> newdata = new List<HostsAdd>();
var FaceList = FaceServer.SelfaceSN_HotelID(hotels.Id);
foreach (var item in resdata.Result)
{
var temp = FaceList.FirstOrDefault(x => x.RoomId == item.ID);
if (temp == null)
temp = new DeviceManage();
newdata.Add(new HostsAdd()
{
Id = item.ID,
HotelID = item.HotelID,
HotelName = item.HotelName,
Status = item.Status ? 1 : 0,
Desc = item.Remark,
RoomNumber = item.RoomNumber,
RoomStatusID = item.RoomStatusID,
MAC = item.MAC,
FaceSN = temp.SerialNo,
FaceStatus = temp.Status,
maintainStatus = temp.maintainStatus,
RoomTypeID = item.RoomTypeID
});
}
return newdata;
}
else
return null;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
/// <summary>
/// 获取酒店列表 全部酒店信息
/// </summary>
public static List<Hotels> GetHotelList() {
var res = new Dictionary<string, dynamic>();
res.Add("jsonData",JsonConvert.SerializeObject( new{ key= Key }));
var resdata = Post<ReturnData<List<HotelsAsync>>>(Url+ "GetHotelList", res);
if (resdata!=null && resdata.IsSuccess)
{
List<Hotels> newdata = new List<Hotels>();
foreach (var item in resdata.Result)
{
newdata.Add(new Hotels() {
Id = item.ID,
Name = item.Name,
Status = item.Status,
Desc = item.Remark,
CreateTime = item.CreatDate,
GroupId = item.SysHotelGroupID,
IsApprove = item.IsApprove?1:0,
Code = item.Code.ToString()
});
}
return newdata;
}
//return resdata.Result;
else
return null;
}
/// <summary>
/// 获取酒店组 全部酒店组信息
/// </summary>
/// <returns></returns>
public static List<HotelGroups> GetHotelGroups()
{
var res = new Dictionary<string, dynamic>();
res.Add("jsonData", JsonConvert.SerializeObject(new { key = Key }));
var resdata = Post<ReturnData<List<HotelGroups>>>(Url + "GetHotelGroupList", res);
if (resdata != null && resdata.IsSuccess)
return resdata.Result;
else
return null;
}
/// <summary>
/// 获取IP
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static dynamic GetIp(string url)
{
return Get<Data>(url);
}
/// <summary>
/// 获取ip的帮助类
/// </summary>
public class Data
{
public int status { get; set; }
public string t { get; set; }
public string set_cache_time { get; set; }
public List<dynamic> data { get; set; }
}
public class ReturnData<T>
{
public bool IsSuccess { get; set; }
public T Result{ get; set; }
}
private static T Get<T>(string url, int Timeout = 10000)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.UserAgent = null;
request.Timeout = Timeout;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
if (!string.IsNullOrEmpty(retString))
return JsonConvert.DeserializeObject<T>(retString);
else
return default(T);
}
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
private static T Post<T>(string url, Dictionary<string, dynamic> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region Post
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
try
{
if (!string.IsNullOrEmpty(result))
return JsonConvert.DeserializeObject<T>(result);
else
{
Logs.WriteTimingUDPLog(result);
return default(T);
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
return default(T);
}
}
}
}

View File

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Services.Tool
{
/// <summary>
/// 实体帮助
/// </summary>
public static class ModelHelper
{
/// <summary>
/// 获取实体属性名
/// </summary>
/// <returns></returns>
public static string GetModelPropertyName<T>() where T : class, new()
{
string nameStr = "";
foreach (PropertyInfo pi in (new T()).GetType().GetProperties())
{
//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
var name = pi.Name;
//var value = pi.GetValue(list, null);//用pi.GetValue获得值
//var type = value?.GetType() ?? typeof(object);//获得属性的类型
nameStr += "`" + name + "`,";
}
return nameStr.Substring(0, nameStr.Length - 1);//nameStr; 去除最后一个逗号
}
public static List<Dictionary<string, object>> TableToRow(DataTable tbl)
{
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
foreach (DataRow Row in tbl.Rows)//循环行
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < Row.ItemArray.Length; i++)
{
row.Add(tbl.Columns[i].ColumnName, Row[i].ToString());
}
rows.Add(row);
}
return rows;
}
}
}

995
Services/Tool/RSAPwd.cs Normal file
View File

@@ -0,0 +1,995 @@
using System;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace Services.Tool
{
#region rsa加密
public class RSA
{
/// <summary>
/// 导出XML格式密钥对如果convertToPublic含私钥的RSA将只返回公钥仅含公钥的RSA不受影响
/// </summary>
public string ToXML(bool convertToPublic = false)
{
return rsa.ToXmlString(!rsa.PublicOnly && !convertToPublic);
}
/// <summary>
/// 将密钥对导出成PEM对象如果convertToPublic含私钥的RSA将只返回公钥仅含公钥的RSA不受影响
/// </summary>
public RSA_PEM ToPEM(bool convertToPublic = false)
{
return new RSA_PEM(rsa, convertToPublic);
}
/// <summary>
/// 加密字符串utf-8出错抛异常
/// </summary>
public string Encode(string str)
{
return Convert.ToBase64String(Encode(Encoding.UTF8.GetBytes(str)));
}
/// <summary>
/// 加密数据,出错抛异常
/// </summary>
public byte[] Encode(byte[] data)
{
int blockLen = rsa.KeySize / 8 - 11;
if (data.Length <= blockLen)
{
return rsa.Encrypt(data, false);
}
using (var dataStream = new MemoryStream(data))
using (var enStream = new MemoryStream())
{
Byte[] buffer = new Byte[blockLen];
int len = dataStream.Read(buffer, 0, blockLen);
while (len > 0)
{
Byte[] block = new Byte[len];
Array.Copy(buffer, 0, block, 0, len);
Byte[] enBlock = rsa.Encrypt(block, false);
enStream.Write(enBlock, 0, enBlock.Length);
len = dataStream.Read(buffer, 0, blockLen);
}
return enStream.ToArray();
}
}
/// <summary>
/// 解密字符串utf-8解密异常返回null
/// </summary>
public string DecodeOrNull(string str)
{
if (String.IsNullOrEmpty(str))
{
return null;
}
byte[] byts = null;
try { byts = Convert.FromBase64String(str); } catch { }
if (byts == null)
{
return null;
}
var val = DecodeOrNull(byts);
if (val == null)
{
return null;
}
return Encoding.UTF8.GetString(val);
}
/// <summary>
/// 解密数据解密异常返回null
/// </summary>
public byte[] DecodeOrNull(byte[] data)
{
try
{
int blockLen = rsa.KeySize / 8;
if (data.Length <= blockLen)
{
return rsa.Decrypt(data, false);
}
using (var dataStream = new MemoryStream(data))
using (var deStream = new MemoryStream())
{
Byte[] buffer = new Byte[blockLen];
int len = dataStream.Read(buffer, 0, blockLen);
while (len > 0)
{
Byte[] block = new Byte[len];
Array.Copy(buffer, 0, block, 0, len);
Byte[] deBlock = rsa.Decrypt(block, false);
deStream.Write(deBlock, 0, deBlock.Length);
len = dataStream.Read(buffer, 0, blockLen);
}
return deStream.ToArray();
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 对str进行签名并指定hash算法SHA256
/// </summary>
public string Sign(string hash, string str)
{
return Convert.ToBase64String(Sign(hash, Encoding.UTF8.GetBytes(str)));
}
/// <summary>
/// 对data进行签名并指定hash算法SHA256
/// </summary>
public byte[] Sign(string hash, byte[] data)
{
return rsa.SignData(data, hash);
}
/// <summary>
/// 验证字符串str的签名是否是sgin并指定hash算法SHA256
/// </summary>
public bool Verify(string hash, string sgin, string str)
{
byte[] byts = null;
try { byts = Convert.FromBase64String(sgin); } catch { }
if (byts == null)
{
return false;
}
return Verify(hash, byts, Encoding.UTF8.GetBytes(str));
}
/// <summary>
/// 验证data的签名是否是sgin并指定hash算法SHA256
/// </summary>
public bool Verify(string hash, byte[] sgin, byte[] data)
{
try
{
return rsa.VerifyData(data, hash, sgin);
}
catch
{
return false;
}
}
private RSACryptoServiceProvider rsa;
/// <summary>
/// 最底层的RSACryptoServiceProvider对象
/// </summary>
public RSACryptoServiceProvider RSAObject
{
get
{
return rsa;
}
}
/// <summary>
/// 密钥位数
/// </summary>
public int KeySize
{
get
{
return rsa.KeySize;
}
}
/// <summary>
/// 是否包含私钥
/// </summary>
public bool HasPrivate
{
get
{
return !rsa.PublicOnly;
}
}
/// <summary>
/// 用指定密钥大小创建一个新的RSA出错抛异常
/// </summary>
public RSA(int keySize)
{
var rsaParams = new CspParameters();
rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider(keySize, rsaParams);
}
/// <summary>
/// 通过指定的密钥创建一个RSAxml内可以只包含一个公钥或私钥或都包含出错抛异常
/// </summary>
public RSA(string xml)
{
var rsaParams = new CspParameters();
rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
rsa = new RSACryptoServiceProvider(rsaParams);
rsa.FromXmlString(xml);
}
/// <summary>
/// 通过一个pem文件创建RSApem为公钥或私钥出错抛异常
/// </summary>
public RSA(string pem, bool noop)
{
rsa = RSA_PEM.FromPEM(pem).GetRSA();
}
/// <summary>
/// 通过一个pem对象创建RSApem为公钥或私钥出错抛异常
/// </summary>
public RSA(RSA_PEM pem)
{
rsa = pem.GetRSA();
}
/// <summary>
/// 本方法会先生成RSA_PEM再创建RSA通过公钥指数和私钥指数构造一个PEM会反推计算出P、Q但和原始生成密钥的P、Q极小可能相同
/// 注意所有参数首字节如果是0必须先去掉
/// 出错将会抛出异常
/// </summary>
/// <param name="modulus">必须提供模数</param>
/// <param name="exponent">必须提供公钥指数</param>
/// <param name="dOrNull">私钥指数可以不提供导出的PEM就只包含公钥</param>
public RSA(byte[] modulus, byte[] exponent, byte[] dOrNull)
{
rsa = new RSA_PEM(modulus, exponent, dOrNull).GetRSA();
}
/// <summary>
/// 本方法会先生成RSA_PEM再创建RSA通过全量的PEM字段数据构造一个PEM除了模数modulus和公钥指数exponent必须提供外其他私钥指数信息要么全部提供要么全部不提供导出的PEM就只包含公钥
/// 注意所有参数首字节如果是0必须先去掉
/// </summary>
public RSA(byte[] modulus, byte[] exponent, byte[] d, byte[] p, byte[] q, byte[] dp, byte[] dq, byte[] inverseQ)
{
rsa = new RSA_PEM(modulus, exponent, d, p, q, dp, dq, inverseQ).GetRSA();
}
}
#endregion
public class RSA_PEM
{
/// <summary>
/// modulus 模数n公钥、私钥都有
/// </summary>
public byte[] Key_Modulus;
/// <summary>
/// publicExponent 公钥指数e公钥、私钥都有
/// </summary>
public byte[] Key_Exponent;
/// <summary>
/// privateExponent 私钥指数d只有私钥的时候才有
/// </summary>
public byte[] Key_D;
//以下参数只有私钥才有 https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.rsaparameters?redirectedfrom=MSDN&view=netframework-4.8
/// <summary>
/// prime1
/// </summary>
public byte[] Val_P;
/// <summary>
/// prime2
/// </summary>
public byte[] Val_Q;
/// <summary>
/// exponent1
/// </summary>
public byte[] Val_DP;
/// <summary>
/// exponent2
/// </summary>
public byte[] Val_DQ;
/// <summary>
/// coefficient
/// </summary>
public byte[] Val_InverseQ;
private RSA_PEM() { }
/// <summary>
/// 通过RSA中的公钥和私钥构造一个PEM如果convertToPublic含私钥的RSA将只读取公钥仅含公钥的RSA不受影响
/// </summary>
public RSA_PEM(RSACryptoServiceProvider rsa, bool convertToPublic = false)
{
var isPublic = convertToPublic || rsa.PublicOnly;
var param = rsa.ExportParameters(!isPublic);
Key_Modulus = param.Modulus;
Key_Exponent = param.Exponent;
if (!isPublic)
{
Key_D = param.D;
Val_P = param.P;
Val_Q = param.Q;
Val_DP = param.DP;
Val_DQ = param.DQ;
Val_InverseQ = param.InverseQ;
}
}
/// <summary>
/// 通过全量的PEM字段数据构造一个PEM除了模数modulus和公钥指数exponent必须提供外其他私钥指数信息要么全部提供要么全部不提供导出的PEM就只包含公钥
/// 注意所有参数首字节如果是0必须先去掉
/// </summary>
public RSA_PEM(byte[] modulus, byte[] exponent, byte[] d, byte[] p, byte[] q, byte[] dp, byte[] dq, byte[] inverseQ)
{
Key_Modulus = modulus;
Key_Exponent = exponent;
Key_D = BigL(d, modulus.Length);
int keyLen = modulus.Length / 2;
Val_P = BigL(p, keyLen);
Val_Q = BigL(q, keyLen);
Val_DP = BigL(dp, keyLen);
Val_DQ = BigL(dq, keyLen);
Val_InverseQ = BigL(inverseQ, keyLen);
}
/// <summary>
/// 通过公钥指数和私钥指数构造一个PEM会反推计算出P、Q但和原始生成密钥的P、Q极小可能相同
/// 注意所有参数首字节如果是0必须先去掉
/// 出错将会抛出异常
/// </summary>
/// <param name="modulus">必须提供模数</param>
/// <param name="exponent">必须提供公钥指数</param>
/// <param name="dOrNull">私钥指数可以不提供导出的PEM就只包含公钥</param>
public RSA_PEM(byte[] modulus, byte[] exponent, byte[] dOrNull)
{
Key_Modulus = modulus;//modulus
Key_Exponent = exponent;//publicExponent
if (dOrNull != null)
{
Key_D = BigL(dOrNull, modulus.Length);//privateExponent
//反推P、Q
BigInteger n = BigX(modulus);
BigInteger e = BigX(exponent);
BigInteger d = BigX(dOrNull);
BigInteger p = FindFactor(e, d, n);
BigInteger q = n / p;
if (p.CompareTo(q) > 0)
{
BigInteger t = p;
p = q;
q = t;
}
BigInteger exp1 = d % (p - BigInteger.One);
BigInteger exp2 = d % (q - BigInteger.One);
BigInteger coeff = BigInteger.ModPow(q, p - 2, p);
int keyLen = modulus.Length / 2;
Val_P = BigL(BigB(p), keyLen);//prime1
Val_Q = BigL(BigB(q), keyLen);//prime2
Val_DP = BigL(BigB(exp1), keyLen);//exponent1
Val_DQ = BigL(BigB(exp2), keyLen);//exponent2
Val_InverseQ = BigL(BigB(coeff), keyLen);//coefficient
}
}
/// <summary>
/// 密钥位数
/// </summary>
public int KeySize
{
get
{
return Key_Modulus.Length * 8;
}
}
/// <summary>
/// 是否包含私钥
/// </summary>
public bool HasPrivate
{
get
{
return Key_D != null;
}
}
/// <summary>
/// 将PEM中的公钥私钥转成RSA对象如果未提供私钥RSA中就只包含公钥
/// </summary>
public RSACryptoServiceProvider GetRSA()
{
var rsaParams = new CspParameters();
rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
var rsa = new RSACryptoServiceProvider(rsaParams);
var param = new RSAParameters();
param.Modulus = Key_Modulus;
param.Exponent = Key_Exponent;
if (Key_D != null)
{
param.D = Key_D;
param.P = Val_P;
param.Q = Val_Q;
param.DP = Val_DP;
param.DQ = Val_DQ;
param.InverseQ = Val_InverseQ;
}
rsa.ImportParameters(param);
return rsa;
}
/// <summary>
/// 转成正整数如果是负数需要加前导0转成正整数
/// </summary>
static public BigInteger BigX(byte[] bigb)
{
if (bigb[0] > 0x7F)
{
byte[] c = new byte[bigb.Length + 1];
Array.Copy(bigb, 0, c, 1, bigb.Length);
bigb = c;
}
return new BigInteger(bigb.Reverse().ToArray());//C#的二进制是反的
}
/// <summary>
/// BigInt导出byte整数首字节>0x7F的会加0前导保证正整数因此需要去掉0
/// </summary>
static public byte[] BigB(BigInteger bigx)
{
byte[] val = bigx.ToByteArray().Reverse().ToArray();//C#的二进制是反的
if (val[0] == 0)
{
byte[] c = new byte[val.Length - 1];
Array.Copy(val, 1, c, 0, c.Length);
val = c;
}
return val;
}
/// <summary>
/// 某些密钥参数可能会少一位32个byte只有31个目测是密钥生成器的问题只在c#生成的密钥中发现这种参数java中生成的密钥没有这种现象直接修正一下就行这个问题与BigB有本质区别不能动BigB
/// </summary>
static public byte[] BigL(byte[] bytes, int keyLen)
{
if (keyLen - bytes.Length == 1)
{
byte[] c = new byte[bytes.Length + 1];
Array.Copy(bytes, 0, c, 1, bytes.Length);
bytes = c;
}
return bytes;
}
/// <summary>
/// 由n e d 反推 P Q
/// 资料: https://stackoverflow.com/questions/43136036/how-to-get-a-rsaprivatecrtkey-from-a-rsaprivatekey
/// https://v2ex.com/t/661736
/// </summary>
static private BigInteger FindFactor(BigInteger e, BigInteger d, BigInteger n)
{
BigInteger edMinus1 = e * d - BigInteger.One;
int s = -1;
if (edMinus1 != BigInteger.Zero)
{
s = (int)(BigInteger.Log(edMinus1 & -edMinus1) / BigInteger.Log(2));
}
BigInteger t = edMinus1 >> s;
long now = DateTime.Now.Ticks;
for (int aInt = 2; true; aInt++)
{
if (aInt % 10 == 0 && DateTime.Now.Ticks - now > 3000 * 10000)
{
throw new Exception("推算RSA.P超时");//测试最多循环2次1024位的速度很快 8ms
}
BigInteger aPow = BigInteger.ModPow(new BigInteger(aInt), t, n);
for (int i = 1; i <= s; i++)
{
if (aPow == BigInteger.One)
{
break;
}
if (aPow == n - BigInteger.One)
{
break;
}
BigInteger aPowSquared = aPow * aPow % n;
if (aPowSquared == BigInteger.One)
{
return BigInteger.GreatestCommonDivisor(aPow - BigInteger.One, n);
}
aPow = aPowSquared;
}
}
}
/// <summary>
/// 用PEM格式密钥对创建RSA支持PKCS#1、PKCS#8格式的PEM
/// 出错将会抛出异常
/// </summary>
static public RSA_PEM FromPEM(string pem)
{
RSA_PEM param = new RSA_PEM();
var base64 = _PEMCode.Replace(pem, "");
byte[] data = null;
try { data = Convert.FromBase64String(base64); } catch { }
if (data == null)
{
throw new Exception("PEM内容无效");
}
var idx = 0;
//读取长度
Func<byte, int> readLen = (first) => {
if (data[idx] == first)
{
idx++;
if (data[idx] == 0x81)
{
idx++;
return data[idx++];
}
else if (data[idx] == 0x82)
{
idx++;
return (((int)data[idx++]) << 8) + data[idx++];
}
else if (data[idx] < 0x80)
{
return data[idx++];
}
}
throw new Exception("PEM未能提取到数据");
};
//读取块数据
Func<byte[]> readBlock = () => {
var len = readLen(0x02);
if (data[idx] == 0x00)
{
idx++;
len--;
}
var val = new byte[len];
for (var i = 0; i < len; i++)
{
val[i] = data[idx + i];
}
idx += len;
return val;
};
//比较data从idx位置开始是否是byts内容
Func<byte[], bool> eq = (byts) => {
for (var i = 0; i < byts.Length; i++, idx++)
{
if (idx >= data.Length)
{
return false;
}
if (byts[i] != data[idx])
{
return false;
}
}
return true;
};
if (pem.Contains("PUBLIC KEY"))
{
/****使用公钥****/
//读取数据总长度
readLen(0x30);
//检测PKCS8
var idx2 = idx;
if (eq(_SeqOID))
{
//读取1长度
readLen(0x03);
idx++;//跳过0x00
//读取2长度
readLen(0x30);
}
else
{
idx = idx2;
}
//Modulus
param.Key_Modulus = readBlock();
//Exponent
param.Key_Exponent = readBlock();
}
else if (pem.Contains("PRIVATE KEY"))
{
/****使用私钥****/
//读取数据总长度
readLen(0x30);
//读取版本号
if (!eq(_Ver))
{
throw new Exception("PEM未知版本");
}
//检测PKCS8
var idx2 = idx;
if (eq(_SeqOID))
{
//读取1长度
readLen(0x04);
//读取2长度
readLen(0x30);
//读取版本号
if (!eq(_Ver))
{
throw new Exception("PEM版本无效");
}
}
else
{
idx = idx2;
}
//读取数据
param.Key_Modulus = readBlock();
param.Key_Exponent = readBlock();
int keyLen = param.Key_Modulus.Length;
param.Key_D = BigL(readBlock(), keyLen);
keyLen = keyLen / 2;
param.Val_P = BigL(readBlock(), keyLen);
param.Val_Q = BigL(readBlock(), keyLen);
param.Val_DP = BigL(readBlock(), keyLen);
param.Val_DQ = BigL(readBlock(), keyLen);
param.Val_InverseQ = BigL(readBlock(), keyLen);
}
else
{
throw new Exception("pem需要BEGIN END标头");
}
return param;
}
static private readonly Regex _PEMCode = new Regex(@"--+.+?--+|\s+");
static private readonly byte[] _SeqOID = new byte[] { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
static private readonly byte[] _Ver = new byte[] { 0x02, 0x01, 0x00 };
/// <summary>
/// 将RSA中的密钥对转换成PEM PKCS#1格式
/// 。convertToPublic等于true时含私钥的RSA将只返回公钥仅含公钥的RSA不受影响
/// 。公钥如:-----BEGIN RSA PUBLIC KEY-----,私钥如:-----BEGIN RSA PRIVATE KEY-----
/// 。似乎导出PKCS#1公钥用的比较少PKCS#8的公钥用的多些私钥#1#8都差不多
/// </summary>
public string ToPEM_PKCS1(bool convertToPublic = false)
{
return ToPEM(convertToPublic, false, false);
}
/// <summary>
/// 将RSA中的密钥对转换成PEM PKCS#8格式
/// 。convertToPublic等于true时含私钥的RSA将只返回公钥仅含公钥的RSA不受影响
/// 。公钥如:-----BEGIN PUBLIC KEY-----,私钥如:-----BEGIN PRIVATE KEY-----
/// </summary>
public string ToPEM_PKCS8(bool convertToPublic = false)
{
return ToPEM(convertToPublic, true, true);
}
/// <summary>
/// 将RSA中的密钥对转换成PEM格式
/// 。convertToPublic等于true时含私钥的RSA将只返回公钥仅含公钥的RSA不受影响
/// 。privateUsePKCS8私钥的返回格式等于true时返回PKCS#8格式-----BEGIN PRIVATE KEY-----否则返回PKCS#1格式-----BEGIN RSA PRIVATE KEY-----),返回公钥时此参数无效;两种格式使用都比较常见
/// 。publicUsePKCS8公钥的返回格式等于true时返回PKCS#8格式-----BEGIN PUBLIC KEY-----否则返回PKCS#1格式-----BEGIN RSA PUBLIC KEY-----返回私钥时此参数无效一般用的多的是true PKCS#8格式公钥PKCS#1格式似乎比较少见公钥
/// </summary>
public string ToPEM(bool convertToPublic, bool privateUsePKCS8, bool publicUsePKCS8)
{
var ms = new MemoryStream();
//写入一个长度字节码
Action<int> writeLenByte = (len) => {
if (len < 0x80)
{
ms.WriteByte((byte)len);
}
else if (len <= 0xff)
{
ms.WriteByte(0x81);
ms.WriteByte((byte)len);
}
else
{
ms.WriteByte(0x82);
ms.WriteByte((byte)(len >> 8 & 0xff));
ms.WriteByte((byte)(len & 0xff));
}
};
//写入一块数据
Action<byte[]> writeBlock = (byts) => {
var addZero = (byts[0] >> 4) >= 0x8;
ms.WriteByte(0x02);
var len = byts.Length + (addZero ? 1 : 0);
writeLenByte(len);
if (addZero)
{
ms.WriteByte(0x00);
}
ms.Write(byts, 0, byts.Length);
};
//根据后续内容长度写入长度数据
Func<int, byte[], byte[]> writeLen = (index, byts) => {
var len = byts.Length - index;
ms.SetLength(0);
ms.Write(byts, 0, index);
writeLenByte(len);
ms.Write(byts, index, len);
return ms.ToArray();
};
Action<MemoryStream, byte[]> writeAll = (stream, byts) => {
stream.Write(byts, 0, byts.Length);
};
Func<string, int, string> TextBreak = (text, line) => {
var idx = 0;
var len = text.Length;
var str = new StringBuilder();
while (idx < len)
{
if (idx > 0)
{
str.Append('\n');
}
if (idx + line >= len)
{
str.Append(text.Substring(idx));
}
else
{
str.Append(text.Substring(idx, line));
}
idx += line;
}
return str.ToString();
};
if (Key_D == null || convertToPublic)
{
/****生成公钥****/
//写入总字节数不含本段长度额外需要24字节的头后续计算好填入
ms.WriteByte(0x30);
var index1 = (int)ms.Length;
//PKCS8 多一段数据
int index2 = -1, index3 = -1;
if (publicUsePKCS8)
{
//固定内容
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
writeAll(ms, _SeqOID);
//从0x00开始的后续长度
ms.WriteByte(0x03);
index2 = (int)ms.Length;
ms.WriteByte(0x00);
//后续内容长度
ms.WriteByte(0x30);
index3 = (int)ms.Length;
}
//写入Modulus
writeBlock(Key_Modulus);
//写入Exponent
writeBlock(Key_Exponent);
//计算空缺的长度
var byts = ms.ToArray();
if (index2 != -1)
{
byts = writeLen(index3, byts);
byts = writeLen(index2, byts);
}
byts = writeLen(index1, byts);
var flag = " PUBLIC KEY";
if (!publicUsePKCS8)
{
flag = " RSA" + flag;
}
return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
}
else
{
/****生成私钥****/
//写入总字节数,后续写入
ms.WriteByte(0x30);
int index1 = (int)ms.Length;
//写入版本号
writeAll(ms, _Ver);
//PKCS8 多一段数据
int index2 = -1, index3 = -1;
if (privateUsePKCS8)
{
//固定内容
writeAll(ms, _SeqOID);
//后续内容长度
ms.WriteByte(0x04);
index2 = (int)ms.Length;
//后续内容长度
ms.WriteByte(0x30);
index3 = (int)ms.Length;
//写入版本号
writeAll(ms, _Ver);
}
//写入数据
writeBlock(Key_Modulus);
writeBlock(Key_Exponent);
writeBlock(Key_D);
writeBlock(Val_P);
writeBlock(Val_Q);
writeBlock(Val_DP);
writeBlock(Val_DQ);
writeBlock(Val_InverseQ);
//计算空缺的长度
var byts = ms.ToArray();
if (index2 != -1)
{
byts = writeLen(index3, byts);
byts = writeLen(index2, byts);
}
byts = writeLen(index1, byts);
var flag = " PRIVATE KEY";
if (!privateUsePKCS8)
{
flag = " RSA" + flag;
}
return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
}
}
/// <summary>
/// 将XML格式密钥转成PEM支持公钥xml、私钥xml
/// 出错将会抛出异常
/// </summary>
static public RSA_PEM FromXML(string xml)
{
RSA_PEM rtv = new RSA_PEM();
Match xmlM = xmlExp.Match(xml);
if (!xmlM.Success)
{
throw new Exception("XML内容不符合要求");
}
Match tagM = xmlTagExp.Match(xmlM.Groups[1].Value);
while (tagM.Success)
{
string tag = tagM.Groups[1].Value;
string b64 = tagM.Groups[2].Value;
byte[] val = Convert.FromBase64String(b64);
switch (tag)
{
case "Modulus": rtv.Key_Modulus = val; break;
case "Exponent": rtv.Key_Exponent = val; break;
case "D": rtv.Key_D = val; break;
case "P": rtv.Val_P = val; break;
case "Q": rtv.Val_Q = val; break;
case "DP": rtv.Val_DP = val; break;
case "DQ": rtv.Val_DQ = val; break;
case "InverseQ": rtv.Val_InverseQ = val; break;
}
tagM = tagM.NextMatch();
}
if (rtv.Key_Modulus == null || rtv.Key_Exponent == null)
{
throw new Exception("XML公钥丢失");
}
if (rtv.Key_D != null)
{
if (rtv.Val_P == null || rtv.Val_Q == null || rtv.Val_DP == null || rtv.Val_DQ == null || rtv.Val_InverseQ == null)
{
return new RSA_PEM(rtv.Key_Modulus, rtv.Key_Exponent, rtv.Key_D);
}
}
return rtv;
}
static private readonly Regex xmlExp = new Regex("\\s*<RSAKeyValue>([<>\\/\\+=\\w\\s]+)</RSAKeyValue>\\s*");
static private readonly Regex xmlTagExp = new Regex("<(.+?)>\\s*([^<]+?)\\s*</");
/// <summary>
/// 将RSA中的密钥对转换成XML格式
/// 如果convertToPublic含私钥的RSA将只返回公钥仅含公钥的RSA不受影响
/// </summary>
public string ToXML(bool convertToPublic)
{
StringBuilder str = new StringBuilder();
str.Append("<RSAKeyValue>");
str.Append("<Modulus>" + Convert.ToBase64String(Key_Modulus) + "</Modulus>");
str.Append("<Exponent>" + Convert.ToBase64String(Key_Exponent) + "</Exponent>");
if (Key_D == null || convertToPublic)
{
/****生成公钥****/
//NOOP
}
else
{
/****生成私钥****/
str.Append("<P>" + Convert.ToBase64String(Val_P) + "</P>");
str.Append("<Q>" + Convert.ToBase64String(Val_Q) + "</Q>");
str.Append("<DP>" + Convert.ToBase64String(Val_DP) + "</DP>");
str.Append("<DQ>" + Convert.ToBase64String(Val_DQ) + "</DQ>");
str.Append("<InverseQ>" + Convert.ToBase64String(Val_InverseQ) + "</InverseQ>");
str.Append("<D>" + Convert.ToBase64String(Key_D) + "</D>");
}
str.Append("</RSAKeyValue>");
return str.ToString();
}
}
}

1172
Services/Tool/RedisHelper.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Tool
{
public class ComputerHelp
{
}
}

View File

@@ -0,0 +1,159 @@
using Services.Extensions;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web.Configuration;
namespace Services.Tool
{
/// <summary>
/// web.config操作类
/// Copyright (C) Maticsoft
/// </summary>
public sealed class ConfigHelper
{
/// <summary>
/// 得到AppSettings中的配置字符串信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetConfigString(string key)
{
string CacheKey = "AppSettings-" + key;
object objModel = CacheExtensions.GetCache<object>(CacheKey);
if (objModel == null)
{
try
{
objModel = ConfigurationManager.AppSettings[key];
if (objModel != null)
{
CacheExtensions.SetCache(CacheKey, objModel, Services.Enums.CacheTimeType.ByHours, 3);
}
}
catch
{ }
}
return objModel.ToString();
}
/// <summary>
/// 得到AppSettings中的配置Bool信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool GetConfigBool(string key)
{
bool result = false;
string cfgVal = GetConfigString(key);
if (null != cfgVal && string.Empty != cfgVal)
{
try
{
result = bool.Parse(cfgVal);
}
catch (FormatException)
{
// Ignore format exceptions.
}
}
return result;
}
/// <summary>
/// 得到AppSettings中的配置Decimal信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static decimal GetConfigDecimal(string key)
{
decimal result = 0;
string cfgVal = GetConfigString(key);
if (null != cfgVal && string.Empty != cfgVal)
{
try
{
result = decimal.Parse(cfgVal);
}
catch (FormatException)
{
// Ignore format exceptions.
}
}
return result;
}
/// <summary>
/// 得到AppSettings中的配置int信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static int GetConfigInt(string key)
{
int result = 0;
string cfgVal = GetConfigString(key);
if (null != cfgVal && string.Empty != cfgVal)
{
try
{
result = int.Parse(cfgVal);
}
catch (FormatException)
{
// Ignore format exceptions.
}
}
return result;
}
/// <summary>
/// 修改AppSettings中的配置信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static void UpdatetConfig(string key, string value)
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppSettings = (AppSettingsSection)objConfig.GetSection("appSettings");
if (objAppSettings != null)
{
objAppSettings.Settings[key].Value = value;
objConfig.Save();
}
}
/// <summary>
/// 加载配置文件 app升级配置文件
/// </summary>
/// <returns></returns>
public static Dictionary<String, String> loadCfg()
{
string cfgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
+ Path.DirectorySeparatorChar + "appset" + Path.DirectorySeparatorChar + "appconfig.properties";
Dictionary<String, String> cfg = new Dictionary<string, string>();
using (StreamReader sr = new StreamReader(cfgPath))
{
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
if (line.StartsWith("#"))
{
continue;
}
int startInd = line.IndexOf("=");
string key = line.Substring(0, startInd);
string val = line.Substring(startInd + 1, line.Length - (startInd + 1));
if (!cfg.ContainsKey(key) && !string.IsNullOrEmpty(val))
{
cfg.Add(key, val);
}
}
}
return cfg;
}
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Services.Tool
{
/// <summary>
/// 枚举帮助类
/// </summary>
public static class EnumHelper
{
///// <summary>
///// 获取枚举的Short类型
///// </summary>
///// <param name="value"></param>
///// <returns></returns>
//public static short GetShortValue(Enum value)
//{
// return short.Parse(((int)Enum.Parse(value.GetType(), value.ToString())).ToString());
//}
///// <summary>
///// 得到枚举中文备注
///// </summary>
///// <param name="enumValue"></param>
///// <returns></returns>
//public static string GetEnumDesc(Enum enumValue)
//{
// string value = enumValue.ToString();
// FieldInfo field = enumValue.GetType().GetField(value);
// object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
// if (objs.Length == 0) //当描述属性没有时,直接返回名称
// return value;
// DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
// return descriptionAttribute.Description;
//}
}
}

View File

@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace Services.Tool
{
public class IPHelper
{
public static string GetIP()
{
if (HttpContext.Current == null)
{
throw new Exception("HttpContext.Current为null");
}
string ip = string.Empty;
if (!string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
ip = Convert.ToString(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
if (string.IsNullOrEmpty(ip))
ip = Convert.ToString(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
return ip;
}
/// <summary>获取客户端的IP可以取到代理后的IP
///
/// </summary>
/// <returns></returns>
public static string GetClientIp()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(result))
{
//可能有代理
if (result.IndexOf(".", StringComparison.Ordinal) == -1)
result = null;
else
{
if (result.IndexOf(",", StringComparison.Ordinal) != -1)
{
//有“,”估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
foreach (string t in temparyip)
{
if (IsIpAddress(t)
&& t.Substring(0, 3) != "10."
&& t.Substring(0, 7) != "192.168"
&& t.Substring(0, 7) != "172.16.")
{
return t; //找到不是内网的地址
}
}
}
else if (IsIpAddress(result)) //代理即是IP格式
return result;
else
result = null; //代理中的内容 非IP取IP
}
}
if (string.IsNullOrEmpty(result))
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(result))
result = HttpContext.Current.Request.UserHostAddress;
return result;
}
/// <summary>判断是否是IP地址格式 0.0.0.0
///
/// </summary>
/// <param name="str">待判断的IP地址</param>
/// <returns>true or false</returns>
public static bool IsIpAddress(string str)
{
if (string.IsNullOrEmpty(str) || str.Length < 7 || str.Length > 15) return false;
const string regformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$";
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Newtonsoft.Json;
namespace Services.Tool
{
/// <summary>
/// Token辅助类
/// 需要引用jwt包
/// </summary>
public class TokenHelper
{
//私钥
static string Private_key = "CWLCJLWQZYY";
//创建一个世界协调时间提供对象 utc时间协调时间
static IDateTimeProvider provider = new UtcDateTimeProvider();
//时间戳起点时间
static DateTime timeEpoch = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
//序列化对象
static IJsonSerializer serializer = new JsonNetSerializer();
//编码序列化对象
static IBase64UrlEncoder encoder = new JwtBase64UrlEncoder();
//编码算法
static IJwtAlgorithm algorithm = new HMACSHA384Algorithm();
//jwt编码
static JwtEncoder jwtEncoder= new JwtEncoder(algorithm,serializer,encoder);
//验证对象
static IJwtValidator validator = new JwtValidator(serializer,provider);
//jwt解码
static JwtDecoder decoder = new JwtDecoder(serializer, validator, encoder, algorithm);
/// <summary>
/// 加密的数据键值对传入
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public static string GetToken(Dictionary<string,object> keys,float day)
{
//荷载,负载,最重要的信息,token中保存的信息 keys
var now = provider.GetNow();
//获取当前时间距离时间戳的差秒
var epochSecons = Math.Round((now-timeEpoch).TotalSeconds);
keys.Add("exp",(epochSecons+3600)*24*day);//设置过期时间
//jwt同一加密
var token = jwtEncoder.Encode(keys,Private_key);
return token;
}
public static string CheckToken(string token)
{
try
{
//解码 tonken 私钥 验证是否过期
//过期时间验证 系统默认起始时间为1970,1,1,0,0,0 如果验证过期需要保证起始时间一致
//要么手动验证过期,现在时间与起始时间的差值如果大于设置exp则过期
return JsonConvert.DeserializeObject<Datainfo>(decoder.Decode(token, Private_key,verify: true)).data.ToString();//str数据转成Dictionary<string,object>类型即可
}
catch (Exception)
{
return null;
}
}
public class Datainfo {
public dynamic data { get; set; }
public dynamic exp { get; set; }
}
}
}

171
Services/UserLoginHelper.cs Normal file
View File

@@ -0,0 +1,171 @@
// Services.UserLoginHelper
using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using Models;
using Models.ModelItems;
using Models.View;
using Services.Cache;
using Services.Extensions;
using Services.Manager;
using Services.Tool;
public class UserLoginHelper
{
private static string CookieName_User = (ConfigHelper.GetConfigString("DBName") + "_UserInfo").ToMD5();
private static string CookieName_Token = (ConfigHelper.GetConfigString("DBName") + "_TokenInfo").ToMD5();
/// <summary>
/// ....
/// </summary>
/// <returns></returns>
public static View_UserInfo CurrentUser()
{
View_UserInfo user = HttpContext.Current.Session[CookieName_User] as View_UserInfo;
if (user != null && CacheHelp.cacheSysUserInfo.FirstOrDefault(a => a.Pwd == user.Pwd && a.Uid == user.Uid && a.IsValid >=2 ) != null)
{
Logs.WriteLog("userֵ" + user.Uid);
return user;
}
if (HttpContext.Current.Session["ras"] != null && HttpContext.Current.Request.Cookies[CookieName_User] != null && HttpContext.Current.Request.Cookies[CookieName_Token] != null)
{
RSA rSA = HttpContext.Current.Session["ras"] as RSA;
string keyword = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[CookieName_User].Value).Trim().ToLower();
Logs.WriteLog("keyword" + keyword);
string value = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[CookieName_Token].Value);
Logs.WriteLog("value"+value);
string pwd = (string.IsNullOrEmpty(rSA.DecodeOrNull(value)) ? "" : rSA.DecodeOrNull(value));
View_UserInfo view_UserInfo = CacheHelp.cacheSysUserInfo.First(a => a.Uid == keyword);
UserInfo usernew = new UserInfo() { Uid = keyword.Trim().ToLower(), Pwd = pwd, CreateTime = view_UserInfo.CreateTime };
usernew = usernew.ComputePasswordHash();
if (view_UserInfo == null || view_UserInfo.Pwd != usernew.Pwd || view_UserInfo.IsValid == 1)
{
return null;
}
else
{
Logs.WriteLog("view_UserInfo" + view_UserInfo);
return view_UserInfo;
}
}
return null;
}
public static UserInfo CurrentUserAsync(HttpContext context)
{
//δʹ<CEB4><CAB9> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
UserInfo userInfo = context.Session[CookieName_User] as UserInfo;
if (userInfo != null)
{
return userInfo;
}
if (context.Request.Cookies[CookieName_User] != null && context.Request.Cookies[CookieName_Token] != null)
{
RSA rSA = HttpContext.Current.Session["ras"] as RSA;
string keyword = context.Request.Cookies[CookieName_User].Value;
string pwd = (string.IsNullOrEmpty(rSA.DecodeOrNull(context.Request.Cookies[CookieName_Token].Value)) ? "" : rSA.DecodeOrNull(context.Request.Cookies[CookieName_Token].Value));
var user = SqlSugarBase.Db.Queryable<UserInfo>().First(x => x.Uid == keyword.Trim());
UserInfo usernew = user.Clones();
usernew.Pwd = pwd;
usernew = usernew.ComputePasswordHash();
return user;
}
return null;
}
public static View_UserInfo GetUserLoginBy(string keyword, string password, int tYPE = 0)
{
string pwd = password;
if (tYPE == 0) {
RSA rSA = HttpContext.Current.Session["ras"] as RSA;
if (rSA == null)
{
throw new CustomException("<22><>Կ<EFBFBD><D4BF><EFBFBD>ڣ<EFBFBD><DAA3><EFBFBD>ˢ<EFBFBD>½<EFBFBD><C2BD><EFBFBD>!");
}
UserLogout();
if (string.IsNullOrEmpty(rSA.DecodeOrNull(password)))
{
throw new CustomException("<22><>Կ<EFBFBD><D4BF><EFBFBD>ڣ<EFBFBD><DAA3><EFBFBD>ˢ<EFBFBD>½<EFBFBD><C2BD><EFBFBD>!");
}
pwd = rSA.DecodeOrNull(password);
}
keyword = keyword.Trim().ToLower();
View_UserInfo view_UserInfo = CacheHelp.cacheSysUserInfo.FirstOrDefault( a => a.Uid.Trim().ToLower() == keyword);
if (view_UserInfo == null)
{
throw new CustomException("<22>˺<EFBFBD><CBBA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!");
}
UserInfo usernew = new UserInfo() { Uid = keyword.Trim(), Pwd = pwd, CreateTime = view_UserInfo == null ? DateTime.Now : view_UserInfo.CreateTime };
usernew = usernew.ComputePasswordHash();
string str = usernew.HashCode(view_UserInfo.Uid.ToUpper() + pwd +( view_UserInfo == null ? DateTime.Now : view_UserInfo.CreateTime).ToString("yyyy-MM-dd HH:mm:ss"));
if (view_UserInfo == null || usernew.Pwd != view_UserInfo.Pwd)
{
throw new CustomException("<22>˺<EFBFBD><CBBA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!");
}
if (view_UserInfo.IsValid == 1)
throw new CustomException("<22>˺Ŷ<CBBA><C5B6><EFBFBD>!");
else
{
if (view_UserInfo.IsValid < 2)
throw new CustomException("<22><>ֹ<EFBFBD><D6B9><EFBFBD><EFBFBD>!");
}
HttpContext.Current.Session[CookieName_User] = view_UserInfo;
CookieExtensions.WriteCookie(CookieName_User, HttpUtility.UrlEncode(keyword, Encoding.GetEncoding("UTF-8")), 60);
CookieExtensions.WriteCookie(CookieName_Token, HttpUtility.UrlEncode(password, Encoding.GetEncoding("UTF-8")), 60);
return view_UserInfo;
}
public static void UserLogout()
{
if (CheckUserLogin())
{
string name = HttpContext.Current.User.Identity.Name;
FormsAuthentication.SignOut();
RemoveUser(name);
}
}
public static void RemoveUser(string ID)
{
HttpContext.Current.Session.Clear();//ɾ<><C9BE><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Session
//HttpContext.Current.Response.Cookies.Clear();//ɾ<><C9BE><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Cookies
HttpCookie httpCookie = HttpContext.Current.Request.Cookies[CookieName_User];
httpCookie.Expires = DateTime.Now.AddDays(-1.0);
HttpContext.Current.Response.Cookies.Add(httpCookie);
HttpCookie httpCookie2 = HttpContext.Current.Request.Cookies[CookieName_Token];
httpCookie2.Expires = DateTime.Now.AddDays(-1.0);
HttpContext.Current.Response.Cookies.Add(httpCookie2);
}
public static bool CheckUserLogin()
{
try
{
if (HttpContext.Current.Request.Cookies[CookieName_User] != null && HttpContext.Current.Request.Cookies[CookieName_Token] != null)
{
string keyword = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[CookieName_User].Value);
RSA rSA = HttpContext.Current.Session["ras"] as RSA ?? throw new CustomException("ras<61><73><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>~");
string pwd = (string.IsNullOrEmpty(rSA.DecodeOrNull(HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[CookieName_Token].Value))) ? "" : rSA.DecodeOrNull(HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[CookieName_Token].Value)));
View_UserInfo view_UserInfo = CacheHelp.cacheSysUserInfo.Single((View_UserInfo a) => a.Uid == keyword);
UserInfo usernew = new UserInfo() { Uid = keyword.Trim(), Pwd = pwd, CreateTime = view_UserInfo == null ? DateTime.Now : view_UserInfo.CreateTime };
usernew = usernew.ComputePasswordHash();
if (view_UserInfo == null || view_UserInfo.Pwd != usernew.Pwd)
return false;
else
return true;
}
return false;
}
catch (Exception ex)
{
Logs.WriteLog("<22><><EFBFBD><EFBFBD><EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD><EFBFBD>"+ ex.Message);
return false;
}
}
}

80
Services/packages.config Normal file
View File

@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="BouncyCastle" version="1.8.5" targetFramework="net461" />
<package id="EntityFramework" version="6.2.0" targetFramework="net461" />
<package id="Google.Protobuf" version="3.19.4" targetFramework="net461" />
<package id="JWT" version="8.6.0" targetFramework="net461" />
<package id="K4os.Compression.LZ4" version="1.2.6" targetFramework="net461" />
<package id="K4os.Compression.LZ4.Streams" version="1.2.6" targetFramework="net461" />
<package id="K4os.Hash.xxHash" version="1.0.6" targetFramework="net461" />
<package id="Microsoft.AspNet.Mvc" version="5.2.4" targetFramework="net48" />
<package id="Microsoft.AspNet.Razor" version="3.2.4" targetFramework="net48" />
<package id="Microsoft.AspNet.WebPages" version="3.2.4" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Authentication.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Authentication.Core" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Authorization" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Authorization.Policy" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Hosting.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Hosting.Server.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Http" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Http.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Http.Extensions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Http.Features" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Mvc.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Mvc.Core" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Mvc.DataAnnotations" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.ResponseCaching.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Routing" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.Routing.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.AspNetCore.WebUtilities" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="1.1.0" targetFramework="net48" />
<package id="Microsoft.DotNet.PlatformAbstractions" version="2.1.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Caching.Abstractions" version="3.1.4" targetFramework="net48" />
<package id="Microsoft.Extensions.Caching.Memory" version="3.1.4" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration.Abstractions" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration.Binder" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration.EnvironmentVariables" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration.FileExtensions" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Configuration.Json" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.DependencyInjection" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.DependencyModel" version="2.1.0" targetFramework="net48" />
<package id="Microsoft.Extensions.FileProviders.Abstractions" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.FileProviders.Physical" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.FileSystemGlobbing" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Hosting.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Localization" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Localization.Abstractions" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="3.1.4" targetFramework="net48" />
<package id="Microsoft.Extensions.ObjectPool" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Extensions.Options" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Options.ConfigurationExtensions" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Extensions.Primitives" version="3.1.23" targetFramework="net48" />
<package id="Microsoft.Net.Http.Headers" version="2.2.0" targetFramework="net48" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net48" />
<package id="MySql.Data" version="8.0.29" targetFramework="net461" requireReinstallation="true" />
<package id="MySqlConnector" version="2.1.10" targetFramework="net461" requireReinstallation="true" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
<package id="StackExchange.Redis" version="1.2.6" targetFramework="net461" />
<package id="System.Buffers" version="4.5.1" targetFramework="net461" />
<package id="System.ComponentModel.Annotations" version="4.7.0" targetFramework="net48" />
<package id="System.Configuration.ConfigurationManager" version="4.7.0" targetFramework="net48" />
<package id="System.Diagnostics.DiagnosticSource" version="5.0.1" targetFramework="net461" />
<package id="System.Drawing.Common" version="4.7.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.4" targetFramework="net461" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net461" />
<package id="System.Runtime.CompilerServices.Unsafe" version="5.0.0" targetFramework="net461" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.0.0" targetFramework="net48" />
<package id="System.Runtime.Loader" version="4.3.0" targetFramework="net48" />
<package id="System.Security.AccessControl" version="4.7.0" targetFramework="net48" />
<package id="System.Security.Permissions" version="4.7.0" targetFramework="net48" />
<package id="System.Security.Principal.Windows" version="4.7.0" targetFramework="net48" />
<package id="System.Text.Encoding.CodePages" version="5.0.0" targetFramework="net48" />
<package id="System.Text.Encodings.Web" version="4.7.1" targetFramework="net48" />
<package id="System.Text.Json" version="4.7.2" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
<package id="UtilsSharp" version="2.5.0" targetFramework="net48" />
<package id="UtilsSharp.Shared" version="1.0.0" targetFramework="net48" />
</packages>