using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Npgsql; using Oracle.ManagedDataAccess.Client; using Shentun.Utilities; using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Shentun.Peis.PlugIns { public class PlugInsBase { protected IConfiguration AppConfig; protected IConfiguration InterfaceConfig; protected string? AppConnctionStr; private string _appBaseAddress; private string _accesToken; protected string? AppUser; protected string? AppPassword; protected string InterfaceSql; protected string InterfaceSqlKeyColumn; protected string InterfaceDbType; protected string? InterfaceConnctionStr; protected string? InterfaceWebApiAddress; protected Guid ItemColumnReferenceId; protected Guid AsbitemColumnReferenceId; protected Guid DepartmentColumnReferenceId; protected Guid UserColumnReferenceId; static PlugInsBase() { Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true; } public PlugInsBase(string parmValue) { AppConfig = new ConfigurationBuilder() .SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); AppConnctionStr = AppConfig.GetSection("ConnectionStrings") .GetSection("Default").Value; _appBaseAddress = AppConfig.GetSection("App") .GetSection("SelfUrl").Value; AppUser = AppConfig.GetSection("App") .GetSection("AppUser").Value; AppPassword = AppConfig.GetSection("App") .GetSection("AppPassword").Value; var configurationBuilder = new ConfigurationBuilder() .AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(parmValue))); InterfaceConfig = configurationBuilder.Build(); InterfaceSql = InterfaceConfig.GetSection("Interface").GetSection("Sql").Value; InterfaceSqlKeyColumn = InterfaceConfig.GetSection("Interface").GetSection("SqlKeyColumn").Value; InterfaceDbType = InterfaceConfig.GetSection("Interface").GetSection("DbType").Value; InterfaceWebApiAddress = InterfaceConfig.GetSection("Interface").GetSection("WebApiAddress").Value; InterfaceConnctionStr = InterfaceConfig.GetSection("Interface").GetSection("ConnectionStrings").Value; var itemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface") .GetSection("ItemColumnReferenceId").Value; if (!string.IsNullOrWhiteSpace(itemColumnReferenceIdStr)) { ItemColumnReferenceId = new Guid(itemColumnReferenceIdStr); } var asbItemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface") .GetSection("AsbitemColumnReferenceId").Value; if (!string.IsNullOrWhiteSpace(asbItemColumnReferenceIdStr)) { AsbitemColumnReferenceId = new Guid(asbItemColumnReferenceIdStr); } var departmentColumnReferenceIdStr = InterfaceConfig.GetSection("Interface") .GetSection("DepartmentColumnReferenceId").Value; if (!string.IsNullOrWhiteSpace(departmentColumnReferenceIdStr)) { DepartmentColumnReferenceId = new Guid(departmentColumnReferenceIdStr); } var userColumnReferenceIdStr = InterfaceConfig.GetSection("Interface") .GetSection("UserColumnReferenceId").Value; if (!string.IsNullOrWhiteSpace(userColumnReferenceIdStr)) { UserColumnReferenceId = new Guid(userColumnReferenceIdStr); } } protected DbConnection CreateInterfaceDbConnect() { DbConnection conn; if (string.IsNullOrWhiteSpace(InterfaceConnctionStr)) { throw new ArgumentException("数据连接设置中的DbType不能为空"); } InterfaceDbType = InterfaceDbType.ToLower(); if (InterfaceDbType == "sqlserver") { conn = new SqlConnection(InterfaceConnctionStr); } else if (InterfaceDbType == "postgres") { conn = new NpgsqlConnection(InterfaceConnctionStr); } else if (InterfaceDbType == "oracle") { conn = new OracleConnection(InterfaceConnctionStr); } else { throw new ArgumentException("数据连接设置中的DbType不支持"); } return conn; } public async Task CallAppServiceAsync(string url, TInput data) { string baseAddress = _appBaseAddress; using (var httpClientHandler = new HttpClientHandler()) { using (var httpClient = new HttpClient(httpClientHandler)) { httpClient.BaseAddress = new Uri(baseAddress); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型 //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesToken); IsoDateTimeConverter timeFormat = new IsoDateTimeConverter(); timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; var sendData = JsonConvert.SerializeObject(data,Newtonsoft.Json.Formatting.Indented, timeFormat); using (HttpContent httpContent = new StringContent(sendData)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await httpClient.PostAsync(url, httpContent); string result; if (!response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result); } result = await response.Content.ReadAsStringAsync(); dynamic resultDto = JsonConvert.DeserializeObject(result); if(resultDto != null) { if(resultDto.code == "-1") { throw new Exception($"调用WebApi失败,返回-1,消息:"+resultDto.message); } } return resultDto; } } } } public virtual async Task DoWorkAsync() { } public virtual Task DoWork() { return Task.CompletedTask; } protected async virtual Task LoginAsync() { var relult = await LoginAsync(AppUser, AppPassword); return relult; } public async Task LoginAsync(string userId,string password) { using (var httpClientHandler = new HttpClientHandler()) { using (var httpClient = new HttpClient(httpClientHandler)) { httpClient.BaseAddress = new Uri(_appBaseAddress); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型 var url = "api/identity/users/login"; var loginUser = new LoginInputDto() { UserName = userId, Password = password }; var sendData = JsonConvert.SerializeObject(loginUser); using (HttpContent httpContent = new StringContent(sendData)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await httpClient.PostAsync(url, httpContent); string result; if (!response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result); } result = await response.Content.ReadAsStringAsync(); var restultDto = JsonConvert.DeserializeObject(result); if (restultDto == null) { throw new Exception("返回结果是空"); } if (restultDto.Code != "1") { throw new Exception($"登录失败{restultDto.Message}"); } _accesToken = restultDto.Data.access_token; return restultDto; } } } } } }