开发定时计算机服务

开发背景:马士基订舱系统(bst)需要开发carrierbooking信息通过报文(EDI)格式发送到EDI部门再发送给船公司去定舱.我们通过定义xml模版生成EDI发送给EDI部门,EDI部门把ACK/Confirm/PartiConfirm/Reject传到一个目录,而我们通过服务定时去扫描这个目录并读取里面的内容去更新我们的系统.

1)首先创建一个Windows应用程序(Moc.ImportService)

2)选中Moc.ImportService右键添加新项,选中并添加安装程序类(ProjectInstaller.cs)

3)选中Moc.ImportService右键添加新项,选中并添加安装程序类(EDIImportService.cs)

4)在ProjectInstaller.cs[设计]添加两个组件,serviceProcessInstaller1(System.ServiceProcess.ServiceProcessInstaller),serviceInstaller1(System.ServiceProcess.ServiceInstaller),在EDIImportService.cs[设计]添加组件timer1(System.Timers.Timer)并设置Interval=1000每一秒执行一次服务

5)在同一目录下添加Program.cs

using ...System; using System.Collections.Generic; using System.ServiceProcess; using System.Text; namespace Moc.ImportService ...{ static class Program ...{ /// <summary> /// 应用程序的主入口点。 /// </summary> static void Main() ...{ ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] ...{ new EDIImportService() }; ServiceBase.Run(ServicesToRun); } } }

 上面的new EDIImportService()在下面的cs类中

  EDIImportService.cs /*********************************************************** * Title : EDI 报文导入服务 * Created : fubin.pan , 2008-12-15 * Desc : * Last : ***********************************************************/ /*********************************************************** * Title : EDI 报文导入服务 * Created : fubin.pan , 2008-12-15 * Desc : * Last : ***********************************************************/ using ...System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Text; using System.Data.SqlClient; using System.IO; using Moc.Import; using Moc.Utility; using System.Configuration; namespace Moc.ImportService ...{ partial class EDIImportService : ServiceBase ...{ private const string PENDING_FILE = "Pending"; //导入文件的文件夹名称; private const string ERROR_FILE = "Error"; //导入错误的文件夹名称; private const string BACKUP_FILE = "Backup"; //导入备份的文件夹名称; private const string ACK_FILE = "Ack"; //导入备份的文件夹名称; private const string FEEDBACK_FILE = "Feedback"; //导入备份的文件夹名称; public EDIImportService() ...{ InitializeComponent(); } protected override void OnStart(string[] args) ...{ // TODO: 在此处添加代码以启动服务。 string VTime = ConfigurationManager.AppSettings["TTime"].ToString(); timer1.Interval = Convert.ToDouble(VTime) * 60000; MocLogger.Trace("[Service start]..."); timer1.Enabled = true; } protected override void OnStop() ...{ MocLogger.Trace("[dispose Timer...]"); // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 timer1.Enabled = false; } private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) ...{ string remark = string.Empty; string filedateTime = string.Empty; timer1.Enabled = false; try ...{ string strPath = System.Configuration.ConfigurationManager.AppSettings["Import_File_Path"].ToString(); //取导入文件的路径 string[] dirs = Directory.GetFiles(strPath + PENDING_FILE); 创建文件目录#region 创建文件目录 //文件正常导入备份目录 if (!System.IO.Directory.Exists(strPath + BACKUP_FILE) && (dirs.Length >= 1)) ...{ System.IO.Directory.CreateDirectory(strPath + BACKUP_FILE); } //文件出错备份目录 if (!System.IO.Directory.Exists(strPath + ERROR_FILE) && (dirs.Length >= 1)) ...{ System.IO.Directory.CreateDirectory(strPath + ERROR_FILE); } #endregion foreach (string dir in dirs) ...{ filedateTime = DateTime.Now.ToString("yyMMddHHmmss") + DateTime.Now.Millisecond.ToString(); MocImport mocreader = new MocImport(); //string FromUser = STS.Communication.RuleManager.GetRoutePerson(EDIRoute, "0", biz_no); string fileName = Path.GetFileName(dir) + "_" +filedateTime; if (mocreader.Read(dir, fileName)) ...{ if (mocreader.rebound.ToUpper() == "FEEDBACK") //如果是一般文件返回 ...{ CreateFilePath(dir, strPath + BACKUP_FILE + @"/" + FEEDBACK_FILE, mocreader.file_name, "FEEDBACK"); } else if (mocreader.rebound.ToUpper() == "ACK") //如果是ACK文件返回 ...{ CreateFilePath(dir, strPath + BACKUP_FILE + @"/" + ACK_FILE, mocreader.file_name, "ACK"); } } else ...{ if (mocreader.rebound.ToUpper() == "FEEDBACK") //如果是一般文件返回 ...{ CreateFilePath(dir, strPath + ERROR_FILE + @"/" + FEEDBACK_FILE, mocreader.file_name, "FEEDBACK"); } else if (mocreader.rebound.ToUpper() == "ACK") //如果是ACK文件返回 ...{ CreateFilePath(dir, strPath + ERROR_FILE + @"/" + ACK_FILE, mocreader.file_name, "ACK"); } } } } catch (Exception ex) ...{ MocLogger.Error("EDI Import failed! " + ex.Message); } finally ...{ } timer1.Enabled = true; } /**//// <summary> /// 创建文件目录 /// </summary> /// <returns></returns> private void CreateFilePath(string dir, string path, string filename, string feedbacktype) ...{ if (!System.IO.Directory.Exists(path)) ...{ System.IO.Directory.CreateDirectory(path); } File.Copy(dir, path + @"/" + filename, true); File.Delete(dir); MocLogger.Trace(feedbacktype + " File " + filename + " Import successful!"); } } }

 读取文件类MocImport.cs

MocImport.cs /*********************************************************** * Title : EDI 报文导入 * Created : fubin.pan , 2008-11-21 * Desc : * Last : ***********************************************************/ /*********************************************************** * Title : EDI 报文导入 * Created : fubin.pan , 2008-11-21 * Desc : * Last : ***********************************************************/ using ...System; using System.Collections.Generic; using System.Text; using System.Data; using System.Collections; using System.IO; using Microsoft.Practices.EnterpriseLibrary.Data; using System.Data.Common; using System.Data.SqlClient; using STS.Communication; using STS.Communication.Common; using STS.DataUtility; using Moc.Utility; namespace Moc.Import ...{ public class MocImport ...{ private Database db; private DataSet dt; private TransactionManager transactionManager; private string region = string.Empty; private const string EDIRoute = "CB-CUS"; private string V_Booking_No = string.Empty; //导入文件的Booking_No public string file_name = string.Empty; //导入文件的名称 private int container_count = 0; //统计所有的箱量总数 private string status = string.Empty; //当前导入文件的状态 CFM,RJB,PDC(ACK),PCM public string rebound = "ACK"; Hashtable ht = new Hashtable(); //创建一个Hashtable实例 string FromUser = string.Empty; //错误格式 string ErrorFormat = string.Empty; string oldstate = string.Empty; public MocImport() ...{ //初始化数据库连接 try ...{ transactionManager = new TransactionManager(); db = transactionManager != null ? transactionManager.Database : DatabaseFactory.CreateDatabase(); } catch(Exception ex) ...{ MocLogger.Error("Created Database failed! "+ex.Message); } } /**//// <summary> /// Description:读取EDI报文,并且更新到数据库中去 /// Author:fubin.pan /// CreateDate:2008-11-30 /// </summary> /// <param name="fileName">原始导入的文件名称</param> /// <param name="refileName">加了时间标识的文件名称</param> /// <returns></returns> public bool Read(string fileName, string refileName) ...{ //数据库连接没有创建成功,返回 if (db == null) return false; file_name = refileName; //开始读取报文... if (!File.Exists(fileName)) ...{ MocLogger.ErrorFormat("文件:...{0} 不存在!", fileName); return false; } //按行读取报文 FileStream dfile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); StreamReader sr = new StreamReader(dfile, System.Text.Encoding.Default); string strLine = null; Load File in Dataset#region Load File in Dataset try ...{ DataSet CarrierBooking = DatabaseManager.LoadDataTable(); DataTable BookingConfirmation = CarrierBooking.Tables["BookingConfirmation"]; DataTable ContainerDetail = CarrierBooking.Tables["ContainerDetail"]; DataTable ShippingOrder = CarrierBooking.Tables["ShippingOrder"]; //Head record, 第一行表头 strLine = sr.ReadLine(); DataRow dr = BookingConfirmation.NewRow(); while (strLine != null) ...{ strLine = strLine.Substring(0, strLine.Length - 1); //转义报文的特殊字符 strLine = strLine.Replace(Consts.splitSymbol, Consts.splitSymbol_Replace); strLine = strLine.Replace(Consts.terminateSymbol, Consts.terminateSymbol_Replace); //分割当前行的值 string[] keyvalues = strLine.Split('|'); if ((keyvalues != null) && (keyvalues.Length > 0)) ...{ if (keyvalues[0].ToString().Trim() == "00") ...{ dr["Message_Type"] = keyvalues[1].ToString(); dr["File_Description"] = keyvalues[2].ToString(); dr["File_Function"] = keyvalues[3].ToString(); dr["Sender_Code"] = keyvalues[4].ToString(); dr["Receiver_Code"] = keyvalues[5].ToString(); if (keyvalues[6].ToString().Trim() != "") ...{ dr["File_Create_Time"] = DatabaseManager.DateTimeParser(keyvalues[6].ToString()).AddHours(8); } dr["Creation"] = keyvalues[7].ToString(); dr["CreateName"] = keyvalues[8].ToString(); if (dr["File_Function"].ToString().ToUpper() == "PDC") ...{ rebound = "ACK"; } else if ((dr["File_Function"].ToString().ToUpper() == "CFM") || (dr["File_Function"].ToString().ToUpper() == "PCM") || (dr["File_Function"].ToString().ToUpper() == "RJB")) ...{ rebound = "FEEDBACK"; } else ...{ //如果不是上面的任何一个状态,则直接进去FEEDBACK Error目录 rebound = "FEEDBACK"; return false; } } else if (keyvalues[0].ToString().Trim() == "10") ...{ V_Booking_No = keyvalues[1].Substring(0, 8) + "-" + keyvalues[1].Substring(8, 4) + "-" + keyvalues[1].Substring(12, 4) + "-" + keyvalues[1].Substring(16, 4) + "-" + keyvalues[1].Substring(20, 12); DataRow so = ShippingOrder.NewRow(); //string V_Sub_Booking_No = string.Empty; //if (keyvalues[2].ToString().Trim() != "") //...{ // V_Sub_Booking_No = keyvalues[2].Substring(0, 8) + "-" + keyvalues[2].Substring(8, 4) + "-" + keyvalues[2].Substring(12, 4) + "-" + keyvalues[2].Substring(16, 4) + "-" + keyvalues[2].Substring(20, 12); //} so["Booking_No"] = V_Booking_No; //so["Shipping_No"] = V_Sub_Booking_No; so["Carrier_SO"] = keyvalues[4].ToString(); ShippingOrder.Rows.Add(so); so.AcceptChanges(); so.SetModified(); dr["Booking_No"] = V_Booking_No; dr["Carrier_SO"] = keyvalues[3].ToString(); if (keyvalues[5].ToString().Trim() != "") ...{ dr["CY_OpenTime"] = DatabaseManager.DateTimeParser(keyvalues[5].ToString());//DateTime.ParseExact(keyvalues[5].ToString(), "yyyyMMddhhmm", null); } if (keyvalues[6].ToString().Trim() != "") ...{ dr["CY_CloseTime"] = DatabaseManager.DateTimeParser(keyvalues[6].ToString()); } if (keyvalues[7].ToString().Trim() != "") ...{ dr["SICutOffTime"] = DatabaseManager.DateTimeParser(keyvalues[7].ToString()); } dr["C_Container_Depot"] = keyvalues[8].ToString(); if (keyvalues[9].ToString().Trim() != "") ...{ dr["C_Release_Date"] = DatabaseManager.DateTimeParser(keyvalues[9].ToString()); } dr["C_Return_Terminal"] = keyvalues[10].ToString(); } else if (keyvalues[0].ToString().Trim() == "11") ...{ container_count += Convert.ToInt32(keyvalues[2]); 添加进哈希表#region 添加进哈希表 if (!ht.Contains(keyvalues[1].ToString())) ht.Add(keyvalues[1].ToString(), Convert.ToInt32(keyvalues[2])); else return false; #endregion DataRow cd = ContainerDetail.NewRow(); cd["Container_Type"] = keyvalues[1].ToString().Trim(); cd["Confirmed_Qty"] = keyvalues[2].ToString().Trim(); ContainerDetail.Rows.Add(cd); cd.AcceptChanges(); cd.SetModified(); } else if (keyvalues[0].ToString() == "14") ...{ dr["Re_Booking_No"] = V_Booking_No; dr["Reject_Reason"] = keyvalues[2].ToString(); } else if (keyvalues[0].ToString() == "15") ...{ dr["Vessel_Code"] = keyvalues[1].ToString(); dr["Vessel"] = keyvalues[2].ToString(); dr["Voyage"] = keyvalues[3].ToString(); dr["ShippingLine_Code"] = keyvalues[4].ToString(); dr["Shipping_Line"] = keyvalues[5].ToString(); dr["Trade_Code"] = keyvalues[6].ToString(); dr["Trade"] = keyvalues[7].ToString(); if (keyvalues[8].ToString() != "") ...{ dr["ETD"] = DateTime.ParseExact(keyvalues[8].ToString(), "yyyyMMdd", null); } if (keyvalues[9].ToString() != "") ...{ dr["ETA"] = DateTime.ParseExact(keyvalues[9].ToString(), "yyyyMMdd", null); } } else if (keyvalues[0].ToString() == "98") ...{ dr["Contact_Person"] = keyvalues[1].ToString(); dr["Phone"] = keyvalues[2].ToString(); dr["Fax"] = keyvalues[3].ToString(); dr["Email"] = keyvalues[4].ToString(); dr["Remark"] = keyvalues[5].ToString(); } } strLine = sr.ReadLine(); } BookingConfirmation.Rows.Add(dr); dr.AcceptChanges(); dr.SetModified(); dt = CarrierBooking; #endregion //判断是否存在Booking_No,不存在的话就放到Error目录 if (!DatabaseManager.ValidateBookingNoInCarrier(V_Booking_No)) ...{ MocLogger.ErrorFormat("Booking No is not exist in system:...{0}", V_Booking_No); return false; } // ICommunication com = CommunicationFactory.CreateInstance(); oldstate = com.GetTaskStatus(V_Booking_No); //获取文件的region STS.Communication.Region regions=new STS.Communication.Region(); region = regions.GetRegionByBranches(DatabaseManager.GetMlog_Entity_By_BookingNo(V_Booking_No)); FromUser = STS.Communication.RuleManager.GetRoutePerson(EDIRoute, "0", V_Booking_No); file_name = refileName + "_" + FromUser;//加了用户标识的文件名称 //获取Error Log的格式 ErrorFormat = file_name + " - " + DatabaseManager.GetMlog_Entity_By_BookingNo(V_Booking_No) + " - " + FromUser + " - " + V_Booking_No + " - " + dt.Tables["ShippingOrder"].Rows[0]["Carrier_SO"].ToString() + " - " + dt.Tables["BookingConfirmation"].Rows[0]["File_Function"].ToString().ToUpper() + " - " + oldstate + " - "; return UpdateInformationData(); } catch (Exception ex) ...{ MocLogger.ErrorFormat("...{0}Read File :{1} failed! Exception : {2} ; ReadLine:{3}", ErrorFormat, fileName, ex, strLine); return false; } finally ...{ sr.Close(); dfile.Close(); } } /**//// <summary> /// 更新数据库返回值 /// </summary> /// <returns></returns> public bool UpdateInformationData() ...{ //如果报文返回状态是"APERAK",则只要更新BookingConfirmation中的Shipment_Type if (dt.Tables["BookingConfirmation"].Rows.Count > 0) ...{ DataRow row = dt.Tables["BookingConfirmation"].Rows[0]; string type = row["Message_Type"].ToString().ToUpper(); //IFTMBC/ APERAK status = row["File_Function"].ToString().ToUpper(); //CFM,RJB,PDC(ACK),PCM string reject = row["Reject_Reason"].ToString().ToUpper(); string sqlsendtime = row["File_Create_Time"].ToString(); DateTime? sendtime = null; if (sqlsendtime != "") ...{ sendtime = Convert.ToDateTime(sqlsendtime); } try ...{ string remarks = dt.Tables["BookingConfirmation"].Rows[0]["Remark"].ToString().Trim(); if (IsExeptionState(V_Booking_No, status))//如果现在的状态与Confirm状态有问题,则只记录一条历史信息 ...{ return false; } else if (status == STS.Communication.Common.Constants.PendingConfirmation) //ACK ...{ return BookingReceivedByCarrier(V_Booking_No, (DateTime)sendtime); } else if (status == STS.Communication.Common.Constants.Confirmation) //CFM ...{ return BookingConfirmByCarrier(V_Booking_No, (DateTime)sendtime); } else if (status == STS.Communication.Common.Constants.PartialConfirmation) //PCM ...{ return BookingPartialConfirmByCarrier(V_Booking_No, (DateTime)sendtime); } else if (status == STS.Communication.Common.Constants.Rejected) //RJB ...{ return BookingRejectByCarrrier(V_Booking_No, reject, (DateTime)sendtime); } } catch (Exception e) ...{ Moc.MocLogger.ErrorFormat("...{0} UpdateInformationData:{1}", ErrorFormat, e.Message); throw e; } } return false; } /**//// <summary> /// ACK回执保存入库 /// </summary> /// <param name="booking_no"></param> /// <param name="receiceTime"></param> /// <returns></returns> public bool BookingReceivedByCarrier(string booking_no, DateTime receiceTime) ...{ transactionManager.BeginTransaction(); try ...{ string remarks = dt.Tables["BookingConfirmation"].Rows[0]["Remark"].ToString().Trim(); UpdateBookingACKState(); SendMessage(booking_no, "Carrier Received By EDI:" + remarks, status, receiceTime, ""); transactionManager.Commit(); return true; } catch (Exception e) ...{ MocLogger.ErrorFormat("...{0} BookingReceivedByCarrier:{1}",ErrorFormat, e.Message); transactionManager.Rollback(); return false; } } /**//// <summary> /// Booking Confirm /// </summary> /// <param name="booking_no"></param> /// <param name="sendDate"></param> /// <returns></returns> public bool BookingConfirmByCarrier(string booking_no, DateTime sendDate) ...{ if (container_count > DatabaseManager.QueryRequest_Qty(V_Booking_No)) //如果Confirm并且箱量大于Request_Qty则做移到Error ...{ MocLogger.ErrorFormat("...{0} Confirm Container Quantity:{1} is more than :{2} System have", ErrorFormat, container_count.ToString(), DatabaseManager.QueryRequest_Qty(V_Booking_No).ToString()); return false; } if (! ContainerValidate()) ...{ return false; } transactionManager.BeginTransaction(); try ...{ if (container_count == DatabaseManager.QueryRequest_Qty(V_Booking_No)) //如果Confirm并且箱量等于Request_Qty则做Confirm ...{ UpdateBookingCFMState(); SendMessage(booking_no, "Carrier Confirm By EDI", status, sendDate, ""); } else if (container_count < DatabaseManager.QueryRequest_Qty(V_Booking_No)) //如果Confirm并且箱量小于Request_Qty则做PartialConfirm ...{ status = STS.Communication.Common.Constants.PartialConfirmation; UpdateBookingPCMState(); SendMessage(booking_no, "Carrier PartialConfirm By EDI", status, sendDate, ""); } transactionManager.Commit(); return true; } catch (Exception e) ...{ MocLogger.ErrorFormat("...{0} BookingConfirmByCarrier:{1}", ErrorFormat, e.Message); transactionManager.Rollback(); return false; } } /**//// <summary> /// BookingPartial /// </summary> /// <param name="booking_no"></param> /// <param name="sendDate"></param> /// <returns></returns> public bool BookingPartialConfirmByCarrier(string booking_no, DateTime sendDate) ...{ if (container_count > DatabaseManager.QueryRequest_Qty(V_Booking_No)) //如果PartialConfirm并且箱量大于Request_Qty则做移到Error ...{ MocLogger.ErrorFormat("BookingPartialConfirmByCarrier: Confirm Container Quantity:...{0} is more than :{1} System have:{2}", container_count.ToString(), DatabaseManager.QueryRequest_Qty(V_Booking_No).ToString(), V_Booking_No); return false; } if (!ContainerValidate()) ...{ return false; } transactionManager.BeginTransaction(); try ...{ UpdateBookingPCMState(); SendMessage(booking_no, "Carrier PartialConfirm By EDI", status, sendDate, ""); transactionManager.Commit(); return true; } catch (Exception e) ...{ MocLogger.ErrorFormat("BookingPartialConfirmByCarrier:...{0}:{1}", e.Message, V_Booking_No); transactionManager.Rollback(); return false; } } /**//// <summary> /// Booking Reject /// </summary> /// <param name="booking_no"></param> /// <param name="sendDate"></param> /// <returns></returns> public bool BookingRejectByCarrrier(string booking_no, string reasonType, DateTime sendDate) ...{ transactionManager.BeginTransaction(); try ...{ UpdateBookingRJBState(); SendMessage(booking_no, "Carrier Reject By EDI", status, sendDate, reasonType); transactionManager.Commit(); return true; } catch (Exception e) ...{ MocLogger.ErrorFormat("BookingRejectByCarrrier:...{0}:{1}", e.Message, V_Booking_No); transactionManager.Rollback(); return false; } } /**//// <summary> /// 填写回执信息到BookingConfirmation中去 /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateBookingACKState() ...{ try ...{ 更新BookingConfirmation表#region 更新BookingConfirmation表 DataRow row = dt.Tables["BookingConfirmation"].Rows[0]; string SqlInsertOrUpdateCommand = string.Empty; bool flag = false; if (DatabaseManager.ValidateBookingNo(V_Booking_No)) ...{ SqlInsertOrUpdateCommand = "INSERT INTO BookingConfirmation " + " (" + " Booking_No,Receive_Date,Creation,CreateDate,LastUpdateId,LastUpdateDate)" + " VALUES (@Booking_No,@Receive_Date,@Creation,@CreateDate,@LastUpdateId,@LastUpdateDate" + " )"; flag = true; } else ...{ SqlInsertOrUpdateCommand = "UPDATE BookingConfirmation " + " SET" + " Receive_Date=@Receive_Date,LastUpdateId=@LastUpdateId,LastUpdateDate=@LastUpdateDate " + " where Booking_No=@Booking_No"; } DbCommand insertCommand = db.GetSqlStringCommand(SqlInsertOrUpdateCommand); db.AddInParameter(insertCommand, "Booking_No", DbType.String, row["Booking_No"].ToString()); db.AddInParameter(insertCommand, "Receive_Date", DbType.DateTime, DateTime.Now.ToString()); db.AddInParameter(insertCommand, "LastUpdateId", DbType.String, row["Creation"].ToString()); db.AddInParameter(insertCommand, "LastUpdateDate", DbType.DateTime, DateTime.Now.ToString()); if (flag) ...{ db.AddInParameter(insertCommand, "Creation", DbType.String, row["Creation"].ToString()); db.AddInParameter(insertCommand, "CreateDate", DbType.DateTime, DateTime.Now.ToString()); } //db.AddInParameter(insertCommand, "Remark", DbType.String, row["Remark"].ToString()); db.ExecuteNonQuery(insertCommand, (DbTransaction)transactionManager.TransactionObject); #endregion } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateBookingACKState:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// Confirmation信息,更新信息到库中去 /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateBookingCFMState() ...{ try ...{ UpdateCarrierBookingInfo(); UpdateBookingConfirmation(); UpdateContainerInfo(); if (region.ToUpper() != "PRE") ...{ UpdateNumberedList(); } else ...{ UpdateShippingOrder(); } } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateBookingCFMState:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// ParticlConfirmation信息,更新信息到库中去 /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateBookingPCMState() ...{ try ...{ UpdateCarrierBookingInfo(); UpdateBookingConfirmation(); UpdateContainerInfo(); if (region.ToUpper() != "PRE") ...{ UpdateNumberedList(); } else ...{ UpdateShippingOrder(); } } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateBookingPCMState:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// Reject信息,更新信息到库中去 /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateBookingRJBState() ...{ try ...{ UpdateBookingConfirmation(); } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateBookingRJBState:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// 更新表CarrierBookingInfo /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateCarrierBookingInfo() ...{ try ...{ 更新CarrierBookingInfo表#region 更新CarrierBookingInfo表 String sqlBookingUpdate = "UPDATE CarrierBookingInfo SET " + " CY_OpenTime=@CY_OpenTime,CY_CloseTime=@CY_CloseTime," + " SICutOffTime=@SICutOffTime,C_Container_Depot=@C_Container_Depot," + " C_Release_Date=@C_Release_Date,C_Return_Terminal=@C_Return_Terminal " + " WHERE Booking_No=@Booking_No"; DbCommand cmdBooking = db.GetSqlStringCommand(sqlBookingUpdate); db.AddInParameter(cmdBooking, "@CY_OpenTime", DbType.DateTime, "CY_OpenTime", DataRowVersion.Current); db.AddInParameter(cmdBooking, "@CY_CloseTime", DbType.DateTime, "CY_CloseTime", DataRowVersion.Current); db.AddInParameter(cmdBooking, "@SICutOffTime", DbType.DateTime, "SICutOffTime", DataRowVersion.Current); db.AddInParameter(cmdBooking, "@C_Container_Depot", DbType.String, "C_Container_Depot", DataRowVersion.Current); db.AddInParameter(cmdBooking, "@C_Release_Date", DbType.DateTime, "C_Release_Date", DataRowVersion.Current); db.AddInParameter(cmdBooking, "@C_Return_Terminal", DbType.String, "C_Return_Terminal", DataRowVersion.Current); db.AddInParameter(cmdBooking, "@Booking_No", DbType.String, "Booking_No", DataRowVersion.Current); db.UpdateDataSet(dt, "BookingConfirmation", null, cmdBooking, null, (DbTransaction)transactionManager.TransactionObject); #endregion } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateCarrierBookingInfo:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// 更新表BookingConfirmation /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateBookingConfirmation() ...{ try ...{ 更新BookingConfirmation表#region 更新BookingConfirmation表 DataRow row = dt.Tables["BookingConfirmation"].Rows[0]; string SqlInsertOrUpdateCommand = string.Empty; bool flag = false; if (DatabaseManager.ValidateBookingNo(V_Booking_No)) ...{ SqlInsertOrUpdateCommand = "INSERT INTO BookingConfirmation " + " (" + " Booking_No,Shipment_Type,Confirm_Date,Carrier_SO," + " Reject_Reason,Vessel_Code,Vessel,Voyage,ShippingLine_Code,Shipping_Line,Trade_Code," + " Trade,ETD,ETA,Contact_Person,Phone,Fax,Email,Remark,Creation,CreateDate,LastUpdateId,LastUpdateDate,FileName)" + " VALUES (@Booking_No,@Shipment_Type,@Confirm_Date,@Carrier_SO," + " @Reject_Reason,@Vessel_Code,@Vessel,@Voyage,@ShippingLine_Code,@Shipping_Line,@Trade_Code," + " @Trade,@ETD,@ETA,@Contact_Person,@Phone,@Fax,@Email,@Remark,@Creation,@CreateDate,@LastUpdateId,@LastUpdateDate,@file_name" + " )"; flag = true; } else ...{ SqlInsertOrUpdateCommand = "UPDATE BookingConfirmation " + " SET Shipment_Type=@Shipment_Type," + " Confirm_Date=@Confirm_Date,Carrier_SO=@Carrier_SO,Reject_Reason=@Reject_Reason," + " Vessel_Code=@Vessel_Code,Vessel=@Vessel,Voyage=@Voyage,ShippingLine_Code=@ShippingLine_Code," + " Shipping_Line=@Shipping_Line,Trade_Code=@Trade_Code,Trade=@Trade,ETD=@ETD,ETA=@ETA,Contact_Person=@Contact_Person," + " Phone=@Phone,Fax=@Fax,Email=@Email,Remark=@Remark,LastUpdateId=@LastUpdateId,LastUpdateDate=@LastUpdateDate,FileName=@file_name" + " where Booking_No=@Booking_No"; } DbCommand insertCommand = db.GetSqlStringCommand(SqlInsertOrUpdateCommand); db.AddInParameter(insertCommand, "Booking_No", DbType.String, row["Booking_No"].ToString()); db.AddInParameter(insertCommand, "Shipment_Type", DbType.String, row["Shipment_Type"].ToString()); //if (!string.IsNullOrEmpty(row["Receive_Date"].ToString())) // db.AddInParameter(insertCommand, "Receive_Date", DbType.DateTime, row["Receive_Date"].ToString()); //else // db.AddInParameter(insertCommand, "Receive_Date", DbType.DateTime, DBNull.Value); if (!string.IsNullOrEmpty(row["File_Create_Time"].ToString())) db.AddInParameter(insertCommand, "Confirm_Date", DbType.DateTime, row["File_Create_Time"].ToString().Trim()); else db.AddInParameter(insertCommand, "Confirm_Date", DbType.DateTime, DBNull.Value); db.AddInParameter(insertCommand, "Carrier_SO", DbType.String, row["Carrier_SO"].ToString().Trim()); db.AddInParameter(insertCommand, "Reject_Reason", DbType.String, row["Reject_Reason"].ToString().Trim()); db.AddInParameter(insertCommand, "Vessel_Code", DbType.String, row["Vessel_Code"].ToString().Trim()); db.AddInParameter(insertCommand, "Vessel", DbType.String, row["Vessel"].ToString().Trim()); db.AddInParameter(insertCommand, "Voyage", DbType.String, row["Voyage"].ToString().Trim()); db.AddInParameter(insertCommand, "ShippingLine_Code", DbType.String, row["ShippingLine_Code"].ToString().Trim()); db.AddInParameter(insertCommand, "Shipping_Line", DbType.String, row["Shipping_Line"].ToString().Trim()); db.AddInParameter(insertCommand, "Trade_Code", DbType.String, row["Trade_Code"].ToString().Trim()); db.AddInParameter(insertCommand, "Trade", DbType.String, row["Trade"].ToString().Trim()); if (!string.IsNullOrEmpty(row["ETD"].ToString())) db.AddInParameter(insertCommand, "ETD", DbType.DateTime, row["ETD"].ToString().Trim()); else db.AddInParameter(insertCommand, "ETD", DbType.DateTime, DBNull.Value); if (!string.IsNullOrEmpty(row["ETA"].ToString())) db.AddInParameter(insertCommand, "ETA", DbType.DateTime, row["ETA"].ToString().Trim()); else db.AddInParameter(insertCommand, "ETA", DbType.DateTime, DBNull.Value); db.AddInParameter(insertCommand, "Contact_Person", DbType.String, row["Contact_Person"].ToString().Trim()); db.AddInParameter(insertCommand, "Phone", DbType.String, row["Phone"].ToString().Trim()); db.AddInParameter(insertCommand, "Fax", DbType.String, row["Fax"].ToString().Trim()); db.AddInParameter(insertCommand, "Email", DbType.String, row["Email"].ToString().Trim()); db.AddInParameter(insertCommand, "Remark", DbType.String, row["Remark"].ToString().Trim()); db.AddInParameter(insertCommand, "LastUpdateId", DbType.String, row["Creation"].ToString().Trim()); db.AddInParameter(insertCommand, "LastUpdateDate", DbType.DateTime, DateTime.Now.ToString().Trim()); if (flag) ...{ db.AddInParameter(insertCommand, "Creation", DbType.String, row["Creation"].ToString().Trim()); db.AddInParameter(insertCommand, "CreateDate", DbType.DateTime, DateTime.Now.ToString().Trim()); } db.AddInParameter(insertCommand, "file_name", DbType.String, file_name); //db.AddInParameter(insertCommand, "Creation", DbType.String, row["Creation"].ToString()); //if (!string.IsNullOrEmpty(row["CreateDate"].ToString())) // db.AddInParameter(insertCommand, "CreateDate", DbType.DateTime, row["CreateDate"].ToString()); //else // db.AddInParameter(insertCommand, "CreateDate", DbType.DateTime, DBNull.Value); db.ExecuteNonQuery(insertCommand, (DbTransaction)transactionManager.TransactionObject); #endregion } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateBookingConfirmation:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// 更新表ContainerInfo /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateContainerInfo() ...{ int k = 0; try ...{ 更新ContainerDetail DETAIL表#region 更新ContainerDetail DETAIL表 if (status == STS.Communication.Common.Constants.PartialConfirmation) ...{ string sqlContainerUpdate = string.Empty; //DataTable dt1 = dt.Tables["ContainerDetail"]; //foreach (DataRow dr in dt1.Rows) foreach (DictionaryEntry d in ht) //循环箱型 ...{ if (DatabaseManager.GetISOCodeCountByBookNo(d.Key.ToString(), V_Booking_No) > 1) //如果给我们的ISOCode对应我们的箱型多于一个 ...{ k = 0; //如果该标准Code的箱量等于库中的多个总和,则更新Confirmed_Qty=ReQuestion_Qty if (Convert.ToInt32(d.Value) == DatabaseManager.GetCountByContainerType(V_Booking_No, d.Key.ToString())) ...{ sqlContainerUpdate = "UPDATE ContainerInfo SET Confirmed_Qty=Request_Qty WHERE Booking_No=@Booking_No and " + "Container_Type in (select Scd_Id from scode where scd_Type = 2 and S_FLD_1 = @Container_Type) "; } else ...{ //如果该标准Code的箱量大于或者小于库中的多个总和,则我们没有办法处理,放到Error目录下 return; } } else if (DatabaseManager.GetISOCodeCountByBookNo(d.Key.ToString(), V_Booking_No) == 1) ...{ k = 1; sqlContainerUpdate = "UPDATE ContainerInfo SET Confirmed_Qty=@Confirmed_Qty WHERE Booking_No=@Booking_No and " + "Container_Type in (select Scd_Id from scode where scd_Type = 2 and S_FLD_1 = @Container_Type) "; } //sqlContainerUpdate = "UPDATE ContainerInfo SET Confirmed_Qty=@Confirmed_Qty WHERE Booking_No=@Booking_No and Container_Type=@Container_Type"; DbCommand cmdContainer = db.GetSqlStringCommand(sqlContainerUpdate); if (k == 1) db.AddInParameter(cmdContainer, "@Confirmed_Qty", DbType.String, d.Value.ToString()); db.AddInParameter(cmdContainer, "@Booking_No", DbType.String, V_Booking_No); db.AddInParameter(cmdContainer, "@Container_Type", DbType.String, d.Key.ToString()); db.ExecuteNonQuery(cmdContainer, (DbTransaction)transactionManager.TransactionObject); } } else if (status == STS.Communication.Common.Constants.Confirmation) ...{ string sqlContainerUpdate = "UPDATE ContainerInfo SET Confirmed_Qty=Request_Qty WHERE Booking_No=@Booking_No"; DbCommand cmdcfmContainer = db.GetSqlStringCommand(sqlContainerUpdate); db.AddInParameter(cmdcfmContainer, "@Booking_No", DbType.String, V_Booking_No); db.ExecuteNonQuery(cmdcfmContainer, (DbTransaction)transactionManager.TransactionObject); } #endregion } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateContainerInfo:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// 更新表NumberedList :PRS/PRN /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateNumberedList() ...{ try ...{ Update Carrier so#region Update Carrier so string guid = Moc.Utility.UID.getUID().ToString(); String sqlCarrierSoUpdate = "if exists (select 1 from NumberedList where Booking_No=@Booking_No) " + " UPDATE NumberedList SET NumberValue=@Carrier_SO WHERE Booking_No=@Booking_No" + " else INSERT INTO NumberedList (Number_No,Booking_No,NumberType,NumberValue)VALUES ('" + guid + "',@Booking_No,1,@Carrier_SO) "; //String sqlCarrierSoUpdate = "UPDATE NumberedList SET NumberValue=@NumberValue WHERE Booking_No=@Booking_No "; DbCommand cmdCarrierSo = db.GetSqlStringCommand(sqlCarrierSoUpdate); db.AddInParameter(cmdCarrierSo, "@Carrier_SO", DbType.String, dt.Tables["ShippingOrder"].Rows[0]["Carrier_SO"].ToString()); db.AddInParameter(cmdCarrierSo, "@Booking_No", DbType.String, V_Booking_No); db.ExecuteNonQuery(cmdCarrierSo, (DbTransaction)transactionManager.TransactionObject); //db.AddInParameter(cmdCarrierSo, "@NumberValue", DbType.String, "Carrier_SO", DataRowVersion.Current); //db.AddInParameter(cmdCarrierSo, "@Booking_No", DbType.String, "Booking_No", DataRowVersion.Current); //db.AddInParameter(cmdCarrierSo, "@Number_No", DbType.DateTime, "Shipping_No", DataRowVersion.Current); //db.UpdateDataSet(dt, "ShippingOrder", null, cmdCarrierSo, null, (DbTransaction)transactionManager.TransactionObject); #endregion } catch (Exception ex) ...{ MocLogger.ErrorFormat("UpdateNumberedList:...{0}:{1}", ex.Message, V_Booking_No); throw (ex); } } /**//// <summary> /// 更新表ShippingOrder :PRE /// </summary> /// <param name="transactionManager"></param> /// <returns></returns> public void UpdateShippingOrder() ...{ try ...{ Update Carrier so#region Update Carrier so string guid = Moc.Utility.UID.getUID().ToString(); String sqlCarrierSoUpdate = "UPDATE ShippingOrder SET Carrier_SO=@Carrier_SO WHERE Booking_No=@Booking_No and Shipping_NO=dbo.Edi_GetMainCarrierForPRE(@Booking_No,0)"; //String sqlCarrierSoUpdate = "UPDATE NumberedList SET NumberValue=@NumberValue WHERE Booking_No=@Booking_No "; DbCommand cmdCarrierSo = db.GetSqlStringCommand(sqlCarrierSoUpdate); db.AddInParameter(cmdCarrierSo, "@Carrier_SO", DbType.String, dt.Tables["ShippingOrder"].Rows[0]["Carrier_SO"].ToString()); db.AddInParameter(cmdCarrierSo, "@Booking_No", DbType.String, V_Booking_No); db.ExecuteNonQuery(cmdCarrierSo, (DbTransaction)transactionManager.TransactionObject); #endregion } catch (Exception ex) ...{ MocLogger.ErrorFormat("...{0} UpdateShippingOrder:{1}", ErrorFormat, ex.Message); throw (ex); } } /**//// <summary> /// 发送历史消息 /// </summary> /// <param name="biz_No"></param> /// <param name="msgText"></param> /// <param name="reasonType"></param> /// <param name="transactionManager"></param> /// <returns></returns> public bool HistoryMessage(string biz_No, string msgText, string reasonType) ...{ string fromTeam = STS.Communication.RuleManager.GetRouteTeam(EDIRoute, "0", biz_No); string fromUser = STS.Communication.RuleManager.GetRoutePerson(EDIRoute, "0", biz_No); ICommunication comm = CommunicationFactory.CreateInstance(); return comm.ArchiveMessage(transactionManager, biz_No, EDIRoute,fromUser, fromTeam, reasonType, msgText); } /**//// <summary> /// 发送一般消息 /// </summary> /// <param name="status"></param> /// <param name="biz_no"></param> /// <param name="fromUser"></param> /// <param name="transactionManager"></param> /// <returns></returns> public bool SendMessage(string status, string biz_no,string fromUser) ...{ ICommunication comm = new SqlCommunication(); STS.Communication.Common.Notification message = new STS.Communication.Common.Notification(); message.RouteDir = 0; message.Route = EDIRoute; message.BizNo = biz_no; message.Priority = "Normal"; message.MessageText = "Carrier Received By EDI"; message.Status = status; message.FromTeam = fromUser;//STS.Communication.RuleManager.GetRouteTeam(EDIRoute, "0", biz_no); message.FromUser = FromUser; message.ReasonType = ""; return comm.Send(transactionManager, message); } /**//// <summary> /// 发送消息 /// </summary> /// <param name="biz_No"></param> /// <param name="msgText"></param> /// <param name="status"></param> /// <param name="senDate"></param> /// <param name="reasonType"></param> /// <param name="transactionManager"></param> /// <returns></returns> public bool SendMessage(string biz_No, string msgText, string status,DateTime senDate, string reasonType) ...{ Notification message = new Notification(); message.RouteDir = 0; message.Route = EDIRoute; message.BizNo = biz_No; message.Priority = "Normal"; message.MessageText = msgText; message.Status = status; //message.FromTeam = "EDI"; //message.FromUser = "EDI"; //List<string> toTeam = new List<string>(); //string team = STS.Communication.RuleManager.GetRouteTeam(EDIRoute, "0", biz_No); //toTeam.Add(team); //message.ToTeam = toTeam; //List<string> toUser = new List<string>(); //string user = STS.Communication.RuleManager.GetRoutePerson(EDIRoute, "0", biz_No); //toUser.Add(user); //message.IsPicked = 1; //message.Picker = user; //message.ToUser = toUser; message.FromUser = STS.Communication.RuleManager.GetRoutePerson(EDIRoute, "0", biz_No); message.FromTeam = STS.Communication.RuleManager.GetRouteTeam(EDIRoute, "0", biz_No); message.ReasonType = reasonType; //if (senDate != null) message.SendDate = Convert.ToDateTime(senDate); //else // message.SendDate = DateTime.Now; ICommunication comm = CommunicationFactory.CreateInstance(); return comm.Send(transactionManager, message); } /**//// <summary> /// 校验状态 /// </summary> /// <param name="booking_no"></param> /// <param name="state">ACK,CFM,PCM,RJB</param> /// <returns></returns> public bool IsExeptionState(string booking_no, string state) ...{ try ...{ //如果是ACK,则原先状态只能为NEW if ((state.ToUpper() == Constants.PendingConfirmation.ToUpper()) && !((oldstate.ToUpper() == Constants.New.ToUpper()) || (oldstate.ToUpper() == Constants.PendingConfirmation.ToUpper()))) ...{ MocLogger.ErrorFormat("...{0} Receive State Error ! Old State:{1} Receive State:{2}", ErrorFormat, oldstate.ToUpper(), state.ToUpper()); return true; } else if ((state.ToUpper() == Constants.Confirmation.ToUpper()) && ((oldstate.ToUpper() == Constants.Draft.ToUpper()) || (oldstate.ToUpper() == Constants.Cancel.ToUpper()) || (oldstate.ToUpper() == Constants.CancelConfirmedBooking.ToUpper()))) ...{ MocLogger.ErrorFormat("...{0} Receive State Error ! Old State:{1} Receive State:{2}", ErrorFormat, oldstate.ToUpper(), state.ToUpper()); return true; } else if ((state.ToUpper() == Constants.PartialConfirmation.ToUpper()) && ((oldstate.ToUpper() == Constants.Draft.ToUpper()) || (oldstate.ToUpper() == Constants.Cancel.ToUpper()) || (oldstate.ToUpper() == Constants.CancelConfirmedBooking.ToUpper()))) ...{ MocLogger.ErrorFormat("...{0} Receive State Error ! Old State:{1} Receive State:{2}", ErrorFormat, oldstate.ToUpper(), state.ToUpper()); return true; } else if ((state.ToUpper() == Constants.Rejected.ToUpper()) && !((oldstate.ToUpper() == Constants.New.ToUpper()) || (oldstate.ToUpper() == Constants.PendingConfirmation.ToUpper()) || (oldstate.ToUpper() == Constants.Amend.ToUpper()) || (oldstate.ToUpper() == Constants.AmendConfirmedBooking.ToUpper()))) ...{ MocLogger.ErrorFormat("...{0} Receive State Error ! Old State:{1} Receive State:{2}", ErrorFormat, oldstate.ToUpper(), state.ToUpper()); return true; } return false; } catch (Exception e) ...{ MocLogger.ErrorFormat("...{0} JudgeState:{1}", ErrorFormat, e.Message); return false; } } /**//// <summary> /// 校验Confirm过来的箱形箱量 /// </summary> /// <param name="booking_no"></param> /// <param name="state">ACK,CFM,PCM,RJB</param> /// <returns></returns> public bool ContainerValidate() ...{ try ...{ foreach (DictionaryEntry d in ht) //循环箱型 ...{ if (DatabaseManager.GetISOCodeCountByBookNo(d.Key.ToString(), V_Booking_No) > 1) //如果给我们的ISOCode对应我们的箱型多于一个 ...{ if (Convert.ToInt32(d.Value) != DatabaseManager.GetCountByContainerType(V_Booking_No, d.Key.ToString())) ...{ MocLogger.ErrorFormat("...{0} One ISO Container Code have more than one Container Type and the Quantity between not equal to:{1}",ErrorFormat, d.Key.ToString()); return false; } } else if (DatabaseManager.GetISOCodeCountByBookNo(d.Key.ToString(), V_Booking_No) <= 0) //如果给我们的ISOCode对应我们的箱型没有 ...{ MocLogger.ErrorFormat("...{0} ISO Container Code have no Container Type find in system :{1}",ErrorFormat, d.Key.ToString()); return false; } } return true; } catch (Exception ex) ...{ MocLogger.ErrorFormat("...{0} UpdateContainerInfo:{1}",ErrorFormat, ex.Message); throw (ex); } } } }

你可能感兴趣的:(exception,Date,String,File,Terminal,dataset)