Explorar o código

重构代码以改进异步处理和空值处理

注释掉多个不再使用的变量和方法,包括布尔变量、静态字符串常量、日志记录代码以及 `VisaFeeInfoRepository` 中的更新逻辑。将 `ReTransBatch`、`TransSync`、`SaveBinaryFile` 和 `GetBeijingTime` 方法改为异步方法,并使用 `HttpClient` 进行 HTTP 请求。改进了 `ComputeHash` 方法中的哈希计算,使用 `SHA256.Create()` 替代 `SHA256CryptoServiceProvider`。在 `groupData.Data` 属性的获取值转换为 `int` 类型时,添加了空值处理。将时间戳转换为 `DateTime` 时,改用 `DateTime.MinValue`。在 `SystemController.cs` 中,将返回的错误信息中的 `null` 改为 `string.Empty`。删除了一个异常处理中的 `throw` 语句。
LEIYI hai 3 meses
pai
achega
3fe2c461b5

+ 30 - 17
OASystem/OASystem.Api/Controllers/GroupsController.cs

@@ -2281,7 +2281,7 @@ FROM
                                 string roomFeeStr = "", roomFeestr1 = "";
 
                                 //是否比较房型价格
-                                bool __isSingle = false, __isDouble = false, __isSuite = false, __isOther = false;
+                                //bool __isSingle = false, __isDouble = false, __isSuite = false, __isOther = false;
 
                                 //roomFeeStr += $"<br/><span style='width:70px;display: inline-block;'></span>";
                                 roomFeeStr += $"<br/>";
@@ -2290,28 +2290,28 @@ FROM
                                 {
                                     var fee = hotelReservations.SingleRoomPrice * hotelReservations.SingleRoomCount * (int)hotel_days;
                                     roomFeestr1 += $"<span style='width:70px;display: inline-block;'></span>单间:{hotelReservations.SingleRoomPrice.ToString("#0.00")} * {hotelReservations.SingleRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}<br/>";
-                                    __isSingle = true;
+                                    //__isSingle = true;
                                     roomTotal += fee;
                                 }
                                 if (hotelReservations.DoubleRoomPrice > 0)
                                 {
                                     var fee = hotelReservations.DoubleRoomPrice * hotelReservations.DoubleRoomCount * (int)hotel_days;
                                     roomFeestr1 += $"<span style='width:70px;display: inline-block;'></span>双人间:{hotelReservations.DoubleRoomPrice.ToString("#0.00")} * {hotelReservations.DoubleRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}<br/>";
-                                    __isDouble = true;
+                                   // __isDouble = true;
                                     roomTotal += fee;
                                 }
                                 if (hotelReservations.SuiteRoomPrice > 0)
                                 {
                                     var fee = hotelReservations.SuiteRoomPrice * hotelReservations.SuiteRoomCount * (int)hotel_days;
                                     roomFeestr1 += $"<span style='width:70px;display: inline-block;'></span>套房:{hotelReservations.SuiteRoomPrice.ToString("#0.00")} * {hotelReservations.SuiteRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}<br/>";
-                                    __isSuite = true;
+                                    //__isSuite = true;
                                     roomTotal += fee;
                                 }
                                 if (hotelReservations.OtherRoomPrice > 0)
                                 {
                                     var fee = hotelReservations.OtherRoomPrice * hotelReservations.OtherRoomCount * (int)hotel_days;
                                     roomFeestr1 += $"<span style='width:70px;display: inline-block;'></span>其他:{hotelReservations.OtherRoomPrice.ToString("#0.00")} * {hotelReservations.OtherRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}<br/>";
-                                    __isOther = true;
+                                    //__isOther = true;
                                     roomTotal += fee;
                                 }
 
@@ -3649,7 +3649,7 @@ FROM
                                 }
                             }
                         }
-                        List<TranslateResult> transData = _airTicketResRep.ReTransBatch(texts, "en");
+                        List<TranslateResult> transData = await _airTicketResRep.ReTransBatch(texts, "en");
                         if (transData.Count > 0)
                         {
                             foreach (TranslateResult item in transData)
@@ -3973,9 +3973,13 @@ FROM
             }
 
             #region 应用推送
-            int otherId = (int)groupData.Data.GetType().GetProperty("dataId").GetValue(groupData.Data, null);
-            int ccpId = (int)groupData.Data.GetType().GetProperty("ccpId").GetValue(groupData.Data, null);
-            int sign = (int)groupData.Data.GetType().GetProperty("sign").GetValue(groupData.Data, null);
+            //int otherId = (int)groupData.Data.GetType().GetProperty("dataId").GetValue(groupData.Data, null);
+            //int ccpId = (int)groupData.Data.GetType().GetProperty("ccpId").GetValue(groupData.Data, null);
+            //int sign = (int)groupData.Data.GetType().GetProperty("sign").GetValue(groupData.Data, null);
+
+            int otherId = Convert.ToInt32(groupData.Data.GetType().GetProperty("dataId").GetValue(groupData.Data, null) ?? 0);
+            int ccpId = Convert.ToInt32(groupData.Data.GetType().GetProperty("ccpId").GetValue(groupData.Data, null) ?? 0);
+            int sign = Convert.ToInt32(groupData.Data.GetType().GetProperty("sign").GetValue(groupData.Data, null) ?? 0);
 
             //自动审核
             var autoAdit = await _feeAuditRep.FeeAutomaticAudit(3, dto.DiId, otherId);
@@ -5203,7 +5207,7 @@ FROM
                             texts.Add(item.CompanyFullName);
                         }
                     }
-                    List<TranslateResult> transData = _airTicketResRep.ReTransBatch(texts, "en");
+                    List<TranslateResult> transData = await _airTicketResRep.ReTransBatch(texts, "en");
                     if (transData.Count > 0)
                     {
                         foreach (TranslateResult item in transData)
@@ -7358,7 +7362,7 @@ FROM
             foreach (var item in countryData)
             {
                 var cityData1 = new List<string>();
-                cityData1 = nationalTravelFeeData.Where(it => it.Country == item).Select(it => it.City).ToList();
+                cityData1 = nationalTravelFeeData.Where(it => it.Country == item).Select(it => it.City ?? "").ToList();
                 var countryData2 = new
                 {
                     CountryName = item,
@@ -16001,10 +16005,14 @@ ORDER by  gctggrc.id DESC
 
             try
             {
+                //int ccpId = (int)_view.Data.GetType().GetProperty("ccpId").GetValue(_view.Data, null);
+                //int sign = (int)_view.Data.GetType().GetProperty("sign").GetValue(_view.Data, null);
+                //int hotelId = (int)_view.Data.GetType().GetProperty("hotelId").GetValue(_view.Data, null);
+
+                int ccpId = Convert.ToInt32(_view.Data.GetType().GetProperty("ccpId").GetValue(_view.Data, null) ?? 0);
+                int sign = Convert.ToInt32(_view.Data.GetType().GetProperty("sign").GetValue(_view.Data, null) ?? 0);
+                int hotelId = Convert.ToInt32(_view.Data.GetType().GetProperty("hotelId").GetValue(_view.Data, null) ?? 0);
 
-                int ccpId = (int)_view.Data.GetType().GetProperty("ccpId").GetValue(_view.Data, null);
-                int sign = (int)_view.Data.GetType().GetProperty("sign").GetValue(_view.Data, null);
-                int hotelId = (int)_view.Data.GetType().GetProperty("hotelId").GetValue(_view.Data, null);
 
                 var diId = _dto.DiId;
                 var groupInfo = await _groupRepository.Query(x => x.Id == diId).FirstAsync();
@@ -16069,9 +16077,14 @@ ORDER by  gctggrc.id DESC
 
             try
             {
-                int ccpId = (int)_view.Data.GetType().GetProperty("ccpId").GetValue(_view.Data, null);
-                int sign = (int)_view.Data.GetType().GetProperty("sign").GetValue(_view.Data, null);
-                int hotelId = (int)_view.Data.GetType().GetProperty("hotelId").GetValue(_view.Data, null);
+                //int ccpId = (int)_view.Data.GetType().GetProperty("ccpId").GetValue(_view.Data, null);
+                //int sign = (int)_view.Data.GetType().GetProperty("sign").GetValue(_view.Data, null);
+                //int hotelId = (int)_view.Data.GetType().GetProperty("hotelId").GetValue(_view.Data, null);
+
+                int ccpId = Convert.ToInt32(_view.Data.GetType().GetProperty("ccpId").GetValue(_view.Data, null) ?? 0);
+                int sign = Convert.ToInt32(_view.Data.GetType().GetProperty("sign").GetValue(_view.Data, null) ?? 0);
+                int hotelId = Convert.ToInt32(_view.Data.GetType().GetProperty("hotelId").GetValue(_view.Data, null) ?? 0);
+
                 await AppNoticeLibrary.SendChatMsg_GroupStatus_ApplyFee(ccpId, sign, QiyeWeChatEnum.GuoJiaoLeaderChat);
 
                 //自动审核

+ 1 - 4
OASystem/OASystem.Api/Controllers/SystemController.cs

@@ -880,7 +880,7 @@ namespace OASystem.API.Controllers
             {
                 if (dto.Id == 0)
                 {
-                    return Ok(JsonView(-1, "请检查信息是否输入完整!", null));
+                    return Ok(JsonView(-1, "请检查信息是否输入完整!", string.Empty));
                 }
                 else
                 {
@@ -895,10 +895,7 @@ namespace OASystem.API.Controllers
             catch (Exception)
             {
                 return Ok(JsonView(false, "程序错误!"));
-                throw;
             }
-
-
         }
         #endregion
 

+ 11 - 13
OASystem/OASystem.Api/OAMethodLib/PayrollComputation.cs

@@ -60,7 +60,7 @@ namespace OASystem.API.OAMethodLib
 
 
             List<string> qyWhchatIdList = new List<string>();
-            qyWhchatIdList = userIdListView.dept_user.Select(it => it.userid).ToList();
+            qyWhchatIdList = userIdListView.dept_user.Select(it => it.userid ?? "").ToList();
             CheckInDayDataView checkInDayDataView = await _qiYeWeChatApiService.GetCheckInDayDataAsync(qyWhchatIdList, startDt, endDt);
             if (checkInDayDataView.errcode != 0)
             {
@@ -313,7 +313,8 @@ namespace OASystem.API.OAMethodLib
                                 long earliest_time = root.summary_info.earliest_time; //最早打卡时间
                                 long lastest_time = root.summary_info.lastest_time; //最晚打卡时间
                                 long this_date = date + earliest_time;
-                                DateTime thisDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks(this_date * 10000000);
+                                //DateTime thisDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks(this_date * 10000000);
+                                DateTime thisDt = DateTime.MinValue.AddTicks(this_date * 10000000);
 
                                 string thisDtStr = thisDt.ToString("yyyy-MM-dd");
 
@@ -336,8 +337,8 @@ namespace OASystem.API.OAMethodLib
                                         beLate_belate_ex.SubTypeId = 1;
                                         beLate_belate_ex.SubType = "迟到";
 
-                                        string thisStartDt = (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + earliest_time) * 10000000))
-                                                              .ToString("yyyy-MM-dd HH:mm:ss");
+                                        //string thisStartDt = (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + earliest_time) * 10000000)).ToString("yyyy-MM-dd HH:mm:ss");
+                                        string thisStartDt = DateTime.MinValue.AddTicks((date + earliest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                         beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisStartDt);
 
                                         if (user_cd_zt_num >= 3)
@@ -352,9 +353,8 @@ namespace OASystem.API.OAMethodLib
                                     }
                                     else if (timelength >= 10 && timelength < 60)
                                     {
-                                        string thisStartDt = (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))
-                                                             .AddTicks((date + earliest_time) * 10000000))
-                                                             .ToString("yyyy-MM-dd HH:mm:ss");
+                                        //string thisStartDt = (TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + earliest_time) * 10000000)).ToString("yyyy-MM-dd HH:mm:ss");
+                                        string thisStartDt = DateTime.MinValue.AddTicks((date + earliest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                         beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisStartDt);
 
                                         day_deduction = 50.00M;
@@ -387,9 +387,8 @@ namespace OASystem.API.OAMethodLib
                                         user_cd_zt_num++;
                                         beLate_belate_ex.SubTypeId = 2;
                                         beLate_belate_ex.SubType = "早退";
-                                        string thisEndDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))
-                                                           .AddTicks((date + lastest_time) * 10000000)
-                                                           .ToString("yyyy-MM-dd HH:mm:ss");
+                                        //string thisEndDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
+                                        string thisEndDt = DateTime.MinValue.AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                         beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisEndDt);
 
                                         if (user_cd_zt_num >= 3)
@@ -408,9 +407,8 @@ namespace OASystem.API.OAMethodLib
                                         early_deduction += day_deduction;  //早退扣款 总计
                                         beLate_belate_ex.SubTypeId = 2;
                                         beLate_belate_ex.SubType = "早退";
-                                        string thisEndDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))
-                                                           .AddTicks((date + lastest_time) * 10000000)
-                                                           .ToString("yyyy-MM-dd HH:mm:ss");
+                                        //string thisEndDt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
+                                        string thisEndDt = DateTime.MinValue.AddTicks((date + lastest_time) * 10000000).ToString("yyyy-MM-dd HH:mm:ss");
                                         beLate_belate_ex.StartTimeDt = Convert.ToDateTime(thisEndDt);
                                     }
                                     else if (timelength >= 60 && timelength <= 180)

+ 7 - 7
OASystem/OASystem.Api/OAMethodLib/QiYeWeChatAPI/QiYeWeChatApiService.cs

@@ -12,17 +12,17 @@ namespace OASystem.API.OAMethodLib.QiYeWeChatAPI
     public class QiYeWeChatApiService : IQiYeWeChatApiService
     {
         private readonly HttpClient _httpClient;
-        private readonly string CorpId = "wwe978bef5495a0728";   //企业Id
-        private readonly string PersonnelAssistant_AgentId = "3010011";   //人事助手Id
+        //private readonly string CorpId = "wwe978bef5495a0728";   //企业Id
+        //private readonly string PersonnelAssistant_AgentId = "3010011";   //人事助手Id
+        //private readonly string PunchCard_AgentId = "3010185";            //打卡Id
+        //private readonly string Email_AgentId = "1000004";   //E-Mail Id
+        //private readonly string Approve_AgentId = "3010040";     //审批 Id
+        //private readonly string GroupStatus_AgentId = "1000008"; //OA通知 Id
         private readonly string PersonnelAssistant_Corpsecret = "ig--IJd6TxWDMJ1wT4e-RDRcRX12v5GjB359DNATwJ4"; //人事助手凭证密钥
-        private readonly string PunchCard_AgentId = "3010185";            //打卡Id
         private readonly string PunchCard_Corpsecret = "Xhrl37GOqlAjsu0VzUSJECaJdjzkDXQLbvrzRsZQb8M";          //打卡凭证密钥
-        private readonly string Email_AgentId = "1000004";   //E-Mail Id
         private readonly string Email_Corpsecret = "NA1zbJM15GmgjPYwDOqz59dIo1Wnug-MbU107MeUemc"; //E-Mail 凭证密钥
         private readonly string AddressBook_Corpsecret = "Y1tnjh7j-BvbqAytAoXZPUbmDR6dqLTL6mXtc6PZ7fo";  //通讯录同步 凭证密钥
-        private readonly string Approve_AgentId = "3010040";     //审批 Id
         private readonly string Approve_Corpsecret = "k_Jo69Jw9Hqg_in-Rypbs30PNbxOYa1t4e-dxYuT-kw";  //审批 凭证密钥
-        private readonly string GroupStatus_AgentId = "1000008"; //OA通知 Id
         private readonly string GroupStatus_Corpsecret = "7J_ST3jTPzbZpFwl7ttToTVufjEx6O2wuApvKHxt2Ak"; //OA通知Secret
 
         private readonly DateTime _1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
@@ -489,7 +489,7 @@ namespace OASystem.API.OAMethodLib.QiYeWeChatAPI
 
             Checkin_MonthData_Request checkInReq = new Checkin_MonthData_Request();
             checkInReq.access_token = access_Token.access_token;
-            checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid).ToList();
+            checkInReq.useridlist = userIdListView.dept_user.Select(it => it.userid ?? "").ToList();
 
             uint starttimeOne, endtimeOne, starttimeTwo, endtimeTwo;
             int days = (int)(endDt - startDt).TotalDays;

+ 4 - 4
OASystem/OASystem.Api/OAMethodLib/Quartz/Business/TaskNotification.cs

@@ -12,7 +12,7 @@ namespace OASystem.API.OAMethodLib.Quartz.Business
     public static class TaskNotification
     {
 
-        private readonly static ILogger _logger;
+        //private readonly static ILogger _logger;
         private readonly static TaskAllocationRepository _taskAllocationRep = AutofacIocManager.Instance.GetService<TaskAllocationRepository>();
         private readonly static IHubContext<ChatHub, IChatClient> _hubContext = AutofacIocManager.Instance.GetService<IHubContext<ChatHub, IChatClient>>();
 
@@ -103,7 +103,7 @@ namespace OASystem.API.OAMethodLib.Quartz.Business
                         if (msgAddId < 0)
                         {
                             newDB.RollbackTran();
-                            _logger.LogError("任务通知消息推送失败!");
+                            //_logger.LogError("任务通知消息推送失败!");
                             return;
                         }
 
@@ -122,7 +122,7 @@ namespace OASystem.API.OAMethodLib.Quartz.Business
                         if (msgAuthAddId < 0)
                         {
                             _taskAllocationRep._sqlSugar.RollbackTran();
-                            _logger.LogError("任务通知消息推送失败!");
+                           // _logger.LogError("任务通知消息推送失败!");
                             return;
                         }
                         userIds.Add(subItem.UserId);
@@ -132,7 +132,7 @@ namespace OASystem.API.OAMethodLib.Quartz.Business
                 //推送消息
                 await _hubContext.Clients.Clients(UserStore.OnlineUser.Where(it => userIds.Contains(it.UserId)).Select(it => it.ConnectionId).ToList()).ReceiveMessage("您有新的任务相关消息");
 
-                _logger.LogInformation("任务消息推送成功 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "【在线人数】:" + JsonConvert.SerializeObject(UserStore.OnlineUser));
+                //_logger.LogInformation("任务消息推送成功 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "【在线人数】:" + JsonConvert.SerializeObject(UserStore.OnlineUser));
             }
             #endregion
         }

+ 32 - 32
OASystem/OASystem.Api/OAMethodLib/YouDaoAPI/YouDaoApiTools.cs

@@ -106,11 +106,10 @@
         /// SHA256加密
         /// </summary>
         /// <param name="data"></param>
-        /// <returns></returns>
         public static string SHA256EncryptString(string data)
         {
             byte[] bytes = Encoding.UTF8.GetBytes(data);
-            byte[] hash = SHA256Managed.Create().ComputeHash(bytes);
+            byte[] hash = SHA256.Create().ComputeHash(bytes);
 
             StringBuilder builder = new StringBuilder();
             for (int i = 0; i < hash.Length; i++)
@@ -127,12 +126,13 @@
         /// <returns>加密数组</returns>
         public static Byte[] SHA256EncryptByte(string StrIn)
         {
-            var sha256 = new SHA256Managed();
-            var Asc = new ASCIIEncoding();
-            var tmpByte = Asc.GetBytes(StrIn);
-            var EncryptBytes = sha256.ComputeHash(tmpByte);
-            sha256.Clear();
-            return EncryptBytes;
+            using (var sha256 = SHA256.Create())
+            {
+                var Asc = new ASCIIEncoding();
+                var tmpByte = Asc.GetBytes(StrIn);
+                var EncryptBytes = sha256.ComputeHash(tmpByte);
+                return EncryptBytes;
+            }
         }
         #endregion
 
@@ -148,30 +148,30 @@
             return type ? Convert.ToInt64(ts.TotalSeconds) : Convert.ToInt64(ts.TotalMilliseconds);
         }
 
-        /// <summary>
-        /// 将当前时间戳转换至Datetime
-        /// </summary>
-        /// <param name="timeStamp"></param>
-        /// <returns></returns>
-        public static DateTime ConvertUTCToDateTime(long timeStamp)
-        {
-            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
-            DateTime dt = startTime.AddSeconds(timeStamp);
-            return dt;
-        }
-
-        /// <summary>
-        /// 把datetime转utc时间戳
-        /// </summary>
-        /// <param name="time"></param>
-        /// <returns></returns>
-        public static int ConvertDateTimeToUTC(DateTime time)
-        {
-            double intResult = 0;
-            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
-            intResult = (time - startTime).TotalSeconds;
-            return (int)intResult;
-        }
+        ///// <summary>
+        ///// 将当前时间戳转换至Datetime
+        ///// </summary>
+        ///// <param name="timeStamp"></param>
+        ///// <returns></returns>
+        //public static DateTime ConvertUTCToDateTime(long timeStamp)
+        //{
+        //    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
+        //    DateTime dt = startTime.AddSeconds(timeStamp);
+        //    return dt;
+        //}
+
+        ///// <summary>
+        ///// 把datetime转utc时间戳
+        ///// </summary>
+        ///// <param name="time"></param>
+        ///// <returns></returns>
+        //public static int ConvertDateTimeToUTC(DateTime time)
+        //{
+        //    double intResult = 0;
+        //    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
+        //    intResult = (time - startTime).TotalSeconds;
+        //    return (int)intResult;
+        //}
         #endregion
 
     }

+ 27 - 81
OASystem/OASystem.Infrastructure/Repositories/Groups/AirTicketResRepository.cs

@@ -927,7 +927,7 @@ namespace OASystem.Infrastructure.Repositories.Groups
             }
         }
 
-        public List<TranslateResult> ReTransBatch(List<string> list, string aimlanguage)
+        public async Task<List<TranslateResult>> ReTransBatch(List<string> list, string aimlanguage)
         {
 
             List<TranslateResult> reultStr = new List<TranslateResult>();
@@ -970,7 +970,7 @@ namespace OASystem.Infrastructure.Repositories.Groups
             string curtime = ((GetBeijingTime().ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
             dic.Add("curtime", curtime);
             string signStr = appKey + Truncate(q) + salt + curtime + appSecret; ;
-            string sign = ComputeHash(signStr, new SHA256CryptoServiceProvider());
+            string sign = ComputeHash(signStr, SHA256.Create());
 
 
             dic.Add("q", Qtext);
@@ -982,7 +982,7 @@ namespace OASystem.Infrastructure.Repositories.Groups
             try
             {
                 //Thread.Sleep(500);
-                jsonStr = TransSync(url, dic);
+                jsonStr = await TransSync(url, dic);
 
                 JObject trans = (JObject)JsonConvert.DeserializeObject(jsonStr);
                 string errorCode = trans["errorCode"].ToString();
@@ -1021,54 +1021,26 @@ namespace OASystem.Infrastructure.Repositories.Groups
             }
             return result;
         }
-        protected string TransSync(string url, Dictionary<string, string> dic)
+        protected async Task<string> TransSync(string url, Dictionary<string, string> dic)
         {
             string result = "";
-            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
-            req.Method = "POST";
-            req.ContentType = "application/x-www-form-urlencoded";
-
-            StringBuilder builder = new StringBuilder();
-            int i = 0;
-            foreach (var item in dic)
+            using (HttpClient client = new HttpClient())
             {
-                if (i > 0)
-                    builder.Append("&");
-                if (item.Key == "q")
+                var content = new FormUrlEncodedContent(dic);
+                HttpResponseMessage response = await client.PostAsync(url, content);
+                response.EnsureSuccessStatusCode();
+                if (response.Content.Headers.ContentType.MediaType.ToLower().Equals("audio/mp3"))
                 {
-                    builder.AppendFormat(item.Value);
+                    await SaveBinaryFile(response, "合成的音频存储路径");
                 }
                 else
                 {
-                    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();
-            }
-            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
-            if (resp.ContentType.ToLower().Equals("audio/mp3"))
-            {
-                SaveBinaryFile(resp, "合成的音频存储路径");
-            }
-            else
-            {
-                Stream stream = resp.GetResponseStream();
-                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
-                {
-                    result = reader.ReadToEnd();
+                    result = await response.Content.ReadAsStringAsync();
                 }
             }
             return result;
         }
-        private static bool SaveBinaryFile(WebResponse response, string FileName)
+        private static async Task<bool> SaveBinaryFile(HttpResponseMessage response, string FileName)
         {
             string FilePath = FileName + DateTime.Now.Millisecond.ToString() + ".mp3";
             bool Value = true;
@@ -1078,20 +1050,18 @@ namespace OASystem.Infrastructure.Repositories.Groups
             {
                 if (File.Exists(FilePath))
                     File.Delete(FilePath);
-                Stream outStream = File.Create(FilePath);
-                Stream inStream = response.GetResponseStream();
-
-                int l;
-                do
+                using (Stream outStream = File.Create(FilePath))
+                using (Stream inStream = await response.Content.ReadAsStreamAsync())
                 {
-                    l = inStream.Read(buffer, 0, buffer.Length);
-                    if (l > 0)
-                        outStream.Write(buffer, 0, l);
+                    int l;
+                    do
+                    {
+                        l = await inStream.ReadAsync(buffer, 0, buffer.Length);
+                        if (l > 0)
+                            await outStream.WriteAsync(buffer, 0, l);
+                    }
+                    while (l > 0);
                 }
-                while (l > 0);
-
-                outStream.Close();
-                inStream.Close();
             }
             catch
             {
@@ -1116,23 +1086,15 @@ namespace OASystem.Infrastructure.Repositories.Groups
         }
         public static DateTime GetBeijingTime()
         {
-            WebRequest request = null;
-            WebResponse response = null;
-            WebHeaderCollection headerCollection = null;
             string datetime = string.Empty;
             try
             {
-                request = WebRequest.Create("https://www.baidu.com");
-                request.Timeout = 3000;
-                request.Credentials = CredentialCache.DefaultCredentials;
-                response = request.GetResponse();
-                headerCollection = response.Headers;
-                foreach (var h in headerCollection.AllKeys)
+                using (HttpClient client = new HttpClient())
                 {
-                    if (h == "Date")
-                    {
-                        datetime = headerCollection[h];
-                    }
+                    client.Timeout = TimeSpan.FromSeconds(3);
+                    HttpResponseMessage response = client.GetAsync("https://www.baidu.com").Result;
+                    response.EnsureSuccessStatusCode();
+                    datetime = response.Headers.Date?.ToString() ?? DateTime.Now.ToString();
                 }
                 return Convert.ToDateTime(datetime);
             }
@@ -1140,22 +1102,6 @@ namespace OASystem.Infrastructure.Repositories.Groups
             {
                 return DateTime.Now;
             }
-            finally
-            {
-                if (request != null)
-                {
-                    request.Abort();
-                }
-                if (response != null)
-                {
-                    response.Close();
-                }
-                if (headerCollection != null)
-                {
-                    headerCollection.Clear();
-                }
-            }
-
         }
 
 

+ 5 - 5
OASystem/OASystem.Infrastructure/Repositories/Groups/VisaFeeInfoRepository.cs

@@ -180,7 +180,7 @@ namespace OASystem.Infrastructure.Repositories.Groups
             List<Grp_VisaFeeInfo> visaInfos = new List<Grp_VisaFeeInfo>();
 
             BeginTran();
-            bool visaFeeUpdate = false;
+            //bool visaFeeUpdate = false;
 
             var countrys = dto.VisaFeeInfos.GroupBy(x => x.Country);
 
@@ -226,10 +226,10 @@ namespace OASystem.Infrastructure.Repositories.Groups
                             LastUpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                         };
                         int update1 = _sqlSugar.Updateable(_CountryFeeCost).UpdateColumns(it => new { it.VisaPrice, it.LastUpdateTime }).WhereColumns(it => it.Id).ExecuteCommand();
-                        if (update1 > 0)
-                        {
-                            visaFeeUpdate = true;
-                        }
+                        //if (update1 > 0)
+                        //{
+                        //    visaFeeUpdate = true;
+                        //}
                     }
                 }