/// <summary> /// 写系统Log /// </summary> /// <param name="entity"></param> /// <returns></returns> public bool CreateApplicationEventLog(ApplicationEventLog entity) { return(ObjectFactory <ICommonDA> .Instance.CreateApplicationEventLog(entity)); }
/// <summary> /// 写系统Log /// </summary> /// <param name="entity"></param> /// <returns></returns> public bool CreateApplicationEventLog(ApplicationEventLog entity) { return(ObjectFactory <CommonDataAppService> .Instance.CreateApplicationEventLog(entity)); }
public void Interpret(Data d, SQLiteConnection conn) { if (d.Type != ECollectorType.Ping) { return; } if (d is ListData <PingResult> ) { ListData <PingResult> data = d as ListData <PingResult>; Dictionary <string, string> ip_to_name_map = new Dictionary <string, string>(); string sql = "SELECT IPAddress, Name FROM Devices WHERE DateDisabled IS NULL;"; using (SQLiteCommand command = new SQLiteCommand(sql, conn)) using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { if (reader.IsDBNull(0) == false) { ip_to_name_map[reader.GetString(0)] = reader.GetString(1); } } } foreach (PingResult result in data.Data) { try { string ip = result.Address.ToString(); string name = ip; if (ip_to_name_map.ContainsKey(ip)) { name = ip_to_name_map[ip]; } sql = $"SELECT IPAddress FROM NetworkStatus WHERE IPAddress = '{ip}';"; Changer changer = null; bool existing = false; using (SQLiteCommand command = new SQLiteCommand(sql, conn)) using (SQLiteDataReader reader = command.ExecuteReader()) { if (reader.Read()) { // It already exists--update the status and name in case it's been changed existing = true; changer = new Updater("NetworkStatus", $"IPAddress = '{ip}'", conn); } else { changer = new Inserter("NetworkStatus", conn); changer.Set("IPAddress", ip, false); } if (changer != null) { changer.Set("Name", name, false); changer.Set("SuccessfulPing", result.IsPingable ? 1 : 0); changer.Set("DatePingAttempted", data.CollectedAt); if (result.IsPingable) { changer.Set("DateSuccessfulPingOccurred", data.CollectedAt); } else if (!existing) { // It's new, and wasn't pingable, so we need to report that. We'll do that by // having an empty date/time changer.Set("DateSuccessfulPingOccurred", "", false, false); } // else it exists, but isn't pingable, so leave the DateSuccessfulPingOccurred alone } } if (changer != null) { changer.Execute(); } } catch (Exception e) { ApplicationEventLog log = new ApplicationEventLog(); log.LogError($"PingInterpreter -- {result.Address.ToString()}"); log.Log(e); } } } else { throw new Exception("PingInterpreter: data type is wrong"); } }
private void ProcessNotificationsToRepair() { Dictionary <string, object> servers = new Dictionary <string, object>(); while (!_Terminate) { while (!_Terminate && (_NotificationsToRepair.Count > 0)) { try { NotificationClient notificationSetupInfo; lock (_NotificationsToRepair) { notificationSetupInfo = _NotificationsToRepair.Dequeue(); } bool successful = SetupNotification(1, notificationSetupInfo.TableName, notificationSetupInfo.EventHandler); if (!successful) { Thread.Sleep(100); } } catch (Exception ex) { ApplicationEventLog.WriteEntry("Flow", string.Format("ProcessNotificationsToRepair:Exception processing notifications {0}", ex), EventLogEntryType.Error); } } int index = 0; servers.Clear(); while (index < _NotificationServersToReconnect.Count) { bool connected = false; if (_NotificationServersToReconnect[index].Connected) { connected = true; } else { if (!servers.ContainsKey(_NotificationServersToReconnect[index].ServerName)) { servers.Add(_NotificationServersToReconnect[index].ServerName, null); Connect(_NotificationServersToReconnect[index], false); } } if (connected) { lock (_NotificationServersToReconnect) { _NotificationServersToReconnect.RemoveAt(index); } } else { index++; } } _TriggerNotificationRepair.Reset(); int timeout = Timeout.Infinite; if (_NotificationServersToReconnect.Count > 0) { timeout = 5000; } if (_NotificationsToRepair.Count == 0) { _TriggerNotificationRepair.WaitOne(timeout); } } }
private void ReceiveCallback(IAsyncResult asyncResult) { ReceiveStateObject stateObject = asyncResult.AsyncState as ReceiveStateObject; try { int readCount = stateObject.Client.EndReceive(asyncResult); bool continueReceive = true; if (readCount > 0) { string text = Encoding.ASCII.GetString(stateObject.Buffer, 0, readCount); #if UNITTEST_DEBUG string logFileName = System.IO.Path.Combine(_LogFolder, string.Format("ReceiveMessage_{0:yyyyMMdd}.log", DateTime.Now)); StringBuilder sb = new StringBuilder(); sb.AppendFormat(string.Format("RX {0:yyyyMMdd_HHmmss.fffff} {1}\r\n", DateTime.Now, text)); lock (this) { System.IO.File.AppendAllText(logFileName, sb.ToString()); } #endif stateObject.Data.Append(text); if (text.Contains("\n")) { string data = stateObject.Data.ToString(); int count = 0; while (!string.IsNullOrEmpty(data)) { int index = data.IndexOf("\n"); if (index == -1) { // partial message - break out and get the rest in the following response //count = 0; break; } else { count += (index + 1); string message = data.Substring(0, index); ProcessMessage(message); index++; if (index < data.Length) { data = data.Substring(index); } else { data = null; } } } if (count > 0) { stateObject.Data.Remove(0, count); } } } else { if (stateObject.Client.ReceiveTimeout <= 0) { continueReceive = false; } else { TimeSpan diff = DateTime.Now.Subtract(stateObject.StartReceive); if (diff.TotalMilliseconds < stateObject.Client.ReceiveTimeout) { continueReceive = false; } } } if (continueReceive) { stateObject.StartReceive = DateTime.Now; SocketError socketError; stateObject.Client.BeginReceive(stateObject.Buffer, 0, ReceiveStateObject.BufferSize, SocketFlags.None, out socketError, _ReceiveCallback, stateObject); } else { ApplicationEventLog.WriteEntry("Flow", string.Format("DALChangeNotification::ReceiveCallback continueReceive false - Reconnecting to serve {0} port {1}", stateObject.NotificationServer.ServerName, stateObject.NotificationServer.Port), EventLogEntryType.Error); stateObject.NotificationServer.Connected = false; stateObject.Client.Close(); Connect(stateObject.NotificationServer, true); } } catch (Exception ex) { ApplicationEventLog.WriteEntry("Flow", string.Format("DALChangeNotification::ReceiveCallback Exception\n{0}", ex), EventLogEntryType.Error); stateObject.NotificationServer.Connected = false; stateObject.Client.Close(); Connect(stateObject.NotificationServer, true); } }
public void SaveObjectProperty(Guid clientID, Guid objectDefinitionID, string instanceID, Property property, TObjectState state) { LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID); if (client == null) { ApplicationEventLog.Write(LogLevel.Warning, string.Concat("SaveObject - Client not found ", clientID.ToString())); throw new NoLongerAvailableException("Device not connected"); } else { ObjectDefinitionLookups lookups = BusinessLogicFactory.Clients.GetLookups(); ObjectDefinition objectDefinition = lookups.GetObjectDefinition(objectDefinitionID); if (objectDefinition != null) { int objectID; if (int.TryParse(objectDefinition.ObjectID, out objectID)) { Model.ObjectType objectType = client.SupportedTypes.GetObjectType(objectID); if (objectType != null) { PropertyDefinition propertyDefinition = objectDefinition.GetProperty(property.PropertyDefinitionID); if (propertyDefinition != null) { byte[] payload = null; int contentType = TlvConstant.CONTENT_TYPE_TLV; if (state != TObjectState.Delete) { if ((property.Value != null) || (property.Values != null)) { if ((property.Value != null) && (LWM2MClient.DataFormat == MediaType.TextPlain)) { contentType = LWM2MClient.DataFormat; //contentType = TlvConstant.CONTENT_TYPE_PLAIN; string text = SerialiseProperty(propertyDefinition, property); if (text != null) { payload = Encoding.UTF8.GetBytes(text); } } else { Model.Object lwm2mObject = new Model.Object(); lwm2mObject.Properties.Add(property); payload = SerialiseObject(objectDefinition, lwm2mObject); } } } Request request = null; switch (state) { case TObjectState.NotChanged: break; case TObjectState.Add: request = client.NewPostRequest(objectType, instanceID, propertyDefinition.PropertyID, contentType, payload); break; case TObjectState.Update: request = client.NewPutRequest(objectType, instanceID, propertyDefinition.PropertyID, contentType, payload); break; case TObjectState.Delete: request = client.NewDeleteRequest(objectType, instanceID, propertyDefinition.PropertyID); break; default: break; } Response response = client.SendRequest(request).WaitForResponse(LWM2MClient.REQUEST_TIMEOUT); if (response == null) { throw new TimeoutException(); } else { BusinessLogicFactory.Clients.UpdateClientActivity(client); if (response.StatusCode != StatusCode.Changed) { throw new BadRequestException(); } } } } } } } }
private void ProcessSubscriptionRequests() { bool connectionError = false; DateTime?nextErrorLogTime = null; while (!_Terminate) { try { connectionError = false; _ConnectionShutdown = false; ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.uri = _Server.Uri; if (!string.IsNullOrEmpty(_Server.Username)) { connectionFactory.UserName = _Server.Username; } if (!string.IsNullOrEmpty(_Server.Password)) { connectionFactory.Password = _Server.Password; } _OpenChannels = 0; using (IConnection connection = connectionFactory.CreateConnection()) { while (!_Terminate && !_ConnectionShutdown) { _TriggerSubscriptionRequest.Reset(); while (_SubscriptionToAdd.Count > 0) { lock (_ChannelHandlers) { ChannelHandler handler; IModel channel; MessageQueue queue; lock (_Queues) { queue = _SubscriptionToAdd.Dequeue(); } if (queue != null) { if (!_ChannelHandlers.TryGetValue(queue.ChannelName, out handler)) { channel = connection.CreateModel(); channel.BasicQos(0, 1, false); channel.ExchangeDeclare(DALRabbitMQ.EXCHANGE_NAME, ExchangeType.Topic, true, false, null); handler = new ChannelHandler(queue.ChannelName, channel, connectionFactory, this); _ChannelHandlers.Add(queue.ChannelName, handler); Interlocked.Increment(ref _OpenChannels); } channel = handler.Channel; queue.Channel = channel; handler.AddQueue(queue); channel.QueueDeclare(queue.QueueName, queue.Durable, queue.Temporary, false, null); channel.QueueBind(queue.QueueName, DALRabbitMQ.EXCHANGE_NAME, queue.RoutingKey); channel.BasicConsume(queue.QueueName, false, queue.QueueName, handler); } } } _TriggerSubscriptionRequest.WaitOne(); } // Handle shutdown lock (_ChannelHandlers) { foreach (ChannelHandler item in _ChannelHandlers.Values) { item.StopProcessingMessages(); item.WaitForIdle(TimeSpan.FromSeconds(10)); if (item.Channel.IsOpen) { item.Channel.Close(200, "Goodbye"); } } _ChannelHandlers.Clear(); } if (connection.IsOpen) { connection.Close(); } } if (_ConnectionShutdown) { connectionError = true; } } catch (ThreadAbortException) { break; } catch (Exception ex) { connectionError = true; if (!nextErrorLogTime.HasValue || nextErrorLogTime.Value < DateTime.UtcNow) { StringBuilder errorMessage = new StringBuilder(); errorMessage.AppendLine(ex.ToString()); if (ex.InnerException != null) { errorMessage.AppendLine("\r\nInnerException:"); errorMessage.AppendLine(ex.InnerException.ToString()); } ApplicationEventLog.WriteEntry("Flow", string.Concat("ProcessSubscriptionRequests (", _Server.Uri.DnsSafeHost, "):\r\n", errorMessage.ToString()), System.Diagnostics.EventLogEntryType.Error); nextErrorLogTime = DateTime.UtcNow.Add(TimeSpan.FromSeconds(60)); } } if (connectionError) { lock (_Queues) { _SubscriptionToAdd.Clear(); foreach (KeyValuePair <string, MessageQueue> item in _Queues) { _SubscriptionToAdd.Enqueue(item.Value); } } lock (_ChannelHandlers) { _ChannelHandlers.Clear(); } Thread.Sleep(500); } } }
private void ReceiveCompleted(object sender, SocketAsyncEventArgs e) { Socket client = (Socket)sender; ReceiveStateObject stateObject = e.UserToken as ReceiveStateObject; try { int readCount = e.BytesTransferred; bool continueReceive = true; if (readCount > 0) { string text = Encoding.ASCII.GetString(stateObject.Buffer, 0, readCount); stateObject.Data.Append(text); if (text.Contains("|")) { string data = stateObject.Data.ToString(); int count = 0; while (!string.IsNullOrEmpty(data)) { int index = data.IndexOf("|"); if (index == -1) { break; } else { count += (index + 1); string table = data.Substring(0, index); index++; if (index < data.Length) { data = data.Substring(index); } else { data = null; } string id = null; string[] fields = table.Split(','); int fieldLength = fields.Length; if (fields[0] == BROADCAST_PURGE_NOTIFICATION) { bool purge = false; if (fieldLength >= 3) { if (!bool.TryParse(fields[2], out purge)) { purge = false; } if (fieldLength >= 4) { id = fields[3]; } } if (fieldLength >= 4) { BusinessLogicFactory.NotificationOrchestrator.SendChangeNotification(fields[1], purge, id); } } else if (fields[0] == BROADCAST_NOTIFICATION) { if (fieldLength >= 4) { id = fields[3]; } if (fieldLength >= 4) { BusinessLogicFactory.NotificationOrchestrator.SendChangeNotification(fields[1], false, id); } } else if (fields[0] == SETUP_NOTIFICATION) { if (fieldLength >= 2) { BusinessLogicFactory.NotificationOrchestrator.AddNotifcationClient(fields[1], client); } } } } stateObject.Data.Remove(0, count); } } else { if (client.ReceiveTimeout <= 0) { continueReceive = false; } else { TimeSpan diff = DateTime.Now.Subtract(stateObject.StartReceive); if (diff.TotalMilliseconds < client.ReceiveTimeout) { continueReceive = false; } } } if (continueReceive) { stateObject.StartReceive = DateTime.Now; if (!client.ReceiveAsync(e)) { ReceiveCompleted(sender, e); } } else { #if DEBUG ApplicationEventLog.WriteEntry("Flow", string.Format("DBNotificationTCPServer::DoReceiveCallback: closing client socket {0}", client), System.Diagnostics.EventLogEntryType.Information); #endif client.Close(); } } #pragma warning disable 168 catch (Exception ex) #pragma warning restore 168 { #if DEBUG ApplicationEventLog.WriteEntry("Flow", string.Format("DBNotificationTCPServer::DoReceiveCallback: Exception\n{0}", ex), System.Diagnostics.EventLogEntryType.Error); #endif } }
public void ThenBizTalkWillReceiveTheMessage(string portName) { Debug.WriteLine("BizTalkBill.TestingFramework.SpecFlow:SharedSteps:ThenBizTalkWillReceiveTheMessage(" + portName + ")"); ApplicationEventLog.CheckForDiagnosticEvent("BizTalk has received a message on port - " + portName); System.Threading.Thread.Sleep(100); Int32 ReceiveCount = 0; string LastMessageTrackingDateTime = (string)ScenarioContext.Current["LastMessageTrackingDateTime"]; new Logger().Write("LastMessageTrackingDateTime = " + LastMessageTrackingDateTime); string dbServerName = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\BizTalk Server\3.0\Administration", "MgmtDBServer", "localhost"); using (SqlConnection connection2 = new SqlConnection("Data Source=" + dbServerName + ";Initial Catalog=BizTalkDTADb;Integrated Security=True")) { string sCommand2 = string.Format("SELECT TOP 1 convert(varchar(50),[Event/Timestamp],126) FROM [BizTalkDTADb].[dbo].[dtav_MessageFacts] where [Event/Port] = '{0}' order by [Event/Timestamp] desc", portName); new Logger().Write("SQL Command = " + sCommand2); using (SqlCommand command2 = new SqlCommand(sCommand2, connection2)) { try { connection2.Open(); var lastfound = (string)command2.ExecuteScalar(); if (lastfound != null) { new Logger().Write("LastMessageFoundTrackingDateTime = " + lastfound); } else { new Logger().Write("returned null"); } } catch (Exception Ex1) { new Logger().Write("Error in LastMessageFoundTrackingDateTime - " + Ex1.ToString()); //throw; } } } using (SqlConnection connection = new SqlConnection("Data Source=" + dbServerName + ";Initial Catalog=BizTalkDTADb;Integrated Security=True")) { string sCommand = string.Format("select count(*) FROM [BizTalkDTADb].[dbo].[dtav_MessageFacts] where [Event/Timestamp] > '{0}' and [Event/Port] = '{1}'", LastMessageTrackingDateTime, portName); new Logger().Write("SQL Command = " + sCommand); new Logger().Write("Starting Receive Check = " + DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff")); for (int i = 1; i <= 20; i++) { using (SqlCommand command = new SqlCommand(sCommand, connection)) { try { connection.Open(); ReceiveCount = (Int32)command.ExecuteScalar(); connection.Close(); new Logger().Write("ReceiveCount = " + ReceiveCount.ToString()); } catch (Exception Ex1) { new Logger().Write("Exception = " + Ex1.Message); //throw; } } new Logger().Write("Ending Receive Check = " + DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff")); if (ReceiveCount > 0) { Debug.WriteLine("Break"); break; } Debug.WriteLine("Looping"); if (i <= 5) { System.Threading.Thread.Sleep(500); } else { Int32 sleepTime = 3000 * (i - 5); System.Threading.Thread.Sleep(sleepTime); } } } Assert.IsFalse(ReceiveCount < 1, "Message Not Received on Port - " + portName); }
/// <summary> /// 申报商品 /// </summary> /// <param name="decalreList">待申报商品列表,必须是同一个商家,不能超过10个商品</param> /// <returns></returns> public DeclareProductResult DeclareProduct(List <WaitDeclareProduct> decalreList) { DeclareProductResult result = new DeclareProductResult(); //检查是否有数据 if (decalreList == null || decalreList.Count <= 0) { return(result); } var group = decalreList.GroupBy(d => d.MerchantSysNo); //检查数据是否满足要求 if (group.Count() > 1 || decalreList.Count > 10) { throw new BizException("待申报商品列表,必须是同一个商家,不能超过10个商品"); } //获取商家取关务对接相关信息 VendorCustomsInfo customsInfo = SODA.LoadVendorCustomsInfoByMerchant(decalreList.FirstOrDefault().MerchantSysNo); //获取待申报商品详细信息 List <ProductDeclare> dataList = ObjectFactory <IIMBizInteract> .Instance.DeclareGetProduct(decalreList); #region 构造请求参数 EasiPayRequestDeclareProduct requestInfo = new EasiPayRequestDeclareProduct(); requestInfo.version = AppSettingManager.GetSetting("SO", "EasiPayDeclareProductConfigVersion"); requestInfo.commitTime = DateTime.Now.ToString("yyyyMMddHHmmss"); requestInfo.coName = customsInfo.CBTMerchantName; requestInfo.coCode = customsInfo.CBTSRC_NCode; requestInfo.serialNumber = this.CreateSerialNumber(requestInfo.coCode); requestInfo.Cargoes = EntityConverter <ProductDeclare, EasiPayRequestDeclareProductDetail> .Convert(dataList, (s, t) => { t.cargoCode = s.ProductID; t.cargoBrand = s.BrandName; t.cargoNameCh = s.ProductName; t.cargoNameEh = s.ProductNameEN; t.cargoModel = s.ProductMode; t.cargoSpec = s.Specifications; t.cargoPlace = s.CountryName; t.cargoFunction = s.Functions; t.cargoPurpose = s.Purpose; t.cargoIngredient = s.Component; t.cargoFactoryDate = s.ManufactureDate.ToString("yyyyMMdd"); t.cargoUnit = s.TaxUnit; t.cargoUnitNum = s.TaxQty.ToString(); t.cargoPrice = s.CurrentPrice.ToString("F2"); t.cargoGrossWT = s.GrossWeight; t.cargoNetWT = s.SuttleWeight; t.serverType = s.BizType == TradeType.FTA ? "S02" : "S01"; t.customsCode = s.CustomsCode; t.copGNo = s.ProductSKUNO; t.materialID = s.SuppliesSerialNo; t.beianUnit = s.ApplyUnit; t.beianQty = s.ApplyQty.ToString(); }); requestInfo.operationCode = "1"; requestInfo.spt = ""; #endregion #region 3.处理请求,解析请求结果 string reqContent = BuildPostReqData(requestInfo, customsInfo.CBTProductDeclareSecretKey); string note = string.Empty; string strRequestResult = HttpPostRequest(AppSettingManager.GetSetting("SO", "EasiPayDeclareProductConfigRequestUrl"), reqContent); strRequestResult = CommonUtility.HttpUrlDecode(strRequestResult); EasiPayRequestResult requestResult = SerializationUtility.JsonDeserialize <EasiPayRequestResult>(strRequestResult); if (requestResult.status.ToLower().Equals("success")) { result.Success = true; try { ObjectFactory <IIMBizInteract> .Instance.ProductBatchEntry(decalreList.Select(t => t.ProductSysNo).ToList(), "", ProductEntryStatus.Entry, ProductEntryStatusEx.Customs); } catch (Exception ex) { result.Message = ex.Message; } note = "商品报关申请成功"; } else { result.Message = requestResult.msg; note = "商品报关申请失败:" + requestResult.msg; } #region 写系统Log ApplicationEventLog log = new ApplicationEventLog() { Source = "JOB ProductDeclare", ReferenceIP = ServiceContext.Current.ClientIP, EventType = 8, HostName = "JOB", EventTitle = "ProductDeclare Request", EventMessage = reqContent, LanguageCode = "zh-CN", CompanyCode = "8601", StoreCompanyCode = "8601", EventDetail = note }; ObjectFactory <ICommonBizInteract> .Instance.CreateApplicationEventLog(log); #endregion #endregion return(result); }
/// <summary> /// 申报订单 /// </summary> /// <param name="entity"></param> /// <returns></returns> public bool DeclareSO(WaitDeclareSO entity) { bool result = false; #region 0.先进行支付申报,申报成功再执行订单申报 if (!this.DeclarePayment(entity)) { return(result); } #endregion #region 1.单笔值计算 DeclareOrderInfo declareOrderInfo = SODA.DeclareGetOrderInfoBySOSysNo(entity.SOSysNo); VendorCustomsInfo customsInfo = SODA.LoadVendorCustomsInfo(entity.SOSysNo); PayType payType = ObjectFactory <ICommonBizInteract> .Instance.GetPayTypeByID(declareOrderInfo.PayTypeID); if (declareOrderInfo == null || declareOrderInfo.SOItemList == null || declareOrderInfo.SOItemList.Count == 0) { return(result); } decimal allCargoTotalPrice = 0m; string cargoDescript = ""; decimal totalTariffAmount = 0m; decimal otherPrice = Math.Abs(declareOrderInfo.Amount.PrepayAmt) * -1; List <EasiPayRequestDeclareOrderCargoes> cargoesList = new List <EasiPayRequestDeclareOrderCargoes>(); foreach (var item in declareOrderInfo.SOItemList) { cargoDescript += (string.IsNullOrEmpty(cargoDescript) ? "" : ";") + (item.ProductName.Replace("#", "").Replace("%", "").Replace("&", "").Replace("+", "") + "描述"); totalTariffAmount += item.TariffAmt * item.Quantity; item.ProductName = item.ProductName.Replace("#", "").Replace("%", "").Replace("&", "").Replace("+", ""); //折扣除不尽时,把多余的作为OtherPrice上送 decimal currOtherPrice = Math.Abs(item.DiscountAmt) % item.Quantity; otherPrice += currOtherPrice * -1; //Item上是商品本身的价格,需要排除折扣 decimal unitPrice = item.OriginalPrice - ((Math.Abs(item.DiscountAmt) - currOtherPrice) / item.Quantity); unitPrice = decimal.Parse(unitPrice.ToString("F2")); otherPrice += Math.Abs(item.PromotionDiscount * item.Quantity) * -1; allCargoTotalPrice += unitPrice * item.Quantity; cargoesList.Add(new EasiPayRequestDeclareOrderCargoes() { cargoName = item.ProductName, cargoCode = item.EntryCode, cargoNum = item.Quantity, cargoUnitPrice = decimal.Parse(unitPrice.ToString("F2")), cargoTotalPrice = decimal.Parse((unitPrice * item.Quantity).ToString("F2")), cargoTotalTax = decimal.Parse((item.TariffAmt * item.Quantity).ToString("F2")) }); } //积分支付作为其他金额报关 otherPrice += Math.Abs(declareOrderInfo.Amount.PointPay * 1.00m / 100.00m) * -1; #endregion #region 2.构造请求业务数据 int serialNumber = SODA.CreateSODeclareRecordsSysNo(); EasiPayRequestDeclareOrder requestInfo = new EasiPayRequestDeclareOrder(); requestInfo.version = AppSettingManager.GetSetting("SO", "EasiPayDeclareOrderConfigVersion"); requestInfo.commitTime = DateTime.Now.ToString("yyyyMMddHHmmss"); requestInfo.coName = customsInfo.CBTMerchantName; requestInfo.coCode = customsInfo.CBTSRC_NCode; requestInfo.MerchantSecretKey = customsInfo.CBTSODeclareSecretKey; requestInfo.serialNumber = serialNumber.ToString(); requestInfo.merchantOrderId = entity.SOSysNo.ToString(); requestInfo.assBillNo = entity.TrackingNumber; requestInfo.orderCommitTime = declareOrderInfo.OrderDate.ToString("yyyyMMddHHmmss"); //发件信息,从Appsetting配置中取(改为从仓库表中读取 by cavin 2014-12-02) //仓库编号 //string warehouseNumber = declareOrderInfo.SOItemList[0].WarehouseNumber.Trim(); requestInfo.senderName = declareOrderInfo.senderName; //AppSettingManager.GetSetting("SO", string.Format("EasiPayDeclareOrderConfig_Sender_{0}_SenderName", warehouseNumber)); requestInfo.senderTel = declareOrderInfo.senderTel; // AppSettingManager.GetSetting("SO", string.Format("EasiPayDeclareOrderConfig_Sender_{0}_SenderTel", warehouseNumber)); requestInfo.senderCompanyName = declareOrderInfo.senderCompanyName; // AppSettingManager.GetSetting("SO", string.Format("EasiPayDeclareOrderConfig_Sender_{0}_SenderCompanyName", warehouseNumber)); requestInfo.senderAddr = declareOrderInfo.senderAddr; // AppSettingManager.GetSetting("SO", string.Format("EasiPayDeclareOrderConfig_Sender_{0}_SenderAddr", warehouseNumber)); requestInfo.senderZip = declareOrderInfo.senderZip; // AppSettingManager.GetSetting("SO", string.Format("EasiPayDeclareOrderConfig_Sender_{0}_SenderZip", warehouseNumber)); requestInfo.senderCity = declareOrderInfo.senderCity; // AppSettingManager.GetSetting("SO", string.Format("EasiPayDeclareOrderConfig_Sender_{0}_SenderCity", warehouseNumber)); requestInfo.senderProvince = declareOrderInfo.senderProvince; // AppSettingManager.GetSetting("SO", string.Format("EasiPayDeclareOrderConfig_Sender_{0}_SenderProvince", warehouseNumber)); //发件地国家,需要适配三位国家代码 requestInfo.senderCountry = declareOrderInfo.SOItemList.FirstOrDefault().CountryCode; requestInfo.cargoDescript = string.IsNullOrEmpty(cargoDescript) ? "无商品信息简述" : cargoDescript; requestInfo.allCargoTotalPrice = decimal.Parse(allCargoTotalPrice.ToString("F2")); requestInfo.allCargoTotalTax = decimal.Parse(totalTariffAmount.ToString("F2")); requestInfo.expressPrice = decimal.Parse(declareOrderInfo.Amount.ShipPrice.ToString("F2")); requestInfo.otherPrice = decimal.Parse(otherPrice.ToString("F2")); requestInfo.recPerson = string.IsNullOrWhiteSpace(declareOrderInfo.ReceiveName) ? "无" : declareOrderInfo.ReceiveName; requestInfo.recPhone = string.IsNullOrWhiteSpace(declareOrderInfo.ReceiveCellPhone) ? "无" : declareOrderInfo.ReceiveCellPhone; requestInfo.recCountry = "中国"; requestInfo.recProvince = string.IsNullOrWhiteSpace(declareOrderInfo.ReceiveProvinceName) ? "无" : declareOrderInfo.ReceiveProvinceName; requestInfo.recCity = string.IsNullOrWhiteSpace(declareOrderInfo.ReceiveCityName) ? "无" : declareOrderInfo.ReceiveCityName; requestInfo.recAddress = string.IsNullOrWhiteSpace(declareOrderInfo.ReceiveAddress) ? "无" : declareOrderInfo.ReceiveAddress; //为空 requestInfo.recZip = ""; requestInfo.serverType = declareOrderInfo.StockType == BizEntity.Common.TradeType.FTA ? "S02" : "S01"; requestInfo.custCode = declareOrderInfo.CustomsCode; requestInfo.operationCode = AppSettingManager.GetSetting("SO", "EasiPayDeclareOrderConfigOperationCode"); //为空 requestInfo.spt = ""; requestInfo.cargoes = cargoesList; requestInfo.payMethod = AppSettingManager.GetSetting("SO", "EasiPayDeclareOrderConfigPayMethod"); requestInfo.payMerchantName = payType.CBTMerchantName; requestInfo.payMerchantCode = payType.CBTMerchantCode; //支付总金额=全部商品合计总价+税费+物流运费+其他金额(其他金额为负数)-余额支付金额 requestInfo.payAmount = decimal.Parse((allCargoTotalPrice + totalTariffAmount + declareOrderInfo.Amount.ShipPrice + otherPrice).ToString("F2")); requestInfo.payCUR = customsInfo.PayCurrencyCode; requestInfo.payID = string.IsNullOrWhiteSpace(declareOrderInfo.PayInfo.SerialNumber) ? "" : declareOrderInfo.PayInfo.SerialNumber.Substring(1).Trim();//因为支付有个前缀P requestInfo.payTime = declareOrderInfo.PayInfo.PayProcessTime.Trim(); #endregion #region 3.处理请求,解析请求结果 SOLogInfo soLogInfo = new SOLogInfo() { UserSysNo = 3025, IP = "Delcare SO Job", OperationType = ECCentral.BizEntity.Common.BizLogType.Sale_SO_Update, SOSysNo = entity.SOSysNo, Note = "", CompanyCode = "8601" }; string reqContent = BuildPostReqData(requestInfo, requestInfo.MerchantSecretKey); string strRequestResult = HttpPostRequest(AppSettingManager.GetSetting("SO", "EasiPayDeclareOrderConfigRequestUrl"), reqContent); strRequestResult = CommonUtility.HttpUrlDecode(strRequestResult); EasiPayRequestResult requestResult = SerializationUtility.JsonDeserialize <EasiPayRequestResult>(strRequestResult); if (requestResult.status.ToLower().Equals("success")) { result = true; soLogInfo.Note = "订单报关申报提交成功"; } else { soLogInfo.Note = string.Format("订单报关申报提交失败:{0}", requestResult.errorMsg); } ObjectFactory <ISOLogDA> .Instance.InsertSOLog(soLogInfo); #region 写系统Log ApplicationEventLog log = new ApplicationEventLog() { Source = "JOB SODeclare", ReferenceIP = ServiceContext.Current.ClientIP, EventType = 8, HostName = "JOB", EventTitle = "SODeclare Request", EventMessage = reqContent, LanguageCode = "zh-CN", CompanyCode = "8601", StoreCompanyCode = "8601", EventDetail = soLogInfo.Note, }; ObjectFactory <ICommonBizInteract> .Instance.CreateApplicationEventLog(log); #endregion #endregion #region 4.提交申报申请成功,创建申报记录 if (result) { SODeclareRecords declareRecord = new SODeclareRecords() { SysNo = serialNumber, SOSysNo = entity.SOSysNo, TrackingNumber = entity.TrackingNumber }; SODA.CreateSODeclareRecords(declareRecord); } #endregion return(result); }
/// <summary> /// 支付申报 /// </summary> /// <param name="entity"></param> /// <returns>true申报成功,false申报失败</returns> public bool DeclarePayment(WaitDeclareSO entity) { bool result = false; #region 获取支付信息 SOPaymentDeclare data = SODA.DeclareGetPaymentInfoBySOSysNo(entity.SOSysNo); #endregion //检查是否需要进行支付申报,东方支付不需要进行支付申报 if (data.PayTypeID == s_EasiPayID) { //东方支付不需要传,直接更新支付申报状态为申报成功 SODA.DeclareUpdatePaymentDeclareInfo(entity.SOSysNo, null, 1); data = SODA.DeclareGetPaymentInfoBySOSysNo(entity.SOSysNo); } if (data.DeclareStatus.HasValue && data.DeclareStatus.Value == 1) { result = true; } else { #region 构造请求参数 VendorCustomsInfo customsInfo = SODA.LoadVendorCustomsInfo(entity.SOSysNo); PayType payType = ObjectFactory <ICommonBizInteract> .Instance.GetPayType(data.PayTypeSysNo); EasiPayRequestDeclarePayment declarePayment = EntityConverter <SOPaymentDeclare, EasiPayRequestDeclarePayment> .Convert(data); declarePayment.Version = "v1.0"; declarePayment.CommitTime = DateTime.Now.ToString("yyyyMMddhhmmss"); declarePayment.CoCode = payType.CBTMerchantCode; declarePayment.CoName = payType.CBTMerchantName; declarePayment.MerchantCode = customsInfo.CBTMerchantCode; declarePayment.MerchantName = customsInfo.CBTMerchantName; declarePayment.SerialNumber = this.CreateSerialNumber(declarePayment.CoCode); declarePayment.IdentifyType = data.IDCardType == 0 ? "30" : "";//固定值30 身份证 declarePayment.Birthday = data.Birthday.ToString("yyyyMMdd"); declarePayment.Sex = data.Gender == 0 ? "F" : data.Gender == 1 ? "M" : ""; declarePayment.PayID = data.PayTransNumber.Substring(1).Trim();//因为支付有个前缀P #endregion #region 处理请求,解析请求结果 string note = string.Empty; string reqContent = BuildPostReqData(declarePayment, payType.CBTSODeclarePaymentSecretKey); string strRequestResult = HttpPostRequest(AppSettingManager.GetSetting("SO", "EasiPayDeclarePaymentConfigRequestUrl"), reqContent); strRequestResult = CommonUtility.HttpUrlDecode(strRequestResult); EasiPayRequestResult requestResult = SerializationUtility.JsonDeserialize <EasiPayRequestResult>(strRequestResult); if (requestResult.status.ToLower().Equals("success")) { result = true; note = "支付报关申请成功"; } else { note = "支付报关申请失败:" + requestResult.msg; } #region 写系统Log ApplicationEventLog log = new ApplicationEventLog() { Source = "JOB SODeclarePayment", ReferenceIP = ServiceContext.Current.ClientIP, EventType = 9, HostName = "JOB", EventTitle = "SODeclarePayment Request", EventMessage = reqContent, LanguageCode = "zh-CN", CompanyCode = "8601", StoreCompanyCode = "8601", EventDetail = note, }; ObjectFactory <ICommonBizInteract> .Instance.CreateApplicationEventLog(log); #endregion #endregion #region 更新支付状态 SODA.DeclareUpdatePaymentDeclareInfo(entity.SOSysNo, declarePayment.SerialNumber, result ? 1 : 0); #endregion } return(result); }
/// <summary> /// Make the return list a priority list. The IDs in the list will be returned /// sorted by the time they should be collected. /// </summary> /// <returns></returns> public List <long> GetCollectorIDs() { Stopwatch watch = Stopwatch.StartNew(); List <long> devices_to_collect = new List <long>(); List <Tuple <long, DateTimeOffset> > to_collect = new List <Tuple <long, DateTimeOffset> >(); string sql = "SELECT C.CollectorID, C.NextCollectionTime, C.CollectorType FROM Collectors C INNER JOIN Devices D ON C.DeviceID = D.DeviceID WHERE D.DateDisabled IS NULL AND C.IsEnabled = 1;"; //ILog log = LogManager.GetLogger(typeof(Database)); //logging.EventLog log = new ApplicationEventLog(); try { using (SQLiteCommand command = new SQLiteCommand(sql, Conn)) using (SQLiteDataReader reader = command.ExecuteReader()) { DateTimeOffset now = DateTimeOffset.Now; while (reader.Read()) { try { long id = reader.GetInt64(0); int type = reader.GetInt32(2); if (type == (int)ECollectorType.Configuration) { continue; } // If it's never been collected, collect. No need to // record the collection time--just add it straight to devices_to_collect if (reader.IsDBNull(1)) { devices_to_collect.Add(id); } else { DateTimeOffset next_collection_time = DateTimeOffset.Parse(reader.GetString(1)); if (next_collection_time < now) { to_collect.Add(Tuple.Create(id, next_collection_time)); } } } catch (Exception ex) { logging.EventLog log = new ApplicationEventLog(); log.LogError("GetDevicesToCollect"); log.Log(ex); } } } } catch (Exception ex) { logging.EventLog log = new ApplicationEventLog(); log.LogError("GetDevicesToCollect: " + sql); log.Log(ex); } to_collect.Sort((a, b) => a.Item2.CompareTo(b.Item2)); to_collect.ForEach(c => devices_to_collect.Add(c.Item1)); //log.LogInformation($"GetDevicesToCollect took {watch.ElapsedMilliseconds} ms for {devices_to_collect.Count} devices"); return(devices_to_collect); }
public bool SetNotificationParameters(Guid clientID, Guid objectDefinitionID, string instanceID, Guid propertyDefinitionID, NotificationParameters notificationParameters) { bool result = false; try { LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID); if (client != null) { ObjectDefinitionLookups lookups = BusinessLogicFactory.Clients.GetLookups(); ObjectDefinition objectDefinition = lookups.GetObjectDefinition(objectDefinitionID); if (objectDefinition != null) { int objectID; if (int.TryParse(objectDefinition.ObjectID, out objectID)) { Model.ObjectType objectType = client.SupportedTypes.GetObjectType(objectID); if (objectType != null) { PropertyDefinition propertyDefinition = objectDefinition.GetProperty(propertyDefinitionID); if (propertyDefinition != null) { Request request = client.NewPutRequest(objectType, instanceID, propertyDefinition.PropertyID, -1, null); if (notificationParameters.MinimumPeriod.HasValue) { request.AddUriQuery(string.Concat("pmin=", notificationParameters.MinimumPeriod.Value.ToString())); } if (notificationParameters.MaximumPeriod.HasValue) { request.AddUriQuery(string.Concat("pmax=", notificationParameters.MaximumPeriod.Value.ToString())); } if (notificationParameters.GreaterThan.HasValue) { request.AddUriQuery(string.Concat("gt=", notificationParameters.GreaterThan.Value.ToString("0.0"))); } if (notificationParameters.LessThan.HasValue) { request.AddUriQuery(string.Concat("lt=", notificationParameters.LessThan.Value.ToString("0.0"))); } if (notificationParameters.Step.HasValue) { request.AddUriQuery(string.Concat("stp=", notificationParameters.Step.Value.ToString("0.0"))); } Response response = client.SendRequest(request).WaitForResponse(LWM2MClient.REQUEST_TIMEOUT); if (response == null) { throw new TimeoutException(); } else { if (response.StatusCode == StatusCode.Changed) { result = true; } } } } } } } } catch (Exception ex) { ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error); } return(result); }
protected void ThreadFunc() { try { int max_collections_per_pass = 10; logging.EventLog elog = new ApplicationEventLog(); Database db = new Database(); DataStorage storage = new DataStorage(); m_interpreters.ForEach(i => storage.AddInterpreter(i)); while (GlobalIsRunning.IsRunning) { int collector_count = 0; using (SQLiteConnection conn = db.Connection) { conn.Open(); CheckForConfigurationChanges(storage, conn); // Used to hold which collector was doing its thing if/when an exception occurs. // It's used in the exception handler. string collector_name = string.Empty; try { DBCollectionTimeRetriever retriever = new DBCollectionTimeRetriever(conn); // Gets the list of things that need to be collected right now. They'll // be in the order they should be collected. List <DataCollector> collectors = m_system_device.GetCollectors(retriever); collector_count = collectors.Count; // Limit this to the top 10 or so while (collectors.Count > max_collections_per_pass) { collectors.RemoveAt(collectors.Count - 1); } foreach (DataCollector collector in collectors) { collector_name = collector.Context.Name; //elog.LogInformation($"Collecting {collector_name}"); Stopwatch watch = Stopwatch.StartNew(); // Records that the collector is being collected, updates the next collection // time, and records when the collection attempt was started. When it's destroyed // when exiting the using, it records that it is no longer being collected. // // This was done so even if an exception occurs within Acquire(), the flag // that the collector is being collected will be cleared. using (BeingCollected bc = new BeingCollected(collector.Context.ID.ID, conn)) { collector.Acquire(); } //long elapsed_ms = watch.ElapsedMilliseconds; //if(elapsed_ms > 500) // elog.LogInformation($"Collecting {collector_name} took {elapsed_ms} ms"); if (GlobalIsRunning.IsRunning == false) { break; // out of the foreach loop } } } catch (Exception e) { elog.LogError($"Exception from within {collector_name}"); elog.Log(e); } // Will write the daily file when it's the right time to do so; otherwise, it does nothing. if (GlobalIsRunning.IsRunning) { m_daily_file_writer.DoWrite(conn); } if (GlobalIsRunning.IsRunning) { m_db_cleaner.CleanOldData(m_days_to_keep, conn); } } // Deletes any old daily files if (GlobalIsRunning.IsRunning) { m_daily_file_cleaner.DoClean(); } // Delete any old log files too, if it's time to do so. if (GlobalIsRunning.IsRunning) { LogManager.CleanOldData(); } // And make sure we update our logging if it changed if (GlobalIsRunning.IsRunning) { LogManager.CheckConfiguration(); } // m_shutdown will be reset when the thread starts, and set when it's time to // stop the thread. So this will wait if this event hasn't been // set, but will return immediately if it has been set. // // If there's still more data to collect let's make another run right away if (GlobalIsRunning.IsRunning && collector_count < max_collections_per_pass) { m_shutdown.WaitOne(TimeSpan.FromSeconds(10)); } } m_interpreters.ForEach(i => storage.RemoveInterpreter(i)); } catch (Exception e) { logging.EventLog elog = new ApplicationEventLog(); elog.Log(e); m_shutdown.Reset(); m_thread.Abort(); m_thread = null; } }
void IBasicConsumer.HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body) { try { if (_ProcessMessages) { Interlocked.Increment(ref _MessageHandlingCount); MessageFormatter messageFormatter = new MessageFormatter(); ServiceEventMessage message = messageFormatter.Deserialise(new MemoryStream(body)); lock (_Queues) { if (_Queues.ContainsKey(consumerTag)) { MessageQueue queue = _Queues[consumerTag]; message.DeliveryID = Guid.NewGuid(); AckMessageInfo ackMessageInfo = new AckMessageInfo(); ackMessageInfo.DeliveryID = message.DeliveryID; ackMessageInfo.QueueName = queue.QueueName; ackMessageInfo.DeliveryTag = deliveryTag; ackMessageInfo.TotalExpected = queue.Handlers.Count; ackMessageInfo.ChannelHandler = this; queue.AddAckMessageInfo(message.DeliveryID, ackMessageInfo); message.Queue = queue.QueueName; for (int index = 0; index < queue.Handlers.Count; index++) { try { MessageArrivedEventHandler handler = queue.Handlers[index]; handler.BeginInvoke(_ConnectionFactory.HostName, message, _Subscription.InvokeCallBack, new MessageArrivedState(handler, message, queue, ackMessageInfo)); } catch (Exception ex) { _Subscription.NackMessage(message); ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error); } } if (queue.Handlers.Count == 0) { Thread.Sleep(500); _Model.BasicReject(deliveryTag, true); Interlocked.Decrement(ref _MessageHandlingCount); ApplicationEventLog.WriteEntry("Flow", string.Format("No handlers to process message {0}", consumerTag), System.Diagnostics.EventLogEntryType.Error); } } else { Thread.Sleep(500); _Model.BasicReject(deliveryTag, true); Interlocked.Decrement(ref _MessageHandlingCount); ApplicationEventLog.WriteEntry("Flow", string.Format("HandleBasicDeliver: Failed to locate queue {0}", consumerTag), System.Diagnostics.EventLogEntryType.Error); } } } } catch (System.Runtime.Serialization.SerializationException) { string path = GetBadMessageDirectory(); File.WriteAllBytes(Path.Combine(path, string.Concat(consumerTag, "_", Guid.NewGuid().ToString())), body); _Model.BasicReject(deliveryTag, false); Interlocked.Decrement(ref _MessageHandlingCount); } catch (Exception ex) { Thread.Sleep(500); try { if (_Model != null) { _Model.BasicReject(deliveryTag, true); } Interlocked.Decrement(ref _MessageHandlingCount); } catch { } ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error); } }
/// <summary> /// 支付宝后台回调 /// </summary> /// <param name="payTypeSysNo"></param> /// <param name="collection"></param> /// <param name="context"></param> /// <returns></returns> public string AliPayCallback(int payTypeSysNo, NameValueCollection collection, out CallbackContext context) { context = new CallbackContext(); try { #region [ 写系统Log ] ApplicationEventLog log = new ApplicationEventLog() { Source = "B2C site pay", EventType = 8, HostName = "B2C", EventTitle = "Pay callback", EventMessage = Charges.BuildStringFromNameValueCollection(collection), LanguageCode = ConstValue.LanguageCode, CompanyCode = ConstValue.CompanyCode, StoreCompanyCode = ConstValue.StoreCompanyCode }; CommonDA.CreateApplicationEventLog(log); #endregion context.PaymentModeId = payTypeSysNo; context.ResponseForm = collection; Charges charge = Charges.GetInstance(context); context.SOSysNo = charge.GetSOSysNo(context); context.SOInfo = ShoppingOrderDA.PayGetOrderInfoBySOSysNo(context.SOSysNo); charge.UpdateCallbackPayment(context); #region [ 检查返回的订单实际支付金额与订单需要支付的金额是否相等,否则不予处理 ] if (context.SOInfo == null) { return(BuildPaymentCallbackReturnResult(payTypeSysNo, false)); } if (!charge.GetPayAmount(context).ToString("F2").Equals(context.SOInfo.RealPayAmt.ToString("F2"))) { ECommerce.Utility.Logger.WriteLog("订单实际支付金额与订单需要支付的金额不相等!", "PayCallback", "CheckPayAmount"); return(BuildPaymentCallbackReturnResult(payTypeSysNo, false)); } #endregion #region [ 检查NetPay是否存在并且状态为>=0,是则已支付过 ] NetpayInfo netPayInfo = ShoppingOrderDA.GetCenterDBNetpayBySOSysNo(context.SOSysNo); if (netPayInfo != null && netPayInfo.Status > (int)NetPayStatusType.Origin) { ECommerce.Utility.Logger.WriteLog("订单已经支付!", "PayCallback", "CheckNetPay"); return(BuildPaymentCallbackReturnResult(payTypeSysNo, true)); } #endregion ECommerce.Utility.Logger.WriteLog(context.ResponseForm["trade_status"], "AliPay", "FrontPay"); if (charge.GetPayResult(context)) { //支付成功 using (ITransaction scope = TransactionManager.Create()) { #region 1.写Netpay netPayInfo = new NetpayInfo() { SOSysNo = context.SOSysNo, PayTypeSysNo = payTypeSysNo, PayAmount = context.SOInfo.RealPayAmt, Source = 0, Status = NetPayStatusType.Verified, CompanyCode = context.SOInfo.CompanyCode, LanguageCode = context.SOInfo.LanguageCode, CurrencySysNo = context.SOInfo.CurrencySysNo, StoreCompanyCode = context.SOInfo.StoreCompanyCode, OrderAmt = (context.SOInfo.SoAmt - Math.Abs((context.SOInfo.Amount.PointPay * 1.00m) / decimal.Parse(ConstValue.PointExhangeRate)) - Math.Abs(context.SOInfo.PromotionAmt) + Math.Abs(context.SOInfo.Amount.PayPrice) + Math.Abs(context.SOInfo.Amount.ShipPrice) + Math.Abs(context.SOInfo.Amount.PremiumAmt) - Math.Abs(context.SOInfo.Amount.DiscountAmt) + Math.Abs(context.SOInfo.TariffAmt) ), PrePayAmt = context.SOInfo.Amount.PrepayAmt, PointPayAmt = context.SOInfo.PointPay * 1.00m / decimal.Parse(ConstValue.PointExhangeRate), GiftCardPayAmt = context.SOInfo.Amount.GiftCardPay, SerialNumber = charge.GetSerialNumber(context), PayProcessTime = charge.GetPayProcessTime(context) }; bool isTrue = ShoppingOrderDA.CreateNetpay(netPayInfo); ECommerce.Utility.Logger.WriteLog("成功", "AliPay", "FrontPay"); #endregion if (!isTrue) { //解决前后台多次并发处理重复数据 ECommerce.Utility.Logger.WriteLog("订单已经支付!", "PayCallback", "CreateNetPay"); return(BuildPaymentCallbackReturnResult(payTypeSysNo, false)); } #region 促销活动里的商品是否支持付款后扣减在线库存【支持:true或不支持:false】 if (ConstValue.PaymentInventory) { List <OrderItem> subOrderItemList = new List <OrderItem>(); context.SOInfo.SOItemList.ForEach(Item => { OrderProductItem opitem = new OrderProductItem(); opitem["Quantity"] = Item.Quantity; opitem.ProductSysNo = int.Parse(Item.ProductID); opitem.ProductName = Item.ProductName; opitem.WarehouseNumber = int.Parse(Item.WarehouseNumber); subOrderItemList.Add(opitem); }); subOrderItemList.ForEach(Item => { //限时促销 if (PipelineDA.CheckCountDownByProductSysNo(Item.ProductSysNo)) { //扣减订单商品库存 int inventoryType = PipelineDA.GetInventoryType(Item); var rowCount = PipelineDA.UpdateInventory(Item); if (rowCount != 1 && inventoryType != 1 && inventoryType != 3 && inventoryType != 5) { ECommerce.Utility.Logger.WriteLog("inventory: qty is not enough", "SOPipeline.CreateSOBasicPersister"); throw new BusinessException(string.Format("商品【{0}】库存不足", Item.ProductName)); } rowCount = PipelineDA.UpdateInventoryStock(Item); if (rowCount != 1 && inventoryType != 1 && inventoryType != 3 && inventoryType != 5) { ECommerce.Utility.Logger.WriteLog("inventory_stock: qty is not enough", "SOPipeline.CreateSOBasicPersister"); throw new BusinessException(string.Format("商品【{0}】库存不足", Item.ProductName)); } } }); } #endregion #region 2.发送支付成功邮件 //确认不需要发邮件 //CustomerInfo customer = CustomerDA.GetCustomerInfo(context.SOInfo.CustomerSysNo); //if (!string.IsNullOrWhiteSpace(customer.Email)) //{ // AsyncEmail email = new AsyncEmail(); // email.MailAddress = customer.Email; // email.CustomerID = customer.CustomerID; // email.Status = (int)EmailStatus.NotSend; // string token = Guid.NewGuid().ToString("N"); // email.ImgBaseUrl = ConfigurationManager.AppSettings["CDNWebDomain"].ToString(); // email.SetNewTokenUrl = "/EmailVerifySucceed?token=" + token + "&sysno=" + customer.SysNo.ToString() + "&email=" + System.Web.HttpUtility.HtmlEncode(customer.Email); // string subject = string.Empty; // email.MailBody = MailHelper.GetMailTemplateBody("SalesOrderPaySuccessful", out subject); // email.MailSubject = subject.Replace("[SOSysNo]", context.SOInfo.SoSysNo.ToString()); // //订单内容 // email.MailBody = email.MailBody.Replace("[CustomerName]", customer.CustomerName); // email.MailBody = email.MailBody.Replace("[SOSysNo]", context.SOInfo.SoSysNo.ToString()); // email.MailBody = email.MailBody.Replace("[PayAmount]", context.SOInfo.RealPayAmt.ToString("F2")); // email.MailBody = email.MailBody.Replace("[PayTypeName]", context.SOInfo.Payment.PayTypeName); // email.MailBody = email.MailBody.Replace("[OrderDate]", context.SOInfo.OrderDate.ToString()); // email.MailBody = email.MailBody.Replace("[ReceiveName]", context.SOInfo.ReceiveName); // email.MailBody = email.MailBody.Replace("[SOMemo]", context.SOInfo.Memo); // email.MailBody = email.MailBody.Replace("[NowDate]", DateTime.Now.ToShortDateString()); // EmailDA.SendEmail(email); //} #endregion scope.Complete(); } return(BuildPaymentCallbackReturnResult(payTypeSysNo, true)); } else { ECommerce.Utility.Logger.WriteLog("返回支付失败", "PayCallback", "CheckPayResult"); return(BuildPaymentCallbackReturnResult(payTypeSysNo, false)); } } catch (Exception ex) { //系统异常,写日志 ECommerce.Utility.Logger.WriteLog(string.Format("系统异常,异常信息:{0}!", ex.ToString()), "PayCallback", "OnlinePayBgCallbackFailure"); return(BuildPaymentCallbackReturnResult(payTypeSysNo, false)); } }
public string SaveObject(Guid clientID, Model.Object item, TObjectState state) { string result = null; LWM2MClient client = BusinessLogicFactory.Clients.GetClient(clientID); if (client == null) { ApplicationEventLog.Write(LogLevel.Warning, string.Concat("SaveObject - Client not found ", clientID.ToString())); throw new NoLongerAvailableException("Device not connected"); } else { ObjectDefinitionLookups lookups = BusinessLogicFactory.Clients.GetLookups(); ObjectDefinition objectDefinition = lookups.GetObjectDefinition(item.ObjectDefinitionID); if (objectDefinition == null) { ApplicationEventLog.Write(LogLevel.Warning, string.Concat("SaveObject - Metadata not found ", item.ObjectDefinitionID.ToString(), " client ", client.Address.ToString())); } else { int objectID; if (int.TryParse(objectDefinition.ObjectID, out objectID)) { Model.ObjectType objectType = client.SupportedTypes.GetObjectType(objectID); if (objectType != null) { Request request = null; switch (state) { case TObjectState.NotChanged: break; case TObjectState.Add: ushort instanceID; if (ushort.TryParse(item.InstanceID, out instanceID)) { request = client.NewPostRequest(objectType, null, null, TlvConstant.CONTENT_TYPE_TLV, SerialiseObject(objectDefinition, item, instanceID)); } else { request = client.NewPostRequest(objectType, null, null, TlvConstant.CONTENT_TYPE_TLV, SerialiseObject(objectDefinition, item)); } break; case TObjectState.Update: request = client.NewPostRequest(objectType, item.InstanceID, null, TlvConstant.CONTENT_TYPE_TLV, SerialiseObject(objectDefinition, item)); break; case TObjectState.Delete: request = client.NewDeleteRequest(objectType, item.InstanceID, null); break; default: break; } ApplicationEventLog.Write(LogLevel.Information, string.Concat("SaveObject - Send request ", string.Concat(objectType.Path, "/", item.InstanceID), " client ", client.Address.ToString())); Response response = client.SendRequest(request).WaitForResponse(LWM2MClient.REQUEST_TIMEOUT); if (response == null) { throw new TimeoutException(); } else { BusinessLogicFactory.Clients.UpdateClientActivity(client); if (response.StatusCode == StatusCode.Created) { if (!string.IsNullOrEmpty(response.LocationPath) && (response.LocationPath.StartsWith(request.UriPath))) { int startIndex = request.UriPath.Length + 1; if (startIndex < response.LocationPath.Length) { result = response.LocationPath.Substring(startIndex); } } } else if (response.StatusCode == StatusCode.Changed) { } else if ((response.StatusCode == StatusCode.NotFound) && (state == TObjectState.Delete)) { } else { throw new BadRequestException(); } } } } } } return(result); }