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
{
///
/// 公司EDICODE
///
private static string _COMEDICODE;
///
/// 船公司EDICODE
///
private static string _CGSEDICODE;
///
/// 报文本地验证信息
///
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("&", "&");
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("&", "&");
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 = "报文生成失败!
原因:
" + checkRst ;
return "Failed";
}
StringBuilder sb = new StringBuilder();
sb.Append("");
sb.Append("");
#region head
sb.Append("");
sb.Append(""+e.head.sndcom+"");
sb.Append(""+e.head.sender+"");
sb.Append("" + e.head.fromop + "");
sb.Append("" + e.head.fromtele + "");
sb.Append("" + e.head.fromfax + "");
sb.Append("" + e.head.frommail + "");
sb.Append("" + e.head.fromopc + "");
sb.Append("" + e.head.fromope + "");
sb.Append("" + e.head.accom + "");
sb.Append("");
sb.Append("");
sb.Append("" + e.head.sendtime + "");
sb.Append("" + e.head.editype + "");
sb.Append("" + e.head.EdiID + "");
sb.Append("" + e.head.EdiName + "");
sb.Append("" + e.head.EdiMode + "");
sb.Append("" + e.head.EdiReceiver + "");
sb.Append(""+e.head.EdiSender+"");
sb.Append("");
#endregion
#region Forward
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
if (type == "5")
{
sb.Append("5");
}
else
{
sb.Append("");
}
sb.Append("");
#endregion
#region reference
sb.Append("");
sb.Append("" + e.reference.blfreight + "");//!
sb.Append("" + e.reference.refid + "");
sb.Append("" + e.reference.freid + "");
sb.Append("" + e.reference.referenceno + "");
sb.Append("");
sb.Append("" + e.reference.workno + "");
sb.Append("gu");
sb.Append("" +e.reference.billofladingno + "");
sb.Append("");
#endregion
#region detail
sb.Append("");
//baseinfo
sb.Append("");
sb.Append(""+e.detail.baseinfo.orderman+"");
sb.Append("");
sb.Append("" + e.detail.baseinfo.usdaccountshipper + "");
sb.Append("");
sb.Append("" + e.detail.baseinfo.rmbaccountshipper + "");
sb.Append("" + e.detail.baseinfo.paymenttermcode + "");
sb.Append("" + e.detail.baseinfo.paymentterm + "");
sb.Append("");
sb.Append("" + e.detail.baseinfo.shippingitem + "");
sb.Append("" + e.detail.baseinfo.billofladingtype + "");
sb.Append("");
sb.Append(textRef(e.detail.baseinfo.shipper));
sb.Append("");
sb.Append("");
sb.Append(textRef(e.detail.baseinfo.consignee));
sb.Append("");
sb.Append("");
sb.Append(textRef(e.detail.baseinfo.notifyparty));
sb.Append("");
sb.Append("");
sb.Append(textRef(e.detail.baseinfo.notifyparty2));
sb.Append("");
sb.Append("");
sb.Append("" + e.detail.baseinfo.numberoforiginals + "");
sb.Append("" + e.detail.baseinfo.numberofcopys + "");
sb.Append("" + e.detail.baseinfo.placeofissuecode + "");
sb.Append("" + e.detail.baseinfo.placeofissue + "");
sb.Append("");
sb.Append("");
//cargo
sb.Append("");
sb.Append("");
sb.Append("" + e.detail.cargo.BOKKINGPARTY + "");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("" + e.detail.cargo.QUOTATIONNO + "");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
//booking
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
//freight
sb.Append("");
sb.Append("" + e.detail.freight.fl + "");
sb.Append("");
sb.Append("" + e.detail.freight.requestdate + "");
sb.Append("");
sb.Append("");
//port
sb.Append("");
sb.Append("");
sb.Append("" + e.detail.freight.port.portofloading + "");
sb.Append("" + e.detail.freight.port.portoftranship + "");
sb.Append("" + e.detail.freight.port.portofdischarge + "");
sb.Append("" + e.detail.freight.port.placeofdelivery + "");
sb.Append("");
sb.Append("");
sb.Append("" + e.detail.freight.port.co_portofloading + "");
sb.Append("");
sb.Append("" + e.detail.freight.port.co_portofdischarge + "");
sb.Append("" + e.detail.freight.port.co_placeofdelivery + "");
sb.Append("");
sb.Append("");
//vessel
sb.Append("");
sb.Append("" + e.detail.freight.vessel.carrier + "");
sb.Append("" + e.detail.freight.vessel.oceanvessel.Trim() + "");
sb.Append("" + e.detail.freight.vessel.voyno + "");
sb.Append("" + e.detail.freight.vessel.etd + "");
sb.Append("" + e.detail.freight.vessel.deliverymode + "");
sb.Append("");
//info2nd
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
//container
sb.Append("");
foreach (var c in e.detail.freight.container.containers)
{
sb.Append("");
sb.Append(""+c.containertype+"");
sb.Append("" + c.containerno + "");
sb.Append("" + c.sealno + "");
sb.Append("" + c.containernoofpkgs + "");
sb.Append("" + c.containergrossweight + "");
sb.Append("" + c.containercbm + "");
sb.Append("" + c.containerpackagingcode + "");
sb.Append("" + c.containerpackaging + "");
sb.Append("");
sb.Append(textRef(c.containerdescription));
sb.Append("");
sb.Append("");
sb.Append("" + c.vgmgrossmassweight + "");
sb.Append("" + (c.vgmweighingmethod=="总重"?"SM1":"SM2") + "");
sb.Append("" + c.vgmweighingtime + "");
sb.Append("" + c.vgmresponsibleparty + "");
sb.Append("" + c.vgmauthorizedperson + "");
sb.Append(""+c.vgmauthorizedpersontele+"");
sb.Append("" + c.vgmauthorizedpersonmail + "");
sb.Append(""+c.vgmremark+"");
sb.Append("");
}
sb.Append("");
sb.Append("");
//goods
sb.Append("");
sb.Append("");
sb.Append(textRef(e.detail.goods.marksandnumbers));
sb.Append("");
sb.Append("" + e.detail.goods.noofpkgs + "");
sb.Append("" + e.detail.goods.packagingcode + "");
sb.Append("" + e.detail.goods.packaging + "");
sb.Append("" + e.detail.goods.cargoid + "");
sb.Append("");
sb.Append("");
sb.Append(textRef(e.detail.goods.description));
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("" + e.detail.goods.grossweight + "");
sb.Append("" + e.detail.goods.cbm + "");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
//dr
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
//loadplan
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
//announce
sb.Append("");
sb.Append("");
sb.Append("");
//remarks
sb.Append("");
sb.Append("");
#endregion
sb.Append("");
return sb.ToString();
}
public static edi getEdi (string bsno,string uid,string type) {
//公司代码
string comCodeName = "";
MsOpSeae s = MsOpSeaeDAL.GetData("B.BSNO = '" + bsno + "'");
List 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 listc = new List();
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 "";
}
string[] strArr = str.Split('\n');
foreach (var item in strArr)
{
if (item=="")
{
continue;
}
sb.Append(""+item+"");
}
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×tamp=" +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(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";
}
}
///
///
///
///
/// 0:订舱 1:货代间订舱
///
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×tamp=" + 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(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 = "
以下字段为空:
[" + temp + "]
";
}
//字段超长
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 = "
以下字段[每行限数35个字符,超过部分请另起一行]:
[" + overlength + "]
";
// 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 = "
以下字段格式错误,请修改后重新提交!:
[" + KanJiValid + "]
";
temp = temp + KanJiValid;
}
//是否是系统支持的船公司
string SupportCGS="";
if (e.head.EdiReceiver=="")
{
SupportCGS += "暂不支持此船公司,详情请与客服联系!";
temp = temp + SupportCGS;
}
return temp;
}
///
/// 判断字符串是否通过每行不超过35个字符的验证
///
///
///
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;
}
///
/// 判断字符串中是否存在汉字以及特殊字符
///
///
///
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();
}
}
}
///
/// VGM发送邮件
///
///
///
///
public 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 + "
申请人:" + mbp.ShenQingRen + "
邮箱:" + mbp.YouXiang +
"
电话:" + mbp.DianHua + "
主提单号:" + 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; }
}
}