打印服务及相关单元测试

master
ZR20090193-陈敬勇 8 months ago
parent 16950d3a59
commit 3342953e2c

@ -0,0 +1,267 @@
using DS.Module.Core.Extensions;
using DS.Module.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.TCBGetPressureTestReportResponse.Types;
using static System.Net.Mime.MediaTypeNames;
namespace DS.Module.PrintModule
{
/// <summary>
/// 打印服务封装请求工具类
/// </summary>
public class HttpUtillib
{
/// <summary>
/// 平台ip
/// </summary>
private static string _ip;
/// <summary>
/// 平台端口
/// </summary>
private static int _port = 443;
/// <summary>
/// 平台APPKey
/// </summary>
private static string _appkey;
/// <summary>
/// 平台APPSecret
/// </summary>
private static string _secret;
/// <summary>
/// 是否使用HTTPS协议
/// </summary>
private static bool _isHttps = true;
/// <summary>
/// 设置信息参数
/// </summary>
/// <param name="appkey">合作方APPKey</param>
/// <param name="secret">合作方APPSecret</param>
/// <param name="ip">平台IP</param>
/// <param name="port">平台端口默认HTTPS的443端口</param>
/// <param name="isHttps">是否启用HTTPS协议默认HTTPS</param>
/// <return></return>
public static void SetPlatformInfo(string appkey, string secret, string ip, int port = 443, bool isHttps = true)
{
_appkey = appkey;
_secret = secret;
_ip = ip;
_port = port;
_isHttps = isHttps;
// 设置并发数如不设置默认为2
ServicePointManager.DefaultConnectionLimit = 512;
}
/// <summary>
/// HTTP GET请求
/// </summary>
/// <param name="uri">HTTP接口Url不带协议和端口如/artemis/api/resource/v1/cameras/indexCode?cameraIndexCode=a10cafaa777c49a5af92c165c95970e0</param>
/// <param name="timeout">请求超时时间,单位:秒</param>
/// <returns></returns>
public static string HttpGet(string uri, int timeout)
{
Dictionary<string, string> header = new Dictionary<string, string>();
// 初始化请求:组装请求头,设置远程证书自动验证通过
initRequest(header, uri, "", false);
// build web request object
StringBuilder sb = new StringBuilder();
sb.Append(_isHttps ? "https://" : "http://").Append(_ip).Append(":").Append(_port.ToString()).Append(uri);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sb.ToString());
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version11;
req.AllowAutoRedirect = false; // 不允许自动重定向
req.Method = "GET";
req.Timeout = timeout * 1000; // 传入是秒,需要转换成毫秒
req.Accept = header["Accept"];
req.ContentType = header["Content-Type"];
foreach (string headerKey in header.Keys)
{
if (headerKey.Contains("appId"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
if (headerKey.Contains("timestamp"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
if (headerKey.Contains("sign"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
}
HttpWebResponse rsp = null;
try
{
rsp = (HttpWebResponse)req.GetResponse();
if (HttpStatusCode.OK == rsp.StatusCode)
{
Stream rspStream = rsp.GetResponseStream(); // 响应内容字节流
StreamReader sr = new StreamReader(rspStream);
string strStream = sr.ReadToEnd();
long streamLength = strStream.Length;
byte[] response = System.Text.Encoding.UTF8.GetBytes(strStream);
rsp.Close();
return System.Text.Encoding.UTF8.GetString(response);
}
else if (HttpStatusCode.Found == rsp.StatusCode || HttpStatusCode.Moved == rsp.StatusCode) // 302/301 redirect
{
string reqUrl = rsp.Headers["Location"].ToString(); // 获取重定向URL
WebRequest wreq = WebRequest.Create(reqUrl); // 重定向请求对象
WebResponse wrsp = wreq.GetResponse(); // 重定向响应
long streamLength = wrsp.ContentLength; // 重定向响应内容长度
Stream rspStream = wrsp.GetResponseStream(); // 响应内容字节流
byte[] response = new byte[streamLength];
rspStream.Read(response, 0, (int)streamLength); // 读取响应内容至byte数组
rspStream.Close();
rsp.Close();
return System.Text.Encoding.UTF8.GetString(response);
}
rsp.Close();
}
catch (WebException e)
{
if (rsp != null)
{
rsp.Close();
}
}
return null;
}
/// <summary>
/// HTTP Post请求
/// </summary>
/// <param name="uri">HTTP接口Url不带协议和端口如/artemis/api/resource/v1/org/advance/orgList</param>
/// <param name="body">请求参数</param>
/// <param name="timeout">请求超时时间,单位:秒</param>
/// <return>请求结果</return>
public static string HttpPost(string uri, string body, int timeout)
{
Dictionary<string, string> header = new Dictionary<string, string>();
// 初始化请求:组装请求头,设置远程证书自动验证通过
initRequest(header, uri, body, true);
// build web request object
StringBuilder sb = new StringBuilder();
sb.Append(_isHttps ? "https://" : "http://").Append(_ip).Append(":").Append(_port.ToString()).Append(uri);
// 创建POST请求
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sb.ToString());
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version11;
req.AllowAutoRedirect = false; // 不允许自动重定向
req.Method = "POST";
req.Timeout = timeout * 1000; // 传入是秒,需要转换成毫秒
req.Accept = header["Accept"];
req.ContentType = header["Content-Type"];
req.UserAgent = "PostmanRuntime/7.26.8";
foreach (string headerKey in header.Keys)
{
if (headerKey.Contains("appId"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
if (headerKey.Contains("timestamp"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
if (headerKey.Contains("sign"))
{
req.Headers.Add(headerKey + ":" + header[headerKey]);
}
}
byte[] data = Encoding.UTF8.GetBytes(body);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
Encoding encode = Encoding.UTF8;
StreamReader reader = new StreamReader(stream, encode);
string content = reader.ReadToEnd();
stream.Close();
reader.Close();
return content;
}
/// <summary>
/// 远程证书验证
/// </summary>
/// <param name="sender"></param>
/// <param name="cert"></param>
/// <param name="chain"></param>
/// <param name="error"></param>
/// <returns>验证是否通过,始终通过</returns>
private static bool remoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain,
SslPolicyErrors error)
{
return true;
}
private static void initRequest(Dictionary<string, string> header, string url, string body, bool isPost)
{
// Accept
// string accept = "application/json"; // "*/*";
string accept = "*/*"; // "*/*";
header.Add("Accept", accept);
// ContentType
string contentType = "application/json";
header.Add("Content-Type", contentType);
// appId
header.Add("appId", _appkey);
var timestamp = DateTime.Now.DateToTimeStamp();
// build string to sign
string signedStr = MD5Helper.Md5EncryptLowerCase(timestamp + _secret);
// timestamp
header.Add("timestamp", DateTime.Now.DateToTimeStamp());
// sign
header.Add("sign", signedStr);
if (_isHttps)
{
// set remote certificate Validation auto pass
ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(remoteCertificateValidate);
// FIX修复不同.Net版对一些SecurityProtocolType枚举支持情况不一致导致编译失败等问题这里统一使用数值
// ServicePointManager.SecurityProtocol = (SecurityProtocolType)48 | (SecurityProtocolType)3072 |
// (SecurityProtocolType)768 | (SecurityProtocolType)192 ;
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
}
}
}
}

@ -1,4 +1,5 @@
using System;
using DS.Module.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -8,5 +9,23 @@ namespace DS.Module.PrintModule
{
public interface IPrintService
{
/// <summary>
/// 获取打印模块列表
/// </summary>
/// <returns></returns>
public DataResult GetOpenPrintModuleList();
/// <summary>
/// 获取打印模板列表
/// </summary>
/// <returns></returns>
public DataResult GetOpenPrintTemplateList(string id);
/// <summary>
/// 获取Json打印信息
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public DataResult GetOpenJsonPrintInfo(OpenJsonPrintReq req);
}
}

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DS.Module.PrintModule
{
/// <summary>
/// Json打印请求数据
/// </summary>
public class OpenJsonPrintReq
{
/// <summary>
/// 模板Id
/// </summary>
public long TemplateId { get; set; }
/// <summary>
/// Json数据
/// </summary>
public string JsonDataStr { get; set; }
}
}

@ -1,6 +1,9 @@
using DS.Module.Core;
using DS.Module.Core.Data;
using DS.Module.Core.Extensions;
using DS.Module.UserModule;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using NLog;
using SqlSugar;
using System;
@ -16,8 +19,13 @@ namespace DS.Module.PrintModule
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly string accessKeyId;
private readonly string ip;
private readonly int port;
private readonly string accessKey;
private readonly string accessSecret;
private readonly string moduleUrl;
private readonly string templateUrl;
private readonly string jsonPrintInfoUrl;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
/// <summary>
@ -30,8 +38,96 @@ namespace DS.Module.PrintModule
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
accessKeyId = AppSetting.app(new string[] { "AliSMS", "AccessKeyId" });
accessSecret = AppSetting.app(new string[] { "AliSMS", "AccessKeySecret" });
ip = AppSetting.app(new string[] { "PrintService", "IP" }).ObjToString();
port = AppSetting.app(new string[] { "PrintService", "Port" }).ToInt();
accessKey = AppSetting.app(new string[] { "PrintService", "AccessKey" }).ObjToString();
accessSecret = AppSetting.app(new string[] { "PrintService", "AccessSecret" }).ObjToString();
moduleUrl = AppSetting.app(new string[] { "PrintService", "GetModuleListUrl" }).ObjToString();
templateUrl = AppSetting.app(new string[] { "PrintService", "GetTemplateListUrl" }).ObjToString();
jsonPrintInfoUrl = AppSetting.app(new string[] { "PrintService", "GetJsonPrintInfoUrl" }).ObjToString();
}
/// <summary>
/// 获取打印模块列表
/// </summary>
/// <returns></returns>
public DataResult GetOpenPrintModuleList()
{
// 只要平台信息参数一致,多个请求只需设置一次参数
HttpUtillib.SetPlatformInfo(accessKey, accessSecret, ip, port, false);
DataResult res = new DataResult();
// 发起POST请求超时时间15秒返回响应字节数组
string result = HttpUtillib.HttpGet(moduleUrl, 15);
if (null == result)
{
res = DataResult.Failed("请求失败,请联系管理员");
// 请求失败
// Console.WriteLine("/artemis/api/resource/v1/cameras/indexCode: POST fail");
}
else
{
res = JsonConvert.DeserializeObject<DataResult>(result);
// Console.WriteLine(System.Text.Encoding.UTF8.GetString(result));
}
return res;
}
/// <summary>
/// 获取打印模板列表
/// </summary>
/// <param name="id">模块id</param>
/// <returns></returns>
public DataResult GetOpenPrintTemplateList(string id)
{
// 只要平台信息参数一致,多个请求只需设置一次参数
HttpUtillib.SetPlatformInfo(accessKey, accessSecret, ip, port, false);
DataResult res = new DataResult();
// 发起POST请求超时时间15秒返回响应字节数组
string result = HttpUtillib.HttpGet(templateUrl+"?id=" + id, 15);
if (null == result)
{
res = DataResult.Failed("请求失败,请联系管理员");
// 请求失败
// Console.WriteLine("/artemis/api/resource/v1/cameras/indexCode: POST fail");
}
else
{
res = JsonConvert.DeserializeObject<DataResult>(result);
// Console.WriteLine(System.Text.Encoding.UTF8.GetString(result));
}
return res;
}
/// <summary>
/// 获取Json打印信息
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public DataResult GetOpenJsonPrintInfo(OpenJsonPrintReq req)
{
// 只要平台信息参数一致,多个请求只需设置一次参数
HttpUtillib.SetPlatformInfo(accessKey, accessSecret, ip, port, false);
DataResult res = new DataResult();
// 发起POST请求超时时间15秒返回响应字节数组
string result = HttpUtillib.HttpPost(jsonPrintInfoUrl, JsonConvert.SerializeObject(req), 30);
if (null == result)
{
res = DataResult.Failed("请求失败,请联系管理员");
// 请求失败
// Console.WriteLine("/artemis/api/resource/v1/cameras/indexCode: POST fail");
}
else
{
res = JsonConvert.DeserializeObject<DataResult>(result);
// Console.WriteLine(System.Text.Encoding.UTF8.GetString(result));
}
return res;
}
}
}

@ -48,5 +48,14 @@
"BasePath": "", //使
"RelativePath": "LinkAttach",
"FileType": [ ".xls", ".xlsx", ".pdf", ".txt", ".pms" ]
},
"PrintService": {
"IP": "60.209.125.238",
"Port": "3009",
"AccessKey": "1777229107311022080",
"AccessSecret": "d816e6fe938f24e2f205db129d31286a",
"GetModuleListUrl": "/printApi/OpenPrint/GetPrintModuleList",
"GetTemplateListUrl": "/printApi/OpenPrint/GetPrintTemplateList",
"GetJsonPrintInfoUrl": "/printApi/OpenPrint/GetOpenJsonPrintInfo"
}
}

@ -11,8 +11,8 @@
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0"/>
<PackageReference Include="xunit" Version="2.4.2"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="Xunit.DependencyInjection" Version="8.9.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@ -27,6 +27,7 @@
<ItemGroup>
<ProjectReference Include="..\DS.Module.AutofacModule\DS.Module.AutofacModule.csproj" />
<ProjectReference Include="..\DS.Module.Core\DS.Module.Core.csproj" />
<ProjectReference Include="..\DS.Module.PrintModule\DS.Module.PrintModule.csproj" />
<ProjectReference Include="..\DS.WMS.Core\DS.WMS.Core.csproj" />
</ItemGroup>

@ -17,17 +17,17 @@ public class OpTest
private readonly IServiceProvider _serviceProvider;
private readonly SqlSugarScope db;
private readonly ISaasDbService saasService;
private readonly IFormSetService _formSetService;
private readonly IClientCommonService _formSetService;
public OpTest(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = (SqlSugarScope)_serviceProvider.GetRequiredService<ISqlSugarClient>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
_formSetService = _serviceProvider.GetRequiredService<IFormSetService>();
_formSetService = _serviceProvider.GetRequiredService<IClientCommonService>();
}
[Fact]
public async void SaasTest1()
public async void OpTest1()
{
//var tenantDb = saasService.GetBizDbScopeById("1750335377144680448");

@ -0,0 +1,65 @@
using System.Reflection;
using DS.Module.Core;
using DS.Module.Core.Extensions;
using DS.Module.PrintModule;
using DS.Module.SqlSugar;
using DS.WMS.Core.Code.Interface;
using DS.WMS.Core.System.Entity;
using DS.WMS.Core.System.Interface;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.IOC;
using Xunit;
namespace Ds.WMS.Test;
public class PrintTest
{
private readonly IServiceProvider _serviceProvider;
private readonly SqlSugarScope db;
private readonly ISaasDbService saasService;
private readonly IPrintService _printService;
public PrintTest(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = (SqlSugarScope)_serviceProvider.GetRequiredService<ISqlSugarClient>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
_printService = _serviceProvider.GetRequiredService<IPrintService>();
}
/// <summary>
/// 获取打印模块列表
/// </summary>
[Fact]
public void GetOpenPrintModuleList()
{
var data = _printService.GetOpenPrintModuleList();
Assert.True(data.Succeeded);
}
/// <summary>
/// 获取打印模板列表
/// </summary>
[Fact]
public void GetOpenPrintTemplateList()
{
var data = _printService.GetOpenPrintTemplateList("1777229219986804736");
Assert.True(data.Succeeded);
}
/// <summary>
/// 获取Json打印信息
/// </summary>
[Fact]
public void GetOpenJsonPrintInfo()
{
var req = new OpenJsonPrintReq()
{
TemplateId = 1777232318486941696,
JsonDataStr = "{\"GID\":\"52fc4ecf-5c88-49a8-aa1f-08da84ccc2d3\",\"BILLTYPE\":false,\"TRUCKNO\":\"鲁A789\",\"BoxWeigth\":10540,\"BoxCode\":\"A124\",\"BoxCode2\":null,\"ISTwoBox\":false,\"CORPID\":null,\"CreateDate\":\"2023-12-22T09:55:43.0332931+08:00\",\"CreateID\":null,\"Creator\":null,\"TURNOVERDATE\":\"2023-12-22T09:55:43.0333166+08:00\",\"Modifier\":null,\"ModifyDate\":null,\"ModifyID\":null,\"REMARK\":null}"
};
var data = _printService.GetOpenJsonPrintInfo(req);
Assert.True(data.Succeeded);
}
}

@ -1,6 +1,7 @@
using Autofac;
using Autofac.Extensions.DependencyInjection;
using DS.Module.AutofacModule;
using DS.Module.PrintModule;
using DS.Module.SqlSugar;
using DS.Module.UserModule;
using Microsoft.Extensions.DependencyInjection;
@ -52,6 +53,7 @@ public class Startup
services.AddUserModuleInstall(); //用户服务
services.AddSqlSugarInstall();
services.AddSaasDbInstall();
services.AddPrintModuleInstall();
}
/// <summary>

@ -1,42 +1,51 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JwtSettings": {
"Issuer": "vol.core.owner",
"Audience": "vol.core",
"User": "C5ABA9E202D94C43A3CA66002BF77FAF",
"SecretKey": "sdfsdfsrty45634kkhllghtdgdfss345t678fs"
},
"Cors": {
"PolicyName": "WMSCore.API",
"Url": "http://localhost:8000,http://localhost:5999,http://localhost:8088,http://localhost:5173,http://0.0.0.0:5999,http://0.0.0.0:9995,http://localhost:9995,http://60.209.125.238:9995,http://localhost:3000,https://localhost:3100,http://47.104.255.182:3100,http://47.104.255.182:3110,https://localhost:3110,http://localhost:8080,http://localhost:8081,http://localhost:8082,http://localhost:8083,http://localhost:8084"
},
"DBInfo": {
"DefaultDbConnId": "1288018625843826688",
"DefaultDbType": 0,
"DefaultDbString": "server=60.209.125.238;port=32006;uid=root;pwd=Djy@Mysql.test;database=shippingweb8_dev",
"DBS": [
{
"ConnId": "1595354960864874496",
"DBType": 1,
"Enabled": false,
"HitRate": 40,
"Connection": "Data Source=47.105.193.36,11435;Initial Catalog=SHIPPINGWEB_JNHJ;Integrated Security=False;Connect Timeout=500;User ID=sa;Password=Ds20040201",
"ProviderName": "System.Data.SqlClient"
}
]
},
"SwaggerDoc": {
"ContactName": "WmsAdminAPI",
"ContactEmail": "Wms API.Core@xxx.com",
"ContactUrl": "https://www.xxx.com",
"Version": "1.0",
"Title": "Wms Admin API",
"Description": "Wms Admin API"
},
"PrintService": {
"IP": "60.209.125.238",
"Port": "3009",
"AccessKey": "1777229107311022080",
"AccessSecret": "d816e6fe938f24e2f205db129d31286a",
"GetModuleListUrl": "/printApi/OpenPrint/GetPrintModuleList",
"GetTemplateListUrl": "/printApi/OpenPrint/GetPrintTemplateList",
"GetJsonPrintInfoUrl": "/printApi/OpenPrint/GetOpenJsonPrintInfo"
}
},
"AllowedHosts": "*",
"JwtSettings": {
"Issuer": "vol.core.owner",
"Audience": "vol.core",
"User": "C5ABA9E202D94C43A3CA66002BF77FAF",
"SecretKey": "sdfsdfsrty45634kkhllghtdgdfss345t678fs"
},
"Cors": {
"PolicyName": "WMSCore.API",
"Url": "http://localhost:8000,http://localhost:5999,http://localhost:8088,http://localhost:5173,http://0.0.0.0:5999,http://0.0.0.0:9995,http://localhost:9995,http://60.209.125.238:9995,http://localhost:3000,https://localhost:3100,http://47.104.255.182:3100,http://47.104.255.182:3110,https://localhost:3110,http://localhost:8080,http://localhost:8081,http://localhost:8082,http://localhost:8083,http://localhost:8084"
},
"DBInfo": {
"DefaultDbConnId": "1288018625843826688",
"DefaultDbType": 0,
"DefaultDbString": "server=60.209.125.238;port=32006;uid=root;pwd=Djy@Mysql.test;database=shippingweb8_dev",
"DBS": [
{
"ConnId": "1595354960864874496",
"DBType": 1,
"Enabled": false,
"HitRate": 40,
"Connection": "Data Source=47.105.193.36,11435;Initial Catalog=SHIPPINGWEB_JNHJ;Integrated Security=False;Connect Timeout=500;User ID=sa;Password=Ds20040201",
"ProviderName": "System.Data.SqlClient"
}
]
},
"SwaggerDoc": {
"ContactName": "WmsAdminAPI",
"ContactEmail": "Wms API.Core@xxx.com",
"ContactUrl": "https://www.xxx.com",
"Version": "1.0",
"Title": "Wms Admin API",
"Description": "Wms Admin API"
}
}
Loading…
Cancel
Save