安睿特接口
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

785 lines
28 KiB

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using XS_DAL;
using XS_Model;
namespace XS_BLL
{
public static class UtilityBLL
{
/// <summary>
/// Md5 加密
/// </summary>
/// <param name="txt"></param>
/// <returns></returns>
public static string GenerateMD5(string txt)
{
using (MD5 mi = MD5.Create())
{
byte[] buffer = Encoding.UTF8.GetBytes(txt);
//开始加密
byte[] newBuffer = mi.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newBuffer.Length; i++)
{
sb.Append(newBuffer[i].ToString("X2"));
}
return sb.ToString();
}
}
/// <summary>
/// 生成获取UUID
/// </summary>
/// <param name="bl"></param>
/// <returns></returns>
public static string GetUuid(bool bl = false)
{
string uuid = string.Empty;
if (bl)
{
//带'-'
uuid = System.Guid.NewGuid().ToString();
}
else
{
//不带'-'
uuid = System.Guid.NewGuid().ToString("N");
}
return uuid;
}
/// <summary>
/// 获取json中指定Key的value值 不能取集合中数据
/// </summary>
/// <param name="recieveBuffer">json串</param>
/// <param name="key">json节点</param>
/// <returns></returns>
public static string GetReceiveValues(string recieveBuffer, string key)
{
try
{
key = key.Replace(" ", "");
string[] keys = key.Split(',');
string resMag = recieveBuffer;
if (!string.IsNullOrEmpty(recieveBuffer))
{
for (int i = 0; i < keys.Count(); i++)
{
JObject obj = Newtonsoft.Json.Linq.JObject.Parse(resMag);
if (obj.Property(keys[i]) != null)
{
resMag = obj[keys[i]].ToString();
}
else
{
resMag = "";
}
}
}
return resMag;
}
catch (Exception ex)
{
LogHelper.ErrorLog(ex);
return "";
}
}
/// <summary>
/// 接收就送数据返回泛型集合{"header":{},"body":{"reqCode":"qw","data":[{}]}}
/// </summary>
/// <typeparam name="T">泛型实体类</typeparam>
/// <param name="recieveBuffer">json数据</param>
/// <returns></returns>
public static List<T> GetReceiveValuesList<T>(string recieveBuffer, string key)
{
try
{
JavaScriptSerializer Jss = new JavaScriptSerializer();
Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(recieveBuffer);
string resMag = GetReceiveValues(recieveBuffer, key);
List<T> busList = Jss.Deserialize<List<T>>(resMag);
return busList;
}
catch (Exception ex)
{
LogHelper.ErrorLog(ex);
return null;
}
}
/// <summary>
/// 添加接口日志、界面显示信息
/// </summary>
/// <param name="name">接口名称</param>
/// <param name="flow">数据方向</param>
/// <param name="reqJson">请求数据</param>
/// <param name="retJson">反馈数据</param>
/// <param name="meno">接口注释/备注</param>
/// <param name="type">是否显示及添加记录</param>
public static void CreateINTERFACE_LOG(string name, string flow, string reqJson, string retJson, string note, int type = 0)
{
try
{
name = name.Replace("/", "_");
IO_INTERFACE_LOG IModel = new IO_INTERFACE_LOG();
#region 接口日志记录-数据库
IModel = new IO_INTERFACE_LOG();
IModel.interface_name = name.Replace("/", "_");
IModel.interface_flow = flow;
IModel.interface_request = reqJson.Replace("'", "''");
IModel.interface_feedback = retJson.Replace("'", "''");
IModel.interface_datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
IModel.interface_meno = note;
bool bl = IModel.Insert();
#endregion 接口日志记录
#region 显示数据信息
switch (type)
{
case 0:
new DisplaySet().AddListBoxItem("", "");
new DisplaySet().AddListBoxItem("请求-->>" + note + ":", reqJson);
new DisplaySet().AddListBoxItem("反馈-->>" + note + ":", retJson);
break;
default:
break;
}
#endregion
#region 接口日志记录-文件
LogHelper.LogOperation(name, reqJson, retJson);
#endregion
}
catch (Exception ex)
{
LogHelper.ErrorLog(ex);
}
}
/// <summary>
/// 接口数据记录 源数据
/// </summary>
/// <param name="name"></param>
/// <param name="flow"></param>
/// <param name="reqJson"></param>
/// <param name="retJson"></param>
public static void CreateINTERFACE_LOG(string name, string flow, string reqJson, string retJson)
{
try
{
IO_INTERFACE_LOG IModel = new IO_INTERFACE_LOG();
#region 接口日志记录-数据库
IModel = new IO_INTERFACE_LOG();
IModel.interface_name = name;
IModel.interface_flow = flow;
IModel.interface_request = reqJson.Replace("'", "''");
IModel.interface_feedback = retJson.Replace("'", "''");
IModel.interface_datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
IModel.interface_meno = flow;
bool bl = IModel.Insert();
#endregion 接口日志记录
#region 接口日志记录-文件
LogHelper.LogOperation(flow, reqJson, retJson);
#endregion
}
catch (Exception ex)
{
LogHelper.ErrorLog(ex);
}
}
#region
///// <summary>
///// 实体类转JSON
///// </summary>
///// <param name="rModel">返回实体类</param>
///// <param name="pageNum">当前页</param>
///// <param name="totalPage">每页行数</param>
///// <param name="dtCount">总页数</param>
///// <returns></returns>
//public static string retHttpJson(t_result rModel, int i = 0)
//{
// try
// {
// string paramString = string.Empty;
// JObject joB = new JObject();
// string sign = Global.appSecret;
// string message = string.IsNullOrEmpty(rModel.message) ? "" : rModel.message;
// var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
// if (rModel.i_type == 0)
// {
// string js = string.Empty;
// if (rModel.dtCount > 0)
// {
// paramString = JsonConvert.SerializeObject(new
// {
// reqCode = rModel.reqCode,
// code = rModel.code,
// message = message,
// data = new { list = rModel.data, totalPage = rModel.pageNum, pageSize = rModel.totalPage, count = rModel.dtCount }
// }, Formatting.Indented, jsonSetting);
// }
// else
// {
// if (i == 1)
// {
// paramString = JsonConvert.SerializeObject(new
// {
// reqCode = rModel.reqCode,
// code = rModel.code,
// message = message,
// data = rModel.materielList
// }, Formatting.Indented, jsonSetting);
// }
// else
// {
// paramString = JsonConvert.SerializeObject(new
// {
// reqCode = rModel.reqCode,
// code = rModel.code,
// message = message,
// data = rModel.data
// }, Formatting.Indented, jsonSetting);
// }
// }
// }
// else
// {
// string uuid = getUuid();
// paramString = JsonConvert.SerializeObject(new
// {
// reqCode = string.IsNullOrEmpty(rModel.reqCode) ? uuid : rModel.reqCode,
// data = rModel.data
// }, Formatting.Indented, jsonSetting);
// }
// //var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include };
// //var json = JsonConvert.SerializeObject(paramString, Formatting.Indented, jsonSetting);
// return paramString;
// //return json;
// }
// catch (Exception ex)
// {
// return ex.Message;
// }
//}
//public static string retHttpJson(t_result rModel)
//{
// JObject joH = new JObject();
// JObject joB = new JObject();
// JObject jo = new JObject();
// string sign = Global.appSecret;
// string message = string.IsNullOrEmpty(rModel.message) ? "" : rModel.message;
// joH.Add("appKey", Global.appKey);
// joH.Add("requestPlan", Global.requestPlan);
// joH.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
// joH.Add("version", Global.version);
// joH.Add("httpVersion", Global.httpVersion);
// if (rModel.i_type == 0)
// {
// joH.Add("sign", GenerateMD5(sign + rModel.reqCode));
// joB.Add("reqCode", rModel.reqCode);
// joB.Add("code", rModel.code);
// if (message.Length > 255)
// {
// message = message.Substring(0, 250) + "...";
// }
// joB.Add("message", message);
// if (rModel.data != null)
// {
// joB.Add("data", rModel.data);
// }
// }
// else
// {
// string uuid = getUuid();
// joH.Add("sign", GenerateMD5(sign + uuid));
// joB.Add("reqCode", uuid);
// if (rModel.data != null)
// {
// joB.Add("data", rModel.data);
// }
// if (rModel.file != null)
// {
// string myStr = System.Text.Encoding.UTF8.GetString(rModel.file);
// byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(myStr);
// string myStr001 = System.Text.Encoding.UTF8.GetString(rModel.file);
// joB.Add("file", rModel.file);
// }
// }
// jo.Add("header", joH);
// jo.Add("body", joB);
// string paramString = jo.ToString(Newtonsoft.Json.Formatting.None, null);
// string strFile = utilityBLL.getReceiveValues(paramString, "body,file");
// return paramString;
//}
#endregion
/// <summary>
/// 生成JSON
/// </summary>
/// <param name="type">JSON格式类型</param>
/// <param name="rCode">返回在参数值:0 成功,1 失败 </param>
/// <param name="rSuccess">返回是否成功</param>
/// <param name="rMsg">返回描述信息</param>
/// <param name="rDate">返回数据</param>
/// <returns>返回JSON 信息</returns>
public static string CreateJson(int type, int rCode, bool rSuccess, string rMsg)
{
string json;
try
{
JObject dataJson = null;
switch (type)
{
case 0:
json = rMsg;
break;
case 1:
json = JsonConvert.SerializeObject(new { code = rCode, success = rSuccess, msg = rMsg, data = dataJson });
break;
case 2:
json = JsonConvert.SerializeObject(new { code = rCode, success = rSuccess, msg = rMsg, data = dataJson });
break;
default:
json = JsonConvert.SerializeObject(new { code = "1", success = false, msg = "无效参数" });
break;
}
return json;
}
catch (Exception ex)
{
JObject dataJson = null;
json = JsonConvert.SerializeObject(new { code = "1", success = false, msg = "JSON生成失败!" + ex.Message, data = dataJson });
return json;
}
}
/// <summary>
/// 生成JSON
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="type">JSON格式类型</param>
/// <param name="rCode">返回在参数值:0 成功,1 失败 </param>
/// <param name="rSuccess">返回是否成功</param>
/// <param name="rMsg">返回描述信息</param>
/// <param name="model">返回数据源</param>
/// <returns></returns>
public static string CreateJson<T>(int type, int rCode, bool rSuccess, string rMsg, List<T> model = null)
{
string json;
try
{
switch (type)
{
case 0:
json = rMsg;
break;
case 1:
json = JsonConvert.SerializeObject(new { code = rCode, success = rSuccess, msg = rMsg, data = model });
break;
default:
json = JsonConvert.SerializeObject(new { code = "1", success = false, msg = "无效参数" });
break;
}
return json;
}
catch (Exception ex)
{
json = JsonConvert.SerializeObject(new { code = "1", success = false, msg = "JSON生成失败!" + ex.Message });
return json;
}
}
/// <summary>
/// List集合转换为DataTable
/// 调用示例 : DataTable tb = ToDataTable(List集合);
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="collection">集合</param>
/// <returns>DataTable</returns>
public static DataTable ListToDataTable<T>(List<T> list)
{
//创建一个名为"tableName"的空表
DataTable dt = new DataTable("tableName");
if (list.Count > 0)
{
//创建传入对象名称的列
foreach (var item in list.FirstOrDefault().GetType().GetProperties())
{
dt.Columns.Add(item.Name);
}
//循环存储
foreach (var item in list)
{
//新加行
DataRow value = dt.NewRow();
//根据DataTable中的值,进行对应的赋值
foreach (DataColumn dtColumn in dt.Columns)
{
int i = dt.Columns.IndexOf(dtColumn);
//基元元素,直接复制,对象类型等,进行序列化
if (value.GetType().IsPrimitive)
{
value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
}
else
{
string aa = "";
if (item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item) != null)
{
aa = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item).ToString();
value[i] = aa;
}
else
{
aa = "";
}
//value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));
}
}
dt.Rows.Add(value);
}
}
return dt;
/*
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
*/
}
/// <summary>
/// DataTable转成List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToDataList<T>(DataTable dt)
{
var list = new List<T>();
var plist = new List<PropertyInfo>(typeof(T).GetProperties());
foreach (DataRow item in dt.Rows)
{
T s = Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
try
{
if (!Convert.IsDBNull(item[i]))
{
object v = null;
if (info.PropertyType.ToString().Contains("System.Nullable"))
{
v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
v = Convert.ChangeType(item[i], info.PropertyType);
}
info.SetValue(s, v, null);
}
}
catch (Exception ex)
{
throw new Exception("字段[" + info.Name + "]转换出错,value:" + item[i] + ex.ToString());
}
}
}
list.Add(s);
}
return list;
}
/// <summary>
/// JSON格式化
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string JsonToString(string str)
{
try
{
//格式化json字符串
JsonSerializer serializer = new JsonSerializer();
TextReader tr = new StringReader(str);
JsonTextReader jtr = new JsonTextReader(tr);
object obj = serializer.Deserialize(jtr);
if (obj != null)
{
StringWriter textWriter = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar = ' '
};
serializer.Serialize(jsonWriter, obj);
return textWriter.ToString();
}
else
{
return str;
}
}
catch (Exception ex)
{
return str;
}
}
public static bool PrevInstance()
{
string procName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
if (System.Diagnostics.Process.GetProcessesByName(procName).GetUpperBound(0) >= 1)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// SqlServer 数据库链接验证
/// </summary>
/// <param name="connString">链接字符</param>
/// <returns></returns>
public static bool IsDbConnected(string connString = "")
{
SqlConnection mySqlConnection;
//获取数据库连接字符串
//创建连接对象
if (string.IsNullOrEmpty(connString))
{
mySqlConnection = new SqlConnection(Global.connstring);
}
else
{
mySqlConnection = new SqlConnection(connString);
}
//ConnectionTimeout 在.net 1.x 可以设置 在.net 2.0后是只读属性,则需要在连接字符串设置
//如:server=.;uid=sa;pwd=;database=PMIS;Integrated Security=SSPI; Connection Timeout=30
//mySqlConnection.ConnectionTimeout = 10;//设置连接超时的时间
bool IsCanConnectioned = false;
try
{
//Open DataBase
//打开数据库
mySqlConnection.Open();
IsCanConnectioned = true;
}
catch
{
//Can not Open DataBase
//打开不成功 则连接不成功
IsCanConnectioned = false;
}
finally
{
//Close DataBase
//关闭数据库连接
mySqlConnection.Close();
}
//mySqlConnection is a SqlConnection object
if (mySqlConnection.State == ConnectionState.Closed || mySqlConnection.State == ConnectionState.Broken)
{
//Connection is not available
return IsCanConnectioned;
}
else
{
//Connection is available
return IsCanConnectioned;
}
}
/// <summary>
/// 删除表数据
/// </summary>
/// <param name="delName"></param>
/// <param name="where"></param>
public static void DelInterface(string delName, string where)
{
try
{
string sql = " delete " + delName;
if (!string.IsNullOrEmpty(where.Trim()))
{
sql += where;
}
DBOperator.DelSql(sql, out string retEx);
}
catch (Exception ex)
{
throw;
}
}
private static object objbm = new object();
/// <summary>
/// 获取调度生成的调度任务的索引
/// </summary>
/// <returns></returns>
public static int GetTempManageIdx()
{
//20100108
try
{
lock (objbm)
{
int maxIdx = 10001;
T_Base_Manage_Task_Index_Temp_Task maxIdx1 = new T_Base_Manage_Task_Index_Temp_Task();
List<T_Base_Manage_Task_Index_Temp_Task> maxIdx2 = maxIdx1.GetModelList();
maxIdx = maxIdx2.Select(c => c.F_ManageTaskIndex).First();
if (maxIdx > 0)
{
if ((maxIdx + 1) >= 19998)
{
maxIdx = 10001;
}
else
{
maxIdx = (maxIdx + 1);
}
}
else
{
maxIdx = 10001;
}
//判断临时调度任务表是否有重复值
IO_CONTROL model = new IO_CONTROL();
List<IO_CONTROL> model1 = model.GetModelList("CONTROL_ID='" + maxIdx + "'");
if (model1.Count == 1)
{
RecordMaxTempManageTaskFID(maxIdx);
maxIdx = GetTempManageIdx();
return maxIdx;
}
RecordMaxTempManageTaskFID(maxIdx);
return maxIdx;
}
}
catch (Exception ex)
{//20100108
throw ex;
}
finally
{
}
}
/// <summary>
/// 记录调度生成的调度任务的索引的最大值
/// </summary>
/// <param name="fid">调度生成的调度任务的索引</param>
public static void RecordMaxTempManageTaskFID(int fid)
{//20100108
try
{//20100108
T_Base_Manage_Task_Index_Temp_Task maxIdx = new T_Base_Manage_Task_Index_Temp_Task();
List<T_Base_Manage_Task_Index_Temp_Task> maxIdx1 = maxIdx.GetModelList();
if (maxIdx1.Count > 0)
{
maxIdx.Update("F_ManageTaskIndex='" + fid + "'");
return;
//}
}
else
{
maxIdx = new T_Base_Manage_Task_Index_Temp_Task();
maxIdx.F_ManageTaskIndex = fid;
maxIdx.Insert();
return;
}
}
catch (Exception ex)
{//20100108
throw ex;
//return 0;
}
finally
{//20100108
}
}
/// <summary>
/// 任务号生成
/// </summary>
public class T_Base_Manage_Task_Index_Temp_Task
{
/// <summary>
/// 任务号
/// </summary>
public int F_ManageTaskIndex { get; set; }
}
}
}