You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/DSWeb/MvcShipping/DAL/Message/vgm/vgmDAL.cs

1326 lines
52 KiB
C#

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DSWeb.Areas.MvcShipping.Models.Message.VGM;
using DSWeb.MvcShipping.Models.MsOpSeae;
using DSWeb.MvcShipping.DAL.MsOpSeaeDAL;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Net;
using System.Security.Cryptography;
using Newtonsoft.Json;
using DSWeb.MvcShipping.Models.FtpSet;
using System.Net.Mail;
using System.Net.Mime;
using DSWeb.MvcShipping.DAL.MsSysParamSet;
using HcUtility.Comm;
using DSWeb.MvcShipping.DAL.DsSendmail;
using DSWeb.EntityDA;
using DSWeb.Common.DB;
using DSWeb.MvcShipping.DAL.MsOpSeaeEdiDAL;
namespace DSWeb.Areas.MvcShipping.DAL.Message.vgm
{
public class vgmDAL
{
/// <summary>
/// 公司EDICODE
/// </summary>
private static string _COMEDICODE;
/// <summary>
/// 船公司EDICODE
/// </summary>
private static string _CGSEDICODE;
/// <summary>
/// 报文本地验证信息
/// </summary>
private static string _VALIDMESSAGE="";
//vgm联系人(系统用户代码)
private static string _VGMLIANXIREN = "";
//vgm联系人电话
private static string _VGMLIANXIRENTEL = "";
//vgm联系单位
private static string _VGMLIANXIDANWEI = "";
public static string writeAndSendVgmXml ( string bsno, string uid, string type, string path,string carrierid, out string filepath,string mblno )
{
try
{
GetUserCodeNameAndTELAndCom(uid);
string xmlstr = getEdiXML(bsno, uid, type);
xmlstr = xmlstr.Replace("&", "&amp;");
if (xmlstr == "Failed")
{
filepath = "";
return _VALIDMESSAGE;
}
string rst = SendFile(xmlstr, path, out filepath);
//string mailTitle = "申请发送VGM-主提单号:"+mblno+" "+ carrierid;
string mailTitle = "VGM发送-主提单号:" + mblno + " " + carrierid;
string mailBody = GetMailBodyWithUidAndMBLNO(uid,mblno);
SendMailWithXMLFile(mailTitle,mailBody,filepath);
return rst;
}
catch (Exception ex)
{
filepath = "";
return ex.Message;
throw;
}
}
public static bool WriteFile ( string mblno, string uid, string type, string path, out string filepath ,out string message)
{
try
{
GetUserCodeNameAndTELAndCom(uid);
string xmlstr = getEdiXML(mblno, uid, type);
if (xmlstr=="Failed")
{
filepath = "";
message = _VALIDMESSAGE;
return false;
}
xmlstr = xmlstr.Replace("&", "&amp;");
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数
Write(path + timeStamp.ToString()+".xml", xmlstr);
filepath = timeStamp.ToString() + ".xml";
message = "OK";
return true;
}
catch (Exception)
{
filepath = "";
message = "数据操作异常";
return false;
throw;
}
}
public static void Write (string filename,string stream)
{
FileStream fs = new FileStream(filename, FileMode.Create);
//获得字节数组
byte[] data = System.Text.Encoding.Default.GetBytes(stream);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
public static string getEdiXML ( string bsno,string uid ,string type) {
edi e = getEdi(bsno,uid,type);
string checkRst = CheckXMLModelValid(e);
if (checkRst != "")
{
_VALIDMESSAGE = "报文生成失败!<br/>原因:<br/> " + checkRst ;
return "Failed";
}
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"GB2312\"?>");
sb.Append("<edi>");
#region head
sb.Append("<head>");
sb.Append("<sndcom>"+e.head.sndcom+"</sndcom>");
sb.Append("<sender>"+e.head.sender+"</sender>");
sb.Append("<fromop>" + e.head.fromop + "</fromop>");
sb.Append("<fromtele>" + e.head.fromtele + "</fromtele>");
sb.Append("<fromfax>" + e.head.fromfax + "</fromfax>");
sb.Append("<frommail>" + e.head.frommail + "</frommail>");
sb.Append("<fromopc>" + e.head.fromopc + "</fromopc>");
sb.Append("<fromope>" + e.head.fromope + "</fromope>");
sb.Append("<accom>" + e.head.accom + "</accom>");
sb.Append("<accepter/>");
sb.Append("<toop/>");
sb.Append("<sendtime>" + e.head.sendtime + "</sendtime>");
sb.Append("<editype>" + e.head.editype + "</editype>");
sb.Append("<EdiID>" + e.head.EdiID + "</EdiID>");
sb.Append("<EdiName>" + e.head.EdiName + "</EdiName>");
sb.Append("<EdiMode>" + e.head.EdiMode + "</EdiMode>");
sb.Append("<EdiReceiver>" + e.head.EdiReceiver + "</EdiReceiver>");
sb.Append("<EdiSender>"+e.head.EdiSender+"</EdiSender>");
sb.Append("</head>");
#endregion
#region Forward
sb.Append("<Forward>");
sb.Append("<EdiForwardFMT/>");
sb.Append("<EdiForwardType/>");
sb.Append("<EdiForwardURL/>");
sb.Append("<EdiForwardId/>");
sb.Append("<EdiForwardPass/>");
sb.Append("<EdiForwardREFE1/>");
sb.Append("<EdiForwardREFE2/>");
sb.Append("<EdiForwardREFE3/>");
sb.Append("<EdiForwardREFE4/>");
if (type == "5")
{
sb.Append("<EdiForwardREFE5>5</EdiForwardREFE5>");
}
else
{
sb.Append("<EdiForwardREFE5/>");
}
sb.Append("</Forward>");
#endregion
#region reference
sb.Append("<reference>");
sb.Append("<blfreight>" + e.reference.blfreight + "</blfreight>");//!
sb.Append("<refid>" + e.reference.refid + "</refid>");
sb.Append("<freid>" + e.reference.freid + "</freid>");
sb.Append("<referenceno>" + e.reference.referenceno + "</referenceno>");
sb.Append("<bookingno/>");
sb.Append("<workno>" + e.reference.workno + "</workno>");
sb.Append("<sale>gu</sale>");
sb.Append("<billofladingno>" +e.reference.billofladingno + "</billofladingno>");
sb.Append("</reference>");
#endregion
#region detail
sb.Append("<detail>");
//baseinfo
sb.Append("<baseinfo>");
sb.Append("<orderman>"+e.detail.baseinfo.orderman+"</orderman>");
sb.Append("<source>" + e.detail.baseinfo.source + "</source>");
sb.Append("<usdaccountshipper>" + e.detail.baseinfo.usdaccountshipper + "</usdaccountshipper>");
sb.Append("<customshipper/>");
sb.Append("<rmbaccountshipper>" + e.detail.baseinfo.rmbaccountshipper + "</rmbaccountshipper>");
sb.Append("<paymenttermcode>" + e.detail.baseinfo.paymenttermcode + "</paymenttermcode>");
sb.Append("<paymentterm>" + e.detail.baseinfo.paymentterm + "</paymentterm>");
sb.Append("<payableat/>");
sb.Append("<shippingitem>" + e.detail.baseinfo.shippingitem + "</shippingitem>");
sb.Append("<billofladingtype>" + e.detail.baseinfo.billofladingtype + "</billofladingtype>");
sb.Append("<shipper>");
sb.Append(textRef(e.detail.baseinfo.shipper));
sb.Append("</shipper>");
sb.Append("<consignee>");
sb.Append(textRef(e.detail.baseinfo.consignee));
sb.Append("</consignee>");
sb.Append("<notifyparty>");
sb.Append(textRef(e.detail.baseinfo.notifyparty));
sb.Append("</notifyparty>");
sb.Append("<notifyparty2>");
sb.Append(textRef(e.detail.baseinfo.notifyparty2));
sb.Append("</notifyparty2>");
sb.Append("<ordermemo/>");
sb.Append("<numberoforiginals>" + e.detail.baseinfo.numberoforiginals + "</numberoforiginals>");
sb.Append("<numberofcopys>" + e.detail.baseinfo.numberofcopys + "</numberofcopys>");
sb.Append("<placeofissuecode>" + e.detail.baseinfo.placeofissuecode + "</placeofissuecode>");
sb.Append("<placeofissue>" + e.detail.baseinfo.placeofissue + "</placeofissue>");
sb.Append("<timeofissue/>");
sb.Append("</baseinfo>");
//cargo
sb.Append("<cargo>");
sb.Append("<APPLICANT/>");
sb.Append("<BOKKINGPARTY>" + e.detail.cargo.BOKKINGPARTY + "</BOKKINGPARTY>");
sb.Append("<FOBPARTY/>");
sb.Append("<SCNO/>");
sb.Append("<QUARANTINECODING/>");
sb.Append("<SCACCODE/>");
sb.Append("<QUOTATIONNO>" + e.detail.cargo.QUOTATIONNO + "</QUOTATIONNO>");
sb.Append("<CHARGETYPE/>");
sb.Append("<NVOCCHBLNO/>");
sb.Append("<realshipper>");
sb.Append("<text/></realshipper>");
sb.Append("<realconsignee>");
sb.Append("<text/></realconsignee>");
sb.Append("<realnotifyparty>");
sb.Append("<text/></realnotifyparty>");
sb.Append("<realnotifyparty2>");
sb.Append("<text/></realnotifyparty2>");
sb.Append("</cargo>");
//booking
sb.Append("<booking>");
sb.Append("<shipmentdate/>");
sb.Append("<expirydate/>");
sb.Append("<tranship/>");
sb.Append("<batch/>");
sb.Append("<quotationno/>");
sb.Append("</booking>");
//freight
sb.Append("<freight>");
sb.Append("<fl>" + e.detail.freight.fl + "</fl>");
sb.Append("<masterlclno/>");
sb.Append("<requestdate>" + e.detail.freight.requestdate + "</requestdate>");
sb.Append("<lastdate/>");
sb.Append("<arrivedate/>");
//port
sb.Append("<port>");
sb.Append("<placeofreceipt/>");
sb.Append("<portofloading>" + e.detail.freight.port.portofloading + "</portofloading>");
sb.Append("<portoftranship>" + e.detail.freight.port.portoftranship + "</portoftranship>");
sb.Append("<portofdischarge>" + e.detail.freight.port.portofdischarge + "</portofdischarge>");
sb.Append("<placeofdelivery>" + e.detail.freight.port.placeofdelivery + "</placeofdelivery>");
sb.Append("<finaldestination/>");
sb.Append("<co_placeofreceipt/>");
sb.Append("<co_portofloading>" + e.detail.freight.port.co_portofloading + "</co_portofloading>");
sb.Append("<co_portoftranship/>");
sb.Append("<co_portofdischarge>" + e.detail.freight.port.co_portofdischarge + "</co_portofdischarge>");
sb.Append("<co_placeofdelivery>" + e.detail.freight.port.co_placeofdelivery + "</co_placeofdelivery>");
sb.Append("<co_finaldestination/>");
sb.Append("</port>");
//vessel
sb.Append("<vessel>");
sb.Append("<carrier>" + e.detail.freight.vessel.carrier + "</carrier>");
sb.Append("<oceanvessel>" + e.detail.freight.vessel.oceanvessel.Trim() + "</oceanvessel>");
sb.Append("<voyno>" + e.detail.freight.vessel.voyno + "</voyno>");
sb.Append("<etd>" + e.detail.freight.vessel.etd + "</etd>");
sb.Append("<deliverymode>" + e.detail.freight.vessel.deliverymode + "</deliverymode>");
sb.Append("</vessel>");
//info2nd
sb.Append("<info2nd>");
sb.Append("<carrier/>");
sb.Append("<oceanvessel/>");
sb.Append("<voyno/>");
sb.Append("<etd/>");
sb.Append("<eta/>");
sb.Append("<remarks>");
sb.Append("<text/>");
sb.Append("</remarks>");
sb.Append("</info2nd>");
//container
sb.Append("<container>");
foreach (var c in e.detail.freight.container.containers)
{
sb.Append("<containers>");
sb.Append("<containertype>"+c.containertype+"</containertype>");
sb.Append("<containerno>" + c.containerno + "</containerno>");
sb.Append("<sealno>" + c.sealno + "</sealno>");
sb.Append("<containernoofpkgs>" + c.containernoofpkgs + "</containernoofpkgs>");
sb.Append("<containergrossweight>" + c.containergrossweight + "</containergrossweight>");
sb.Append("<containercbm>" + c.containercbm + "</containercbm>");
sb.Append("<containerpackagingcode>" + c.containerpackagingcode + "</containerpackagingcode>");
sb.Append("<containerpackaging>" + c.containerpackaging + "</containerpackaging>");
sb.Append("<containerdescription>");
sb.Append(textRef(c.containerdescription));
sb.Append("</containerdescription>");
sb.Append("<containermarksandnumbers/>");
sb.Append("<vgmgrossmassweight>" + c.vgmgrossmassweight + "</vgmgrossmassweight>");
sb.Append("<vgmweighingmethod>" + (c.vgmweighingmethod=="总重"?"SM1":"SM2") + "</vgmweighingmethod>");
sb.Append("<vgmweighingtime>" + c.vgmweighingtime + "</vgmweighingtime>");
sb.Append("<vgmresponsibleparty>" + c.vgmresponsibleparty + "</vgmresponsibleparty>");
sb.Append("<vgmauthorizedperson>" + c.vgmauthorizedperson + "</vgmauthorizedperson>");
sb.Append("<vgmauthorizedpersontele>"+c.vgmauthorizedpersontele+"</vgmauthorizedpersontele>");
sb.Append("<vgmauthorizedpersonmail>" + c.vgmauthorizedpersonmail + "</vgmauthorizedpersonmail>");
sb.Append("<vgmremark>"+c.vgmremark+"</vgmremark>");
sb.Append("</containers>");
}
sb.Append("</container>");
sb.Append("</freight>");
//goods
sb.Append("<goods>");
sb.Append("<marksandnumbers>");
sb.Append(textRef(e.detail.goods.marksandnumbers));
sb.Append("</marksandnumbers>");
sb.Append("<noofpkgs>" + e.detail.goods.noofpkgs + "</noofpkgs>");
sb.Append("<packagingcode>" + e.detail.goods.packagingcode + "</packagingcode>");
sb.Append("<packaging>" + e.detail.goods.packaging + "</packaging>");
sb.Append("<cargoid>" + e.detail.goods.cargoid + "</cargoid>");
sb.Append("<hscode/>");
sb.Append("<description>");
sb.Append(textRef(e.detail.goods.description));
sb.Append("</description>");
sb.Append("<cdescription>");
sb.Append("<text/>");
sb.Append("</cdescription>");
sb.Append("<grossweight>" + e.detail.goods.grossweight + "</grossweight>");
sb.Append("<cbm>" + e.detail.goods.cbm + "</cbm>");
sb.Append("<specialgoods>");
sb.Append("<text/>");
sb.Append("</specialgoods>");
sb.Append("</goods>");
//dr
sb.Append("<dr>");
sb.Append("<CLASS/>");
sb.Append("<PAGE/>");
sb.Append("<UNDGNO/>");
sb.Append("<TECNAME/>");
sb.Append("<PACKGROUP/>");
sb.Append("<LABEL>");
sb.Append("<text/>");
sb.Append("</LABEL>");
sb.Append("<FLASHPOINT></FLASHPOINT>");
sb.Append("<FLASHUNIT></FLASHUNIT>");
sb.Append("<EMSNO/>");
sb.Append("<MFAGNO/>");
sb.Append("<MPT/>");
sb.Append("<Elinkman/>");
sb.Append("<DANGEROUS>");
sb.Append("<text/>");
sb.Append("</DANGEROUS>");
sb.Append("<TEMPERATURE></TEMPERATURE>");
sb.Append("<TEMPERATUREUNIT></TEMPERATUREUNIT>");
sb.Append("<MINTEMPERATURE/>");
sb.Append("<MAXTEMPERATURE/>");
sb.Append("<ALLCOLDTORAGE/>");
sb.Append("<VENTI/>");
sb.Append("<REEFER>");
sb.Append("<text/>");
sb.Append("</REEFER>");
sb.Append("</dr>");
//loadplan
sb.Append("<loadplan>");
sb.Append("<entryno/>");
sb.Append("<warehouse/>");
sb.Append("<landcarrier/>");
sb.Append("<stuffdate></stuffdate>");
sb.Append("<stuffmode/>");
sb.Append("<stuffaddress/>");
sb.Append("<stuffmemo></stuffmemo>");
sb.Append("</loadplan>");
//announce
sb.Append("<announce>");
sb.Append("<text/>");
sb.Append("</announce>");
//remarks
sb.Append("<remarks/>");
sb.Append("</detail>");
#endregion
sb.Append("</edi>");
return sb.ToString();
}
public static edi getEdi (string bsno,string uid,string type) {
//公司代码
string comCodeName = "";
MsOpSeae s = MsOpSeaeDAL.GetData("B.BSNO = '" + bsno + "'");
List<MsOpSeaeDetail> sd = MsOpSeaeDAL.GetBodyList("bsno ='"+s.BSNO+"'");
head hdata = getHeadData(uid);
_CGSEDICODE = getCtnEdiCodeWithCARRIER(s.CARRIER);
hdata.accom = _CGSEDICODE;
hdata.EdiReceiver = _CGSEDICODE;
edi e = new edi();
e.head = hdata;
Forward eforward = new Forward();
e.Forward = eforward;
reference r = new reference();
r.blfreight = type;//参数传9新增5修改1取消
r.refid = "";//客户端托单id *
r.freid = "";//操作系统托单id *
r.referenceno = "";//托运编号 *
r.bookingno = "";//订舱编号 *
r.workno = s.CUSTNO;//委托编号
r.sale = "";//销售员*
r.billofladingno = s.MBLNO;//提单号
e.reference = r;
detail d = new detail();
baseinfo bi = new baseinfo();
bi.orderman = s.FORWARDER==""?comCodeName:s.FORWARDER;//订舱代理
bi.source = s.BSSOURCE;
bi.usdaccountshipper = "";//结算货主usd*
bi.customshipper = "";//报关货主*
bi.rmbaccountshipper = "";//结算货主rmb*
bi.paymenttermcode = "";//付费方式PCE
bi.paymentterm = "";//付费方式
bi.payableat = "";//第三地付款地点
bi.shippingitem = s.SERVICE;//运费条款
bi.billofladingtype = "";//提单类型?
//提单货主
bi.shipper = s.SHIPPER;
//收货人
bi.consignee = s.CONSIGNEE;
//通知人
bi.notifyparty = s.NOTIFYPARTY;
//第二通知人
bi.notifyparty2 = "";
//订舱说明
bi.ordermemo = "";//订舱说明*
bi.numberoforiginals = "";//提单正本数
bi.numberofcopys = "";//提单副本数
bi.placeofissuecode = "";//签单地代码
bi.placeofissue = "";//签单地
bi.timeofissue = "";//签单时间
d.baseinfo = bi;
cargo cargo = new cargo();
d.cargo = cargo;
booking booking = new booking();
d.booking = booking;
freight f = new freight();
f.fl = "";
f.masterlclno = s.MBLNO;
f.requestdate = "";
f.lastdate = "";
f.arrivedate = "";
port port = new port();
port.placeofreceipt = s.PLACERECEIPT;
port.portofloading = s.PORTLOAD;
port.portoftranship = "";//中转港
port.portofdischarge = s.PORTDISCHARGE;
port.placeofdelivery = s.PLACEDELIVERY;
port.finaldestination = s.DESTINATION;//最终目的地
port.co_placeofreceipt = s.PLACERECEIPTID;
port.co_portofloading = s.PORTLOADID;
port.co_portoftranship = "";//中转港
port.co_portofdischarge = s.PORTDISCHARGEID;
port.co_placeofdelivery = s.PLACEDELIVERYID;
port.co_finaldestination = s.DESTINATIONID;//最终目的地
f.port = port;
vessel vessel = new vessel();
vessel.carrier = _CGSEDICODE;
vessel.oceanvessel = s.VESSEL;
vessel.voyno = s.VOYNO;
vessel.etd = s.ETD;
vessel.deliverymode = "";//运输方式
f.vessel = vessel;
info2nd i2 = new info2nd();
i2.carrier = "";
i2.oceanvessel = "";
i2.voyno = "";
i2.etd = "";
i2.deliverymode = "";
i2.remarks = "";
f.info2nd = i2;
container container = new container();
List<containers> listc = new List<containers>();
foreach (var item in sd)
{
containers cont = new containers();
cont.containertype = getCtnEdiCodeWithCtn(item.CTNALL);
cont.containerno = item.CNTRNO;
cont.sealno = item.SEALNO;
cont.containernoofpkgs = item.PKGS.ToString();
cont.containergrossweight = item.KGS.ToString();
cont.containercbm = item.CBM.ToString();
cont.containerpackagingcode = getPackingCodeWithKINDPKGS(item.KINDPKGS);
cont.containerpackaging = item.KINDPKGS;
cont.containerdescription = "";
cont.containermarksandnumbers = "";
cont.vgmgrossmassweight = item.WEIGHKGS.ToString();
//称重方式
cont.vgmweighingmethod = item.WEIGHTYPE==""?"累加":item.WEIGHTYPE;
if (item.WEIGHDATE == "")
{
//称重时间 etd前三天
string datetemp = "";
try
{
DateTime dtemp = DateTime.Parse(s.ETD);
datetemp = dtemp.AddDays(-3).ToString("yyyy-MM-dd HH:mm:ss");
}
catch (Exception)
{
}
cont.vgmweighingtime = datetemp;
}
else
{
cont.vgmweighingtime =Convert.ToDateTime(item.WEIGHDATE).ToString("yyyy-MM-dd HH:mm:ss");
}
cont.vgmresponsibleparty = _VGMLIANXIDANWEI;
cont.vgmauthorizedperson = _VGMLIANXIREN;
cont.vgmauthorizedpersontele = _VGMLIANXIRENTEL;
cont.vgmauthorizedpersonmail = "";
cont.vgmremark = item.REMARK;
listc.Add(cont);
}
container.containers = listc;
f.container = container;
d.freight = f;
goods g = new goods();
g.marksandnumbers = s.MARKS;
g.noofpkgs = s.NOPKGS;
g.packagingcode = s.KINDPKGS;
g.packaging = s.KINDPKGS;
g.cargoid = s.CARGOID;
g.hscode = s.HSCODE;
g.description = s.DESCRIPTION;
g.cdescription = "";
g.grossweight = s.GROSSWEIGHT;
g.cbm = s.CBM.ToString();
g.specialgoods = "";
d.goods = g;
dr dr = new dr();
dr.CLASS = s.DCLASS;
dr.PAGE = s.DPAGE;
dr.UNDGNO = s.DUNNO;
dr.TECNAME = "";
dr.PACKGROUP = "";
dr.LABEL = s.DLABEL;
dr.FLASHPOINT = "";
dr.FLASHUNIT = "";
dr.EMSNO = "";
dr.MFAGNO = "";
dr.MPT = "";
dr.Elinkman = "";
dr.DANGEROUS = "";
dr.TEMPERATURE = "";
dr.MINTEMPERATURE = "";
dr.MAXTEMPERATURE = "";
dr.ALLCOLDTORAGE = "";
dr.VENTI = "";
dr.REEFER = "";
d.dr = dr;
//loadplan
loadplan l = new loadplan();
l.entryno = "";
l.warehouse = "";
l.landcarrier = "";
l.stuffdate = "";
l.stuffmode = "";
l.stuffaddress = "";
l.stuffmemo = "";
d.loadplan = l;
//announce
d.announce = "";
d.remarks = "";
e.detail = d;
return e;
}
private static string textRef (string str) {
StringBuilder sb = new StringBuilder();
if (str=="")
{
return "<text/>";
}
string[] strArr = str.Split('\n');
foreach (var item in strArr)
{
if (item=="")
{
continue;
}
sb.Append("<text>"+item+"</text>");
}
return sb.ToString();
}
private static string getPackingCodeWithKINDPKGS ( string kindpkgs ) {
string sql = "select top 1 edicode from code_pkgs_edi where pkgs = '" + kindpkgs + "' and ediname = 'VGM'";
Database db = DatabaseFactory.CreateDatabase();
var rst = db.ExecuteScalar(CommandType.Text, sql);
string edicode = rst == null ? kindpkgs : rst.ToString();
return edicode;
}
private static string getCtnEdiCodeWithCtn ( string ctn ) {
string sql = "select top 1 edicode from code_ctn_edi where ctn = '"+ctn+"' and ediname = 'VGM'";
Database db = DatabaseFactory.CreateDatabase();
var rst = db.ExecuteScalar(CommandType.Text, sql);
string edicode = rst == null ? ctn : rst.ToString();
return edicode;
}
private static string getCtnEdiCodeWithCARRIER ( string carrier )
{
string sql = "select top 1 edicode from code_cust_edi where cust = '" + carrier + "' and ediname = 'VGM'";
Database db = DatabaseFactory.CreateDatabase();
var rst = db.ExecuteScalar(CommandType.Text, sql);
string edicode = rst == null ? "" : rst.ToString();
return edicode;
}
private static string getVGMCodeWithComcode ( string comid ) {
string sql = "select top 1 sendcode from code_FtpSet where ediname = 'VGM' and corpid = '" + comid + "'";
Database db = DatabaseFactory.CreateDatabase();
var rst = db.ExecuteScalar(CommandType.Text, sql);
string edicode = rst == null ? "" : rst.ToString();
return edicode;
}
private static string getComCodeNameWithComShortName (string shortname) {
string sql = "select top 1 CODENAME from info_client WHERE SHORTNAME = '"+shortname+"'";
Database db = DatabaseFactory.CreateDatabase();
var rst = db.ExecuteScalar(CommandType.Text, sql);
string codename = rst == null ? "" : rst.ToString();
return codename;
}
private static head getHeadData (string uid) {
head h = new head();
string sql = @"select c.CODENAME comcode,
u.CODENAME,
u.SHOWNAME,
ub.OFFICEPHONE,
ub.FAX,
ub.MOBILE,
ub.EMAIL1,
c.GID comid
from [user] u
JOIN user_company uc on u.GID = uc.USERID
JOIN company c on uc.COMPANYID = c.GID
JOIN user_baseinfo ub on u.GID = ub.USERID
where u.GID = '" + uid+"'";
Database db = DatabaseFactory.CreateDatabase();
using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
{
while (reader.Read())
{
_COMEDICODE = getVGMCodeWithComcode(reader["comid"].ToString());
h.sndcom = _COMEDICODE;
h.sender = reader["comcode"].ToString() ;
h.fromop = reader["CODENAME"].ToString();
h.fromtele = reader["OFFICEPHONE"].ToString();
h.fromfax = reader["FAX"].ToString();
//h.frommail = reader["EMAIL1"].ToString();
h.frommail = "dongshengsoft@dongshengsoft.com";
h.fromopc = reader["SHOWNAME"].ToString();
h.fromope = reader["CODENAME"].ToString();
h.accom = "";
h.accepter = "";
h.toop = "";
h.sendtime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
h.editype = "VERMAS";
h.EdiID = "";
h.EdiName = "";
h.EdiMode = "HYXML";
h.EdiSender = _COMEDICODE;
h.EdiReceiver = "";
}
}
return h;
}
public static string EncodeBase64 ( string source )
{
byte[] bytes = Encoding.Default.GetBytes(source); //gb编码base64
return Convert.ToBase64String(bytes);
}
public static string SendFile (string xml,string path,out string filepath)
{
try
{
string innerXml = xml;
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string signOrg = "dssoft" + "ced93003-1577-4ff4-9fcf-73a52408eb36" + timestamp;
string sign = MD5Encrypt32(signOrg).Replace("-","") ;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filename = timeStamp.ToString() + ".xml";
filepath = path+filename;
Write(path + filename, innerXml);
string xmlContent = System.Web.HttpUtility.UrlEncode(EncodeBase64(innerXml));
string url = "user_id=dssoft&format=json&timestamp=" +System.Web.HttpUtility.UrlEncode(timestamp) + "";
url = url + "&sign=" + sign + "&method=cargoedi.demessage.msgrec.post&deaId=" + _COMEDICODE + "";
url = url + "&userId=dssoft&docName=" + filename + "&docType=VERMAS&docLength="+xmlContent.Length+"&";
url = url + "docContent=" + xmlContent;
url = url + "&channel=WSTOM&destDeaId="+_CGSEDICODE+"&port=Qingdao";
string formUrl = "http://api.nbeport.com/router/rest";
string formData = url; //提交的参数
byte[] postData = Encoding.UTF8.GetBytes(formData);
HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
Encoding myEncoding = Encoding.UTF8;
request.Method = "POST";
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();
HttpWebResponse response;
Stream responseStream;
StreamReader reader;
string srcString;
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
string rstmsg = "";
srcString = reader.ReadToEnd();
Result result = JsonConvert.DeserializeObject<Result>(srcString);
if (result.code == "T")
{
if (result.data.result=="true")
{
rstmsg = "发送成功!";
}
else
{
rstmsg = result.data.errorInfo;
}
}
else
{
rstmsg = "接受失败," + result.msg;
}
reader.Close();
return rstmsg;
}
catch
{
filepath = "";
return "error";
}
}
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <param name="type">0:订舱 1:货代间订舱</param>
/// <returns></returns>
public static string SendFileWithFilePath(string path, CodeFtpSet ftpSet, string filetype, string carrierid = "")
{
try
{
string docType = "";
if (filetype == "B")//订舱
{
docType = "SHPMBF";
}
else if (filetype == "SHPORD")//货代间订舱
{
docType = "SHPORD";
}
else if (filetype == "E")//确认
{
docType = "SHPMIN";
}
else if (filetype == "SHPMIN")//确认(多品名)
{
docType = "SHPMIN";
}
_COMEDICODE = ftpSet.SENDCOMPANYCODE;
if (carrierid=="")
_CGSEDICODE = ftpSet.RECEIVECODE;
else
_CGSEDICODE = carrierid;
string innerXml = GetStringWithFilePath(path);
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string signOrg = "dssoft" + "ced93003-1577-4ff4-9fcf-73a52408eb36" + timestamp;
string sign = MD5Encrypt32(signOrg).Replace("-", "");
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数
string filename = System.IO.Path.GetFileName(path);
Write(path + filename, innerXml);
string xmlContent = System.Web.HttpUtility.UrlEncode(EncodeBase64(innerXml));
string url = "user_id=dssoft&format=json&timestamp=" + System.Web.HttpUtility.UrlEncode(timestamp) + "";
url = url + "&sign=" + sign + "&method=cargoedi.demessage.msgrec.post&deaId=" + _COMEDICODE + "";
url = url + "&userId=dssoft&docName=" + filename + "&docType="+docType+"&docLength=" + xmlContent.Length + "&";
url = url + "docContent=" + xmlContent;
url = url + "&channel=WSTOM&destDeaId=" + _CGSEDICODE + "&port=Qingdao";
string formUrl = "http://api.nbeport.com/router/rest";
string formData = url; //提交的参数
byte[] postData = Encoding.UTF8.GetBytes(formData);
HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
Encoding myEncoding = Encoding.UTF8;
request.Method = "POST";
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();
HttpWebResponse response;
Stream responseStream;
StreamReader reader;
string srcString;
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
string rstmsg = "";
srcString = reader.ReadToEnd();
Result result = JsonConvert.DeserializeObject<Result>(srcString);
if (result.code == "T")
{
if (result.data.result == "true")
{
rstmsg = "发送成功!";
}
else
{
rstmsg = result.data.errorInfo;
}
}
else
{
rstmsg = "接受失败," + result.msg;
}
reader.Close();
return rstmsg;
}
catch
{
return "error";
}
}
public static string GetStringWithFilePath ( string path ) {
StreamReader sr = new StreamReader(path, Encoding.Default);
String line;
StringBuilder sb = new StringBuilder();
while ((line = sr.ReadLine()) != null)
{
sb.Append(line.ToString());
}
return sb.ToString();
}
public static string MD5Encrypt32 ( string password )
{
string cl = password;
string pwd = "";
MD5 md5 = MD5.Create(); //实例化一个md5对像
// 加密后是一个字节类型的数组这里要注意编码UTF8/Unicode等的选择 
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 0; i < s.Length; i++)
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母如果使用大写X则格式后的字符是大写字符
pwd = pwd + s[i].ToString("X2");
}
return pwd;
}
public static string CheckXMLModelValid (edi e) {
string temp = "";
//非空
if (e.reference.billofladingno=="")
{
temp += "提单号,";
}
//if (e.detail.baseinfo.shipper=="")
//{
// temp += "发货人,";
//}
//if (e.detail.baseinfo.consignee == "")
//{
// temp += "收货人,";
//}
//if (e.detail.baseinfo.notifyparty == "")
//{
// temp += "通知人,";
//}
if (e.detail.freight.port.portofloading == "")
{
temp += "装货港,";
}
//if (e.detail.freight.port.portofdischarge == "")
//{
// temp += "卸货港,";
//}
if (e.detail.freight.port.placeofdelivery == "")
{
temp += "目的港,";
}
if (e.detail.freight.port.co_portofloading == "")
{
temp += "装货港代码,";
}
//if (e.detail.freight.port.co_portofdischarge == "")
//{
// temp += "卸货港代码,";
//}
//if (e.detail.freight.port.co_placeofdelivery == "")
//{
// temp += "目的港代码,";
// }
if (e.detail.freight.vessel.carrier == "")
{
temp += "船公司,";
}
if (e.detail.freight.vessel.oceanvessel == "")
{
temp += "船名,";
}
if (e.detail.freight.vessel.voyno == "")
{
temp += "航次,";
}
if (e.detail.freight.vessel.etd == "")
{
temp += "开航日期,";
}
foreach (var item in e.detail.freight.container.containers)
{
if (item.containertype=="")
{
temp += "箱型,";
}
if (item.containerno == "")
{
temp += "箱号,";
}
if (item.sealno == "")
{
temp += "封号,";
}
if (item.containernoofpkgs == "")
{
temp += "件数,";
}
if (item.containergrossweight == "")
{
temp += "毛重,";
}
if (item.containercbm == "")
{
temp += "体积,";
}
if (item.containerpackagingcode == "")
{
temp += "箱货物包装类型代码,";
}
if (item.containerpackaging == "")
{
temp += "箱货物包装类型,";
}
if (item.vgmgrossmassweight == "")
{
temp += "VGM总重量,";
}
else
{
if (double.Parse(item.vgmgrossmassweight) == 0)
{
temp += "VGM总重量,";
}
}
if (item.vgmweighingmethod == "")
{
temp += "VGM称重方式,";
}
if (item.vgmweighingtime == "")
{
temp += "VGM称重时间,";
}
if (item.vgmresponsibleparty == "")
{
temp += "VGM联系单位,";
}
if (item.vgmauthorizedperson == "")
{
temp += "VGM授权联系人,";
}
if (item.vgmauthorizedpersontele == "")
{
temp += "VGM授权联系人电话,";
}
}
if (temp!="")
{
temp = temp.Substring(0, temp.Length - 1);
temp = "<br/>以下字段为空:<br/>[" + temp + "]<br/>";
}
//字段超长
var overlength = "";
//if (!checkValid35(e.detail.baseinfo.shipper))
//{
// overlength = "发货人,";
//}
//if (!checkValid35(e.detail.baseinfo.consignee))
//{
// overlength = "收货人,";
//}
//if (!checkValid35(e.detail.baseinfo.notifyparty))
//{
// overlength = "通知人,";
//}
//if (overlength!="")
//{
// overlength = overlength.Substring(0, overlength.Length - 1);
// overlength = "<br/>以下字段[每行限数35个字符超过部分请另起一行]:<br/>[" + overlength + "]<br/>";
// temp = temp + overlength;
//}
//仅限英文
string KanJiValid = "";
foreach (var item in e.detail.freight.container.containers)
{
if (!checkValidKanJi(item.vgmresponsibleparty))
{
KanJiValid += "[VGM联系单位]";
}
if (!checkValidKanJi(item.vgmauthorizedperson))
{
KanJiValid += "[VGM授权联系人]";
}
if (!checkValidKanJi(item.vgmauthorizedpersontele))
{
KanJiValid += "[VGM授权联系人电话]";
}
}
if (KanJiValid!="")
{
//KanJiValid = KanJiValid.Substring(0, KanJiValid.Length - 1);
KanJiValid = "<br/>以下字段格式错误,请修改后重新提交!:<br/>[" + KanJiValid + "]<br/>";
temp = temp + KanJiValid;
}
//是否是系统支持的船公司
string SupportCGS="";
if (e.head.EdiReceiver=="")
{
SupportCGS += "暂不支持此船公司,详情请与客服联系!";
temp = temp + SupportCGS;
}
return temp;
}
/// <summary>
/// 判断字符串是否通过每行不超过35个字符的验证
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static bool checkValid35 (string str) {
StringBuilder sb = new StringBuilder();
if (str == "")
{
return true;
}
string[] strArr = str.Split('\n');
foreach (var item in strArr)
{
if (item == "")
{
continue;
}
if (item.Length>35)
{
return false;
}
}
return true;
}
/// <summary>
/// 判断字符串中是否存在汉字以及特殊字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static bool checkValidKanJi ( string str ) {
for (int i = 0; i < str.Length; i++)
{
if ((int)str[i] > 127)
{
return false;
}
}
return true;
}
private static void GetUserCodeNameAndTELAndCom (string uid)
{
string sql =@"SELECT u.CODENAME,ub.OFFICEPHONE,isnull(c.CODENAME,'') comcodename
from [user] u
join user_baseinfo ub on u.GID=ub.USERID
join user_company uc on uc.USERID = u.GID
join company c on c.GID = uc.COMPANYID where u.gid = '"+uid+"'";
Database db = DatabaseFactory.CreateDatabase();
using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
{
while (reader.Read())
{
_VGMLIANXIREN = reader["CODENAME"].ToString();
_VGMLIANXIRENTEL = reader["OFFICEPHONE"].ToString();
_VGMLIANXIDANWEI = reader["comcodename"].ToString();
}
}
}
/// <summary>
/// VGM发送邮件
/// </summary>
/// <param name="title"></param>
/// <param name="context"></param>
/// <param name="xmlpath"></param>
private static void SendMailWithXMLFile (string title,string context,string xmlpath)
{
// SendEmail se = new SendEmail("dongshengsoft@dongshengsoft.com", "admin@dongshengsoft.com", "", "", title, context, false);
// se.SetSmtp("admin@dongshengsoft.com", "ds!@#)(*", "smtpcom.263xmail.com", 25, false,
//System.Net.Mail.MailPriority.Normal);
var MAILTONAME = "admin@dongshengsoft.com";
var PARAMVALUE = MsSysParamSetDAL.GetData("PARAMNAME='MAILTONAME'");
if (PARAMVALUE.PARAMVALUE != "") MAILTONAME = PARAMVALUE.PARAMVALUE;
var MAILTOPASSWORD = "ds!@#)(*";
PARAMVALUE = MsSysParamSetDAL.GetData("PARAMNAME='MAILTOPASSWORD'");
if (PARAMVALUE.PARAMVALUE != "") MAILTOPASSWORD = PARAMVALUE.PARAMVALUE;
var MAILTOSERVER = "smtpcom.263xmail.com";
PARAMVALUE = MsSysParamSetDAL.GetData("PARAMNAME='MAILTOSERVER'");
if (PARAMVALUE.PARAMVALUE != "") MAILTOSERVER = PARAMVALUE.PARAMVALUE;
var MAILTOPORT = "465";
PARAMVALUE = MsSysParamSetDAL.GetData("PARAMNAME='MAILTOPORT'");
if (PARAMVALUE.PARAMVALUE != "") MAILTOPORT = PARAMVALUE.PARAMVALUE;
var DONGSHENGMAILADDR = "myshipping@myshipping.net";
PARAMVALUE = MsSysParamSetDAL.GetData("PARAMNAME='DONGSHENGMAILADDR'");
if (PARAMVALUE.PARAMVALUE != "") DONGSHENGMAILADDR = PARAMVALUE.PARAMVALUE;
using (var smtp = new SmtpClient())
//TO:
using (var mail = new MailMessage(MAILTONAME, DONGSHENGMAILADDR))
{
//附件
var attach = new Attachment(xmlpath, MediaTypeNames.Text.Xml);
//设置ContentId
mail.Attachments.Add(attach);
//标题和内容注意设置编码因为默认编码是ASCII
mail.Subject = title;
mail.SubjectEncoding = Encoding.UTF8;
//HTML内容
mail.Body = context;
mail.BodyEncoding = Encoding.UTF8;
//指示改电子邮件内容是HTML格式
mail.IsBodyHtml = true;
//20210622 同时将邮件文件发至ftp服务器
SendEmail se = new SendEmail(DONGSHENGMAILADDR, MAILTONAME, "", "", title, context, true);
var xmlfonder = xmlpath.Replace(Path.GetFileName(xmlpath), "");
se.Attachments(xmlpath);
MsOpSeaeEdiDAL.SendMailToFtp(se, xmlfonder, SendEmail.MailBillType.VGM);
//SMTP设置根据邮箱类型设置这里是Live Mail的SMTP服务器地址
smtp.Host = MAILTOSERVER;
smtp.Port =Convert.ToInt32(MAILTOPORT);
smtp.EnableSsl = false;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(MAILTONAME, MAILTOPASSWORD);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
}
}
private static string GetMailBodyWithUidAndMBLNO ( string uid, string mblno )
{
string sql = @"SELECT c.NAME,u.SHOWNAME,ub.EMAIL1,ub.OFFICEPHONE from [user] u
join user_baseinfo ub on ub.USERID=u.GID
join user_company uc on uc.USERID=u.GID
join company c on uc.COMPANYID = c.GID
where u.gid = '"+uid+"'";
Database db = DatabaseFactory.CreateDatabase();
MailBodyProp mbp = new MailBodyProp();
using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
{
while (reader.Read())
{
mbp.GongSiMingCheng = reader["NAME"].ToString();
mbp.ShenQingRen = reader["SHOWNAME"].ToString();
mbp.YouXiang = reader["EMAIL1"].ToString();
mbp.DianHua = reader["OFFICEPHONE"].ToString();
mbp.ZhuTiDanHao = mblno;
}
}
string bodyStr = "公司名称:" + mbp.GongSiMingCheng + "<br/>申请人:" + mbp.ShenQingRen + "<br/>邮箱:" + mbp.YouXiang +
"<br/>电话:" + mbp.DianHua + "<br/>主提单号:" + mbp.ZhuTiDanHao + "\n";
return bodyStr;
}
}
class MailBodyProp {
public string GongSiMingCheng { get; set; }
public string ShenQingRen { get; set; }
public string YouXiang { get; set; }
public string DianHua { get; set; }
public string ZhuTiDanHao { get; set; }
}
}