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.

2226 lines
98 KiB
C#

This file contains ambiguous Unicode 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.Text;
using System.IO;
using System.Net;
using System.Windows.Forms;
using dongshengFtpTools.common;
using MailAnalyzeTools.Common;
using System.Configuration;
using System.Data;
using MailAnalyzeTools;
using System.Text.RegularExpressions;
using MailAnalyzeTools.Logic.MSK;
using MailAnalyzeTools.Models;
using MailAnalyzeTools.Logic;
using WinSCP;
namespace dongshengFtpTools
{
public class ftptool
{
/// <summary>
/// 构造函数
/// </summary>
internal ftptool()
{
initConfig();
}
/// <summary>
/// 构造函数
/// </summary>
internal ftptool(downloadReportType fptconfigNo)
{
initConfig(fptconfigNo);
}
#region 公有方法
public void downloadfile()
{
//只考虑一级目录情况
m_curFolder = "";
analyzeFilelist(GetFileList(""));
doDownloadList();
//
if (m_Folderlist.Count > 0)
{
fileprop[] fldLst = new fileprop[m_Folderlist.Count];
m_Folderlist.CopyTo(fldLst);
for (int i = 0; i < fldLst.Length; i++)
{ //只考虑2级目录
m_curFolder = fldLst[i].fname;
analyzeFilelist(GetFileList(m_curFolder));
doDownloadList();
}
}
}
#endregion //公有方法
#region 私有方法
/// <summary>m_downloaderrList
/// 初始化配置
/// </summary>
private void initConfig(downloadReportType ftpcnfigno = downloadReportType.BLControl)
{
FtpConfig cfg;
switch (ftpcnfigno)
{
case downloadReportType.BcReport:
cfg = frmMailSet.FtpBcConfigSet();
break;
case downloadReportType.InvoceEdi:
cfg = frmMailSet.FtpInvoiceConfigSet();
break;
default:
cfg = frmMailSet.FtpConfigSet();
break;
}
LogHelper.WriteLog(typeof(ftptool), "SFTP准备连接");
//ftp服务器路径
m_ftpServer = cfg.FtpServer;
//ftp本地路径
m_ftpDefaultUrl = ConfigurationManager.AppSettings["FtpDefaultPath"] ;
//登入到ftp的账号
m_ftpUserName = cfg.LoginID;
//登入到ftp的密码
m_ftpUserPwd = cfg.LoginPWD;
//登入到ftp的端口
m_ftpPort = cfg.Port;
//下载后的文件存放路径
m_localpath = cfg.DownloadPath;
//
cfg.SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"];
cfg.SshPrivateKeyPath = ConfigurationManager.AppSettings["SshPrivateKeyPath"];
LogHelper.WriteLog(typeof(ftptool), "SFTP准备连接2");
//
try
{
m_sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = m_ftpServer,
PortNumber = Convert.ToInt32(cfg.Port),
UserName = m_ftpUserName,
Password = m_ftpUserPwd,
SshHostKeyFingerprint = cfg.SshHostKeyFingerprint,
SshPrivateKeyPath = cfg.SshPrivateKeyPath,
PrivateKeyPassphrase = m_ftpUserPwd,
};
m_sessionOptions.AddRawSettings("KEX", "rsa,ecdh,dh-gex-sha1,dh-group14-sha1,WARN,dh-group1-sha1");
m_sessionOptions.AddRawSettings("FSProtocol", "2");
}
catch (Exception e) {
LogHelper.WriteLog(typeof(ftptool), e.Message);
}
try
{
LogHelper.WriteLog(typeof(ftptool), "SFTP准备连接3");
m_session = new Session();
m_session.Open(m_sessionOptions);
LogHelper.WriteLog(typeof(ftptool),"SFTP已连接");
//this.propUpdateDownloadStatus("已连接");
}
catch (Exception e) {
LogHelper.WriteLog(typeof(ftptool), e.Message);
//this.propUpdateDownloadStatus("FTP连接出现错误"+e.Message);
}
initialDownloadFailureDic();
}
/// <summary>
/// 初始化下载失败的数据字典
/// </summary>
private void initialDownloadFailureDic()
{
// select ftp_filename,lastmodi_date from t_op_seae_ftpfile_bc where download_ok=0
string strsql = "select ftp_filename,ReportID,download_failuretimes from t_op_seae_ftpfile_bc where download_ok=0";
DataTable dt = DbHelperSQL.QueryTable(strsql);
if (m_downloaderrList == null)
{
m_downloaderrList = new Dictionary<string, DLDFilestruct>();
}
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string fname = dt.Rows[i]["ftp_filename"].ToString();
int flcount;
int.TryParse(dt.Rows[i]["download_failuretimes"].ToString(), out flcount);
string reportid = dt.Rows[i]["ReportID"].ToString();
DLDFilestruct fstrut = new DLDFilestruct(reportid);
fstrut.FileName = fname;
fstrut.FailurCount = flcount;
if (!m_downloaderrList.Keys.Contains(fname))
{
m_downloaderrList.Add(fname, fstrut);
}
}
}
}
/// <summary>
/// 先处理根目录的文件,然后遍历子目录
/// </summary>
/// <param name="ftpRemotePath"></param>
/// <returns></returns>
private string[] GetFileList(string ftpRemotePath)
{
string uriPath;
if (m_ftpServer.IndexOf("ftp:") < 0)
uriPath = "ftp://" + m_ftpServer;
else
uriPath = m_ftpServer;
if (m_ftpPort != "21")
{
uriPath = uriPath.TrimEnd('/') + ":" + m_ftpPort;
}
if (!string.IsNullOrEmpty(ftpRemotePath))
{
uriPath = uriPath.TrimEnd('/') + "/" + ftpRemotePath;
}
string[] downloadFiles = null;
StringBuilder result = new StringBuilder();
if (m_filelist == null)
m_filelist = new List<fileprop>();
else
m_filelist.Clear();
if (m_Folderlist == null)
m_Folderlist = new List<fileprop>();
else
m_Folderlist.Clear();
try
{
FtpWebRequest m_reqFTP = (FtpWebRequest)FtpWebRequest.Create(uriPath);
m_reqFTP.UseBinary = true;
m_reqFTP.Credentials = new NetworkCredential(m_ftpUserName, m_ftpUserPwd);
this.propUpdateDownloadStatus(uriPath + ":" + m_ftpUserName + ":连接失败");
//m_reqFTP.UsePassive = true;// 默认是 true也就是被动模式主动模式false
m_reqFTP.KeepAlive = true;//长连接
// 除非 EnableSsl 属性是 true否则所有数据和命令包括您的用户名和密码信息都会以明文形式发送到服务器。
//监视网络流量的任何人都可以查看凭据并使用它们连接服务器。如果要连接的 FTP 服务器要求凭据并支持安全套接字层 (SSL),则应将 EnableSsl 设置为 true。
// m_reqFTP.EnableSsl = true;//
//m_reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
m_reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = m_reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);// Encoding.GetEncoding("gb2312")// Encoding.Default//Encoding.Default,Encoding.ASCII
this.propUpdateDownloadStatus("已连接");
string line = reader.ReadLine();
while (line != null)
{
if (line.Substring(0, 5) == "total" || line.Substring(line.Length - 1, 1) == ".") {
}
else
result.AppendLine(line);
//debug
///// LogHelper.WriteLog(this.GetType(), "文件结构:" + line);
line = reader.ReadLine();
}
// to remove the trailing '\n'
if (result.Length > 0 && result.ToString().LastIndexOf('\n') >= 0)
{
result.Remove(result.ToString().LastIndexOf('\n'), 1);
}
//得到全部目录
reader.Close();
response.Close();
if (result.Length < 1)
{
this.propUpdateDownloadStatus("无下载文件");
return null;
}
return result.ToString().Split('\n');
}
catch (Exception ex)
{
LogHelper.WriteLog(this.GetType(), uriPath + ":" + m_ftpUserName + ":" + m_ftpUserPwd + "\n" + ex.Message);
// System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
/// <summary>
/// 分析ftp信息列表:windows的dos模式目录
/// </summary>
/// <param name="resultlist"></param>
/// <returns></returns>
private bool analyzeFilelist(string[] resultlist)
{
if (resultlist == null)
{
return true;
}
var _directoryListStyle = (FtpCommon.GuessFileListStyle(resultlist));
for (int i = 0; i < resultlist.Length; i++)
{
fileprop finf;
//Temp = Msg[i].ToString().ToUpper().IndexOf("DIR");
FtpCommon.FileStruct fstruct;
switch (_directoryListStyle)
{
case FtpCommon.FileListStyle.UnixStyle:
if (resultlist[i].ToString().Length > 11)
{
fstruct = FtpCommon.ParseFileStructFromUnixStyleRecord(resultlist[i].ToString());
finf = new fileprop();
finf.fdate = fstruct.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
finf.fname = fstruct.Name;
finf.fsize = fstruct.Size;
finf.ftype = fstruct.IsDirectory ? "文件夹" : "文件";
}
else {
fstruct = FtpCommon.ParseFileStructFromWindowsStyleRecord(resultlist[i].ToString());
finf = new fileprop(_directoryListStyle, resultlist[i].ToString());
}
break;
case FtpCommon.FileListStyle.WindowsStyle:
finf = new fileprop(_directoryListStyle, resultlist[i].ToString());
fstruct = FtpCommon.ParseFileStructFromWindowsStyleRecord(resultlist[i].ToString());
break;
default:
fstruct = FtpCommon.ParseFileStructFromWindowsStyleRecord(resultlist[i].ToString());
finf = new fileprop(_directoryListStyle, resultlist[i].ToString());
break;
}
if (resultlist[i].ToString().Length > 11)
{
if (fstruct.IsDirectory || finf.ftype == "文件夹")
{
//Temp_Name = Msg[i].ToString().Substring(Temp+4).Trim();
m_Folderlist.Add(finf);
}
else
{
if (m_curFolder != null && m_curFolder.Length > 0)
finf.fname = m_curFolder + "/" + finf.fname;
m_filelist.Add(finf);
//BLDdownload_info.Append(finf.fname + " " + finf.fdate + "\n");
}
}
//debug
//if (i > 2000)
// break;
}
return true;
}
private bool doDownloadList()
{
bool downloadok = true;
try
{
if (!m_session.Opened)
{
m_session.Open(m_sessionOptions);
}
var ftpfilelist = m_session.ListDirectory(m_ftpDefaultUrl);
for (var i = 0; i <= ftpfilelist.Files.Count - 1; i++)
{
if (!ftpfilelist.Files[i].IsDirectory && Path.GetFileName(ftpfilelist.Files[i].FullName) != "..")
{
var finf = new fileprop();
finf.fdate = ftpfilelist.Files[i].LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
finf.fname = Path.GetFileName(ftpfilelist.Files[i].FullName);
finf.fullname = ftpfilelist.Files[i].FullName;
finf.fsize = ftpfilelist.Files[i].Length.ToString();
finf.ftype ="文件";
m_filelist.Add(finf);
}
else {
if (ftpfilelist.Files[i].Name != "..") {
var ftpfilelist2 = m_session.ListDirectory(ftpfilelist.Files[i].FullName);
for (var j = 0; j <= ftpfilelist2.Files.Count - 1; j++)
{
if (!ftpfilelist2.Files[j].IsDirectory&& ftpfilelist2.Files[j].Name!="..")
{
var finf = new fileprop();
finf.fdate = ftpfilelist2.Files[j].LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
finf.fname = ftpfilelist2.Files[j].Name;
finf.fullname = ftpfilelist2.Files[j].FullName;
finf.fsize = ftpfilelist2.Files[j].Length.ToString();
finf.ftype = "文件";
m_filelist.Add(finf);
}
}
}
}
}
}
catch (Exception e) {
LogHelper.WriteLog(typeof(ftptool), e.Message);
}
if (m_filelist.Count > 0)
{
//文件数
int i = 0;
int iFailure = 0;//失败文件数
int ncount = m_filelist.Count;
//按修改日期升序
string sql_pre = "INSERT INTO [t_op_seae_ftpfile_bc]([ftp_filename],[lastmodi_date] ,[filesize],[download_ok],[remark],local_path,download_date,ReportID,fileType) "
+ " VALUES ('{0}','{1}','{2}',{3},'{4}','{5}',getdate(),'{6}','{7}')";
string sql;
string sql_Analyze;
m_filelist.Sort();
DateTime dtmodi = DateTime.Today;
string localfileName = "";
foreach (fileprop fp in m_filelist)
{
sql_Analyze = "";
i++;
try
{
try
{
TSLabl_Info.Text = string.Format("{0}/{1}:{2}", i, ncount, fp.fname);
}
catch (Exception)
{
;
}
Application.DoEvents();
//var tmp1 = fp.fdate.Replace(" ", " ").Split(' ');
//DateTime dt1 = (tmp1[0].Length == 8) ? DateTime.ParseExact(tmp1[0], "MM-dd-yy", System.Globalization.CultureInfo.CurrentCulture) :
// DateTime.ParseExact(tmp1[0], "MM-dd-yyyy", System.Globalization.CultureInfo.CurrentCulture);
//TimeSpan tsp = tmp1[1].IndexOf('P') > 0 ? TimeSpan.Parse(tmp1[1].Substring(0, 5) + ":00") + TimeSpan.Parse("12:00")
// : TimeSpan.Parse(tmp1[1].Substring(0, 5) + ":00");
//dtmodi = dt1 + tsp;
//TODO:失败后如何处理???????
string dwnErr = "";
IsDate(fp.fdate, out dtmodi);
if (frmMailSet.FtpConfigSet().TimeZoneNum != 0)
{
dtmodi = dtmodi.AddHours(frmMailSet.FtpConfigSet().TimeZoneNum);
}
//检查要下载的文件是否操作失败次数
if (checkDownloadFtpFileOvermax(fp.fname))
{
//TSLabl_Info.Text += ":超过失败次数,跳过!";
propUpdateDownloadStatus(":下载文件失败");
iFailure++;
continue;
}
//报文类型:"ADVANCE" 不下载.不做处理.直接删除
// 不下载.不做处理.直接删除
string reporttype = GetReporType(Path.GetFileName(fp.fname));
if (reporttype == "ADVANCE" || reporttype == "CONTRL")
{
//Uri uri;
//uri = new Uri(m_ftpServer + System.Web.HttpUtility.UrlEncode("/" + fp.fname).Replace("+", "%20"));
//DeleteFtpFile(uri.AbsoluteUri);
try
{
m_session.RemoveFile(fp.fullname);
}
catch (Exception e) {
LogHelper.WriteLog(typeof(ftptool),"删除文件出错:"+ e.Message);
}
continue;
}
else
{
//
downloadok = downloadfile(fp.fname, fp.fullname, out localfileName, out dwnErr);
}
if (downloadok)
{
//清理失败记录
string sqlclear = "";
if (m_downloaderrList.Keys.Contains(fp.fname))
{
string reportid = m_downloaderrList[fp.fname].ID;
sqlclear = string.Format("delete from t_op_seae_ftpfile_bc where ReportID='{0}'; ", reportid);
m_downloaderrList.Remove(fp.fname);
}
string newreportid = NewGUID();
//
//
sql = sqlclear + string.Format(sql_pre, fp.fname, dtmodi, fp.fsize, downloadok ? 1 : 0, dwnErr, m_localpath, newreportid, GetReporType(fp.fname));
int iresult = MailAnalyzeTools.DbHelperSQL.ExecuteSql(sql);
string analyinfo = "";
//业务分析
string realfilepath = m_localpath + "\\" + localfileName;
bool dealok = true; ;
string guadanPath;
switch (reporttype)
{
case "IFTMBC":
dealok = AnalyzeBCEdi_InsertSql(realfilepath, newreportid, out analyinfo, realfilepath, dtmodi);
UpdateFTPDealState(dealok, newreportid, analyinfo, "");
break;
case "APERAK":
dealok = AnalyzeAPERAKEdi_InsertSql(realfilepath, newreportid, out analyinfo, realfilepath, dtmodi);
//UpdateFTPDealState(dealok, newreportid, analyinfo, "");
break;
case "INVOIC":
// ImportEdiFeeList
dealok = AnalyzeInvoice_InsertSql(realfilepath, newreportid, dtmodi, out analyinfo);
//插入
UpdateFTPDealState(dealok, newreportid, analyinfo, "");
break;
case "SEAWAY": //挂单并生成任务 //FTP 不在生成任务,改成从邮件接收 程建波 2017-12-08
//// 生成任务
//dealok = AnalyzeBLEdi_InsertSql(realfilepath, newreportid, out analyinfo);
//if (dealok)
//{
// bool cpok1 = GuadanTool.FTPAnalyzeAndGuadan(realfilepath, newreportid, out analyinfo, out guadanPath);
// if (cpok1)
// {
// UpdateFTPDealState(dealok, newreportid, analyinfo, guadanPath);
// UpdateTaskFilePath(guadanPath, 1, newreportid);
// }
//}
//else
//{
// LogHelper.WriteLog(typeof(ftptool), analyinfo);
//}
break;
case "APPROVED":
dealok = GuadanTool.FTPAnalyzeAndGuadan(realfilepath, newreportid, out analyinfo, out guadanPath);
UpdateFTPDealState(dealok, newreportid, analyinfo, guadanPath);
break;
// case "ADVANCE":
//bl 只有正本才生成任务
case "ORIGINAL":
dealok = AnalyzeBLEdi_InsertSql(realfilepath, newreportid, out analyinfo);
if (dealok)
{
// 挂单 --nass server,手动执行
UpdateFTPDealState(dealok, newreportid, analyinfo, "");
//复制副本到nass服务器,并更新任务的文件路径
string nassFilePath;
bool cpok = GuadanTool.UpLoadFileToNass("Task\\ftp", realfilepath, newreportid, reporttype, out nassFilePath);
if (cpok)
{
UpdateTaskFilePath(nassFilePath, 1, newreportid);
}
}
else
{
LogHelper.WriteLog(typeof(ftptool), analyinfo);
}
break;
default:
break;
}
if (!string.IsNullOrEmpty(analyinfo))
{
dwnErr = string.IsNullOrEmpty(dwnErr) ? analyinfo : dwnErr + analyinfo;
}
}
else
{
iFailure++;
if (m_downloaderrList.Keys.Contains(fp.fname))
{
m_downloaderrList[fp.fname].FailurCount += 1;
sql = string.Format("update t_op_seae_ftpfile_bc set [download_date]=getdate(),[download_failuretimes]=[download_failuretimes]+1,[remark]='{1}' "
+ " where download_ok=0 and ftp_filename='{0}' ", fp.fname);
MailAnalyzeTools.DbHelperSQL.ExecuteSql(sql);
}
//else
//{
// DLDFilestruct fstrut = new DLDFilestruct(NewGUID());
// fstrut.FailurCount=1;
// fstrut.FileName=fp.fname;
// sql = string.Format(sql_pre, fp.fname, dtmodi, fp.fsize, 0, "下载文件失败:" + dwnErr, localpath, fstrut.ID, GetReporType(fp.fname));
// m_downloaderrList.Add(fp.fname,fstrut);
//}
//TSLabl_Info.Text += ":下载文件失败"
propUpdateDownloadStatus(":下载文件失败");
}
}
catch (Exception ex)
{
//DLDFilestruct fstrut = new DLDFilestruct(NewGUID());
//sql = string.Format(sql_pre, fp.fname, dtmodi, fp.fsize, 0, ex.Message, "", fstrut.ID, GetReporType(fstrut.FileName));
System.Diagnostics.Trace.Write(ex.Message);
LogHelper.WriteLog(typeof(ftptool), ex);
downloadok = false;
}
}//end for
// TSLabl_Info.Text = string.Format("成功{0}/共{1} ", (i-iFailure), ncount );
propUpdateDownloadStatus(string.Format("成功{0}/共{1} ", (i - iFailure), ncount));
}
return downloadok;
}
//private bool doDownloadList2()
//{
// bool downloadok = true;
// if (m_filelist.Count > 0)
// {
// //文件数
// int i = 0;
// int iFailure = 0;//失败文件数
// int ncount = m_filelist.Count;
// //按修改日期升序
// string sql_pre = "INSERT INTO [t_op_seae_ftpfile_bc]([ftp_filename],[lastmodi_date] ,[filesize],[download_ok],[remark],local_path,download_date,ReportID,fileType) "
// + " VALUES ('{0}','{1}','{2}',{3},'{4}','{5}',getdate(),'{6}','{7}')";
// string sql;
// string sql_Analyze;
// m_filelist.Sort();
// DateTime dtmodi = DateTime.Today;
// string localfileName = "";
// foreach (fileprop fp in m_filelist)
// {
// sql_Analyze = "";
// i++;
// try
// {
// try
// {
// TSLabl_Info.Text = string.Format("{0}/{1}:{2}", i, ncount, fp.fname);
// }
// catch (Exception)
// {
// ;
// }
// Application.DoEvents();
// //var tmp1 = fp.fdate.Replace(" ", " ").Split(' ');
// //DateTime dt1 = (tmp1[0].Length == 8) ? DateTime.ParseExact(tmp1[0], "MM-dd-yy", System.Globalization.CultureInfo.CurrentCulture) :
// // DateTime.ParseExact(tmp1[0], "MM-dd-yyyy", System.Globalization.CultureInfo.CurrentCulture);
// //TimeSpan tsp = tmp1[1].IndexOf('P') > 0 ? TimeSpan.Parse(tmp1[1].Substring(0, 5) + ":00") + TimeSpan.Parse("12:00")
// // : TimeSpan.Parse(tmp1[1].Substring(0, 5) + ":00");
// //dtmodi = dt1 + tsp;
// //TODO:失败后如何处理???????
// string dwnErr = "";
// IsDate(fp.fdate, out dtmodi);
// if (frmMailSet.FtpConfigSet().TimeZoneNum != 0)
// {
// dtmodi = dtmodi.AddHours(frmMailSet.FtpConfigSet().TimeZoneNum);
// }
// //检查要下载的文件是否操作失败次数
// if (checkDownloadFtpFileOvermax(fp.fname))
// {
// //TSLabl_Info.Text += ":超过失败次数,跳过!";
// propUpdateDownloadStatus(":下载文件失败");
// iFailure++;
// continue;
// }
// //报文类型:"ADVANCE" 不下载.不做处理.直接删除
// // 不下载.不做处理.直接删除
// string reporttype = GetReporType(fp.fname);
// if (reporttype == "ADVANCE" || reporttype == "CONTRL")
// {
// Uri uri;
// uri = new Uri(m_ftpServer + System.Web.HttpUtility.UrlEncode("/" + fp.fname).Replace("+", "%20"));
// DeleteFtpFile(uri.AbsoluteUri);
// continue;
// }
// else
// {
// //
// downloadok = downloadfile(fp.fname, out localfileName, out dwnErr);
// }
// if (downloadok)
// {
// //清理失败记录
// string sqlclear = "";
// if (m_downloaderrList.Keys.Contains(fp.fname))
// {
// string reportid = m_downloaderrList[fp.fname].ID;
// sqlclear = string.Format("delete from t_op_seae_ftpfile_bc where ReportID='{0}'; ", reportid);
// m_downloaderrList.Remove(fp.fname);
// }
// string newreportid = NewGUID();
// //
// //
// sql = sqlclear + string.Format(sql_pre, fp.fname, dtmodi, fp.fsize, downloadok ? 1 : 0, dwnErr, m_localpath, newreportid, GetReporType(fp.fname));
// int iresult = MailAnalyzeTools.DbHelperSQL.ExecuteSql(sql);
// string analyinfo = "";
// //业务分析
// string realfilepath = m_localpath + "\\" + localfileName;
// bool dealok = true; ;
// string guadanPath;
// switch (reporttype)
// {
// case "IFTMBC":
// dealok = AnalyzeBCEdi_InsertSql(realfilepath, newreportid, out analyinfo, realfilepath, dtmodi);
// UpdateFTPDealState(dealok, newreportid, analyinfo, "");
// break;
// case "INVOIC":
// // ImportEdiFeeList
// dealok = AnalyzeInvoice_InsertSql(realfilepath, newreportid, dtmodi, out analyinfo);
// //插入
// UpdateFTPDealState(dealok, newreportid, analyinfo, "");
// break;
// case "SEAWAY": //挂单并生成任务 //FTP 不在生成任务,改成从邮件接收 程建波 2017-12-08
// //// 生成任务
// //dealok = AnalyzeBLEdi_InsertSql(realfilepath, newreportid, out analyinfo);
// //if (dealok)
// //{
// // bool cpok1 = GuadanTool.FTPAnalyzeAndGuadan(realfilepath, newreportid, out analyinfo, out guadanPath);
// // if (cpok1)
// // {
// // UpdateFTPDealState(dealok, newreportid, analyinfo, guadanPath);
// // UpdateTaskFilePath(guadanPath, 1, newreportid);
// // }
// //}
// //else
// //{
// // LogHelper.WriteLog(typeof(ftptool), analyinfo);
// //}
// break;
// case "APPROVED":
// dealok = GuadanTool.FTPAnalyzeAndGuadan(realfilepath, newreportid, out analyinfo, out guadanPath);
// UpdateFTPDealState(dealok, newreportid, analyinfo, guadanPath);
// break;
// // case "ADVANCE":
// //bl 只有正本才生成任务
// case "ORIGINAL":
// dealok = AnalyzeBLEdi_InsertSql(realfilepath, newreportid, out analyinfo);
// if (dealok)
// {
// // 挂单 --nass server,手动执行
// UpdateFTPDealState(dealok, newreportid, analyinfo, "");
// //复制副本到nass服务器,并更新任务的文件路径
// string nassFilePath;
// bool cpok = GuadanTool.UpLoadFileToNass("Task\\ftp", realfilepath, newreportid, reporttype, out nassFilePath);
// if (cpok)
// {
// UpdateTaskFilePath(nassFilePath, 1, newreportid);
// }
// }
// else
// {
// LogHelper.WriteLog(typeof(ftptool), analyinfo);
// }
// break;
// default:
// break;
// }
// if (!string.IsNullOrEmpty(analyinfo))
// {
// dwnErr = string.IsNullOrEmpty(dwnErr) ? analyinfo : dwnErr + analyinfo;
// }
// }
// else
// {
// iFailure++;
// if (m_downloaderrList.Keys.Contains(fp.fname))
// {
// m_downloaderrList[fp.fname].FailurCount += 1;
// sql = string.Format("update t_op_seae_ftpfile_bc set [download_date]=getdate(),[download_failuretimes]=[download_failuretimes]+1,[remark]='{1}' "
// + " where download_ok=0 and ftp_filename='{0}' ", fp.fname);
// MailAnalyzeTools.DbHelperSQL.ExecuteSql(sql);
// }
// //else
// //{
// // DLDFilestruct fstrut = new DLDFilestruct(NewGUID());
// // fstrut.FailurCount=1;
// // fstrut.FileName=fp.fname;
// // sql = string.Format(sql_pre, fp.fname, dtmodi, fp.fsize, 0, "下载文件失败:" + dwnErr, localpath, fstrut.ID, GetReporType(fp.fname));
// // m_downloaderrList.Add(fp.fname,fstrut);
// //}
// //TSLabl_Info.Text += ":下载文件失败"
// propUpdateDownloadStatus(":下载文件失败");
// }
// }
// catch (Exception ex)
// {
// //DLDFilestruct fstrut = new DLDFilestruct(NewGUID());
// //sql = string.Format(sql_pre, fp.fname, dtmodi, fp.fsize, 0, ex.Message, "", fstrut.ID, GetReporType(fstrut.FileName));
// System.Diagnostics.Trace.Write(ex.Message);
// LogHelper.WriteLog(typeof(ftptool), ex);
// downloadok = false;
// }
// }//end for
// // TSLabl_Info.Text = string.Format("成功{0}/共{1} ", (i-iFailure), ncount );
// propUpdateDownloadStatus(string.Format("成功{0}/共{1} ", (i - iFailure), ncount));
// }
// return downloadok;
//}
public static bool IsDate(string sValue, out DateTime dt)
{
dt = DateTime.Today;
try
{
sValue = sValue.Replace(" ", " ");
Regex re = new Regex(@"^((\d{4}))\/(|(0[1-9])|(1[0-2]))\/((0[1-9])|(1\d)|(2\d)|(3[0-1]))$");
Regex re2 = new Regex(@"^((\d{4}))\-(|(0[1-9])|(1[0-2]))\-((0[1-9])|(1\d)|(2\d)|(3[0-1]))$");
var tmp1 = sValue.Split(' ');
DateTime dt1;
if (re2.IsMatch(sValue))
{
dt1 = (tmp1[0].Length == 8) ? DateTime.ParseExact(tmp1[0], "MM-dd-yy", System.Globalization.CultureInfo.CurrentCulture) :
DateTime.ParseExact(tmp1[0], "MM-dd-yyyy", System.Globalization.CultureInfo.CurrentCulture);
}
else if (re.IsMatch(sValue))
{
dt1 = (tmp1[0].Length == 8) ? DateTime.ParseExact(tmp1[0], "MM/dd/yy", System.Globalization.CultureInfo.CurrentCulture) :
DateTime.ParseExact(tmp1[0], "MM/dd/yyyy", System.Globalization.CultureInfo.CurrentCulture);
}
else
{
dt1 = DateTime.Parse(tmp1[0]);
}
TimeSpan tsp = tmp1[1].IndexOf('P') > 0 ? TimeSpan.Parse(tmp1[1].Substring(0, 5) + ":00") + TimeSpan.Parse("12:00")
: TimeSpan.Parse(tmp1[1].Substring(0, 5) + ":00");
dt = dt1 + tsp;
return re.IsMatch(sValue) || re2.IsMatch(sValue);
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message.ToString());
return false;
}
}
private string NewGUID()
{
return System.Guid.NewGuid().ToString("N");
}
/// <summary>
/// 分析BC报文
/// </summary>
/// <param name="filename"></param>
/// <param name="rptid"></param>
/// <param name="errorinfo"></param>
/// <param name="realfilepath">电子文档路径</param>
/// <param name="dtmodi">任务生成时间</param>
/// <returns></returns>
private bool AnalyzeBCEdi_InsertSql(string filename, string rptid, out string errorinfo, string realfilepath, DateTime dtmodi)
{
string analyzesql = "";
errorinfo = "";
bool isok = true;
try
{
//获得BC报文内容到实体类
TOp_seae_edi_rp_iftmbc iftmbc = new TOp_seae_edi_rp_iftmbc();
iftmbc.F_Base_ReportID = rptid;
string debugstr = MaskEdiAnalyzeTool.ImportBCEdiList(filename, iftmbc);
analyzesql = iftmbc.GetInsertSql();
if (string.IsNullOrEmpty(analyzesql))
{
errorinfo = "无法正确分析BC报文:请确认此报文是否正确!";
return false;
}
try
{
//插入报文内容
int iresut = MailAnalyzeTools.DbHelperSQL.ExecuteSql(analyzesql);
isok = (iresut > 0);
TOP_Task optsk = new TOP_Task();
//与系统中的数据进行对比
StringBuilder bldContrastInfo;
//Seae表[运费协议号]
string yfxyh;
//委托单位
string wtdw;
bool isContrastBc = BcContrastSea(iftmbc, out bldContrastInfo, optsk,out yfxyh,out wtdw);
errorinfo += bldContrastInfo.ToString();
//01 任务编号 --
//06 任务说明 --
//09 任务开始时间 --
//13 提单号 --
//14 文件编号 --
//16 电子档案路径 --?
//17 是否公共
//18 任务相关人员
//19 SEA编号
string updateSqlBcMatch;
if (!isContrastBc)
{
//FTP的BC报文不生成任务,只有邮件才生成任务
//检查有无时间匹配的任务:查询条件为 提单号和 任务开始时间(时间差小于20分钟)
updateSqlBcMatch = "update t_op_seae_edi_rp_iftmbc set F_EXT_IsmatchBusi=0,F_EXT_IsmatchBusiRemark= " + StrUtill.GetValueString(bldContrastInfo.ToString(), 190)
+ string.Format("where F_Base_ReportID ='{0}'", rptid);
int irst = DbHelperSQL.ExecuteSql(updateSqlBcMatch);
if (irst < 0)
{
LogHelper.WriteLog("更新 t_op_seae_edi_rp_iftmbc 是否匹配状态失败: ", updateSqlBcMatch);
}
}
else
{
updateSqlBcMatch = " update t_op_seae_edi_rp_iftmbc set F_EXT_IsmatchBusi=1,F_EXT_IsmatchBusiRemark= " + StrUtill.GetValueString(bldContrastInfo.ToString(), 190)
+ string.Format(" where F_Base_ReportID ='{0}'", rptid);
int irst = DbHelperSQL.ExecuteSql(updateSqlBcMatch);
if (irst < 0)
{
LogHelper.WriteLog("更新 t_op_seae_edi_rp_iftmbc 是否匹配状态失败: ", updateSqlBcMatch);
}
//是否增加已处理完毕的状态????? .....
//检查邮件
//根据提单号和与邮件对照报文对照,如果邮件任务已经处理完毕,则忽略
}
//todo 上线测试时,严格按照时间偏差
int pc_minutes = 3;
string sql = @" select top 1 * from
(
select top 3 datediff(MI,t.任务开始时间,cast('{1}' as datetime )) as f_difminutes, * from t_op_task t where t.任务类型 in ('bc','ba','bcl')
and 提单号 ='{0}'
and 是否公共=0
) v where ABS(v.f_difminutes)< " + pc_minutes.ToString() + " order by ABS(v.f_difminutes) ";
try
{
DataTable dttsk = DbHelperSQL.QueryTable(string.Format(sql, iftmbc.F_RFF_BN, dtmodi.ToString("yyyy-MM-dd HH:mm:ss")));
if (dttsk == null || dttsk.Rows.Count < 1)
{
return isok;
}
//如果任务里找到了邮件任务 做什么? --->转发邮件
//更新reportid 到任务里面的reportid字段,判断任务状态
sql = string.Format("update t_op_task set 文件编号='{1}' where 任务编号='{0}'", dttsk.Rows[0]["任务编号"], rptid);
int irst = DbHelperSQL.ExecuteSql(sql);
if (irst > 0)
{
//自动转发邮件
//rmMailSet.BcMailAutoForword() 配置
//1.判断是否是BC,只有BC才自动转发未完成的才自动转发
// 2.自动转发 要判断邮件是否符合自动转发,邮件状态是否已经完成,邮件任务类型?????
//3.判断是否含有MSDS关键字
//4.合约号和运费协议号是否一致
//自动转发任务中增加任务ID,成功后更新任务中的状态!!!
// cjb 补充 frmMailSet.BcMailAutoForword()的条件 2018-04-02
optsk = GetOpTask(dttsk);
if (optsk.F_03RWLX == "BC" && optsk.F_21SFWC == 0 && isContrastBc &&frmMailSet.BcMailAutoForword()) //2018-03-28 cjb 补充 isContrastBc
{
//不含有MSDS关键字并且未结束的任务
sql = "select F_isMsds,F_HYH from t_op_seae_edi_mail_bcinfo b where F_Base_MailID='" + optsk.F_15YJBH +"' and F_isMsds=0;";
DataTable dttmp = DbHelperSQL.QueryTable(sql);
if (dttmp != null && dttmp.Rows.Count > 0)
{
//运费协议号比较
string yhxyh2 = dttmp.Rows[0]["F_HYH"].ToString();
if (yfxyh == yhxyh2)
{
//增加一次判断:电子档案路径是否在已发送列表中
//检查是否已经存在发件记录中
try
{
string sqlcheck = @"select t.任务编号 from t_op_task t where t.任务编号='{0}'
and exists(select m.attachment from t_op_seae_edi_send_mailbox m where
DATEDIFF(DAY,m.createdate, GETDATE())<3 and cast(t.电子档案路径 as varchar(200) )=cast(m.attachment as varchar(200)))";
DataTable dttmp2 = DbHelperSQL.QueryTable(string.Format(sqlcheck, optsk.F_01RWBH));
if (dttmp2 != null && dttmp2.Rows.Count > 0)
{
return true;
}
}
catch (Exception ex)
{
LogHelper.WriteLog("检查是否已自动转发了该邮件出错:ftp691", ex.Message);
}
TOp_seae_edi_mail edimail= GetEdiMail(optsk.F_15YJBH);
//DEBUG
bool isdebugsend = false;
//读取邮件信息,然后转发
if (wtdw != ""&&edimail!=null)
{
if (!frmAnalyzeMail.SendbyYJFang_an(wtdw, optsk, edimail, isdebugsend))
{
//
LogHelper.WriteLog(string.Format("ftp-->文件编号:{0}/邮件编号:{1}BC类邮件自动转发失败", rptid, optsk.F_15YJBH), "自动转发邮件失败");
}
else
{
//调试,不自动发送bc邮件时不挂单 cjb 2018-04-02
// if (isdebugsend)
// {
// return true;
// }
//挂单路径
string tarpath;
//执行挂单
bool guadanok = true;
try
{
guadanok = GuadanTool.Guadan(optsk.F_13TDH, optsk.F_19SEABH, "入货通知", optsk.F_16DZDALJ, out tarpath, true);
}
catch (Exception ex )
{
LogHelper.WriteLog("收到BC报文后挂单失败 :ftp 694", ex.Message);
}
sql = string.Format("update t_op_task set 任务状态='已转发',是否完成=1,完成方式='自动', 操作人='DEMO-SA',完成时间=GETDATE() where 任务编号='{0}'", optsk.F_01RWBH);
try
{
DbHelperSQL.ExecuteSql(sql);
LogHelper.WriteLog( "收到BC报文后,ftp更新t_op_task状态OK : "+ optsk.F_13TDH , sql);
}
catch (Exception ex)
{
LogHelper.WriteLog("收到BC报文后,更新t_op_task状态失败 :ftp 708", ex.Message);
}
}//end if 发送成功
} // end --〉 (wtdw != ""&&edimail!=null)
}// end --〉(yfxyh == yhxyh2)
}
}
}
}
catch (Exception ex)
{
errorinfo = "分析BC结果出错651:" + ex.Message;
LogHelper.WriteLog("分析BC结果出错662,", " 请参见下面的信息:");
LogHelper.WriteLog(typeof(ftptool), ex);
}
}
catch (Exception ex)
{
errorinfo = "分析BC结果出错651:" + ex.Message;
LogHelper.WriteLog("分析BC结果出错651,", " 请参见下面的信息:");
LogHelper.WriteLog(typeof(ftptool), ex);
}
}
catch (Exception ex)
{
errorinfo = "分析BC发生异常:" + ex.Message;
}
return isok;
}
/// <summary>
/// 分析BC报文
/// </summary>
/// <param name="filename"></param>
/// <param name="rptid"></param>
/// <param name="errorinfo"></param>
/// <param name="realfilepath">电子文档路径</param>
/// <param name="dtmodi">任务生成时间</param>
/// <returns></returns>
private bool AnalyzeAPERAKEdi_InsertSql(string filename, string rptid, out string errorinfo, string realfilepath, DateTime dtmodi)
{
string analyzesql = "";
errorinfo = "";
bool isok = true;
try
{
//获得BC报文内容到实体类
Opseae_edi_apk iftmbc = new Opseae_edi_apk();
string debugstr = MaskEdiAnalyzeTool.ImportAPKEdiList(filename, iftmbc);
if (string.IsNullOrEmpty(iftmbc.BN))
{
errorinfo = "无法正确分析APK报文:请确认此报文是否正确!";
return false;
}
try
{
//var sql = "select top 1 邮箱 from t_sys_employee where 姓名 in (select 操作员 from t_op_seae where 主提单号='"+ iftmbc.BN + "')";
//DataTable dttmp = DbHelperSQL.QueryTable(sql);
string emailaddr = "MSKSMART@SDSMARTLOGISTICS.COM";
//if (dttmp != null && dttmp.Rows.Count > 0)
//{
// //运费协议号比较
// emailaddr = dttmp.Rows[0]["邮箱"].ToString();
//}
if (!string.IsNullOrEmpty(emailaddr))
{
analyzesql = " insert into Mail_Send(GID,SendTo,Title,Body,SendStatus,CreateTime,TryCount,SmtpConfig) "
+" values(newid(), '"+ emailaddr + "', 'BOOKING ACKNOWLEDGEMENT "+ iftmbc.BN + "', 'Booking no(s)."+ iftmbc.BN + " have been successfully received. "+ iftmbc.STATUS + "', 'Create', GETDATE(), 0, 1)";
int iresut = MailAnalyzeTools.DbHelperSQL.ExecuteSql(analyzesql);
isok = (iresut > 0);
}
}
catch (Exception ex)
{
errorinfo = "分析APK结果出错651:" + ex.Message;
LogHelper.WriteLog("分析APK结果出错651,", " 请参见下面的信息:");
LogHelper.WriteLog(typeof(ftptool), ex);
}
}
catch (Exception ex)
{
errorinfo = "分析APK发生异常:" + ex.Message;
}
return isok;
}
/// <summary>
/// 获得任务实体
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
internal static TOP_Task GetOpTask(DataTable dt)
{
TOP_Task tsk = new TOP_Task();
if (dt.Rows.Count > 0)
{
//pl_id
//任务编号
//上级任务号
//任务类型
//任务来源
//任务状态
//任务说明
//发起人
//录入日期
//任务开始时间
//完成方式
//完成时间
//KPI值
//提单号
//文件编号
//邮件编号
//电子档案路径
//是否公共
//任务相关人员
//SEA编号
//操作人
//是否完成
//备注
tsk.F_01RWBH = dt.Rows[0]["任务编号"].ToString();
tsk.F_03RWLX = dt.Rows[0]["任务类型"].ToString();
tsk.F_13TDH = dt.Rows[0]["提单号"].ToString();
tsk.F_14WJBH = dt.Rows[0]["文件编号"]==null?"": dt.Rows[0]["文件编号"].ToString();
tsk.F_15YJBH = dt.Rows[0]["邮件编号"].ToString();
tsk.F_16DZDALJ = dt.Rows[0]["电子档案路径"] == null ? "" : dt.Rows[0]["电子档案路径"].ToString();
tsk.F_17SFGG = dt.Rows[0]["是否公共"].ToString() == "1" ? true : false;
tsk.F_18RWXGRY = dt.Rows[0]["任务相关人员"] == null ? "" : dt.Rows[0]["任务相关人员"].ToString();
tsk.F_19SEABH = dt.Rows[0]["SEA编号"] == null ? "" : dt.Rows[0]["SEA编号"].ToString();
tsk.F_21SFWC = dt.Rows[0]["是否完成"].ToString() == "1" ? 1 : 0;
}
return tsk;
}
/// <summary>
/// 获得邮件实体
/// </summary>
/// <param name="mailid"></param>
/// <returns></returns>
internal static TOp_seae_edi_mail GetEdiMail(string mailid)
{
TOp_seae_edi_mail edimail = null;
string sql = string.Format(" select [邮件ID],[邮件主题],[邮件内容],[附件名称] from t_op_seae_edi_mail where 邮件ID='{0}'; ", mailid);
DataTable dt = DbHelperSQL.QueryTable(sql);
if (dt != null && dt.Rows.Count > 0)
{
//F_01_YJID ,[邮件ID]
//F_03_YJZT ,[邮件主题]
//F_03_YJNR ,[邮件内容]
//F_05_FJMC ,[附件名称]
edimail = new TOp_seae_edi_mail();
edimail.F_01_YJID = dt.Rows[0]["邮件ID"].ToString();
edimail.F_03_YJZT = dt.Rows[0]["邮件主题"].ToString();
edimail.F_03_YJNR = dt.Rows[0]["邮件内容"] == DBNull.Value ? "" : dt.Rows[0]["邮件内容"].ToString();
edimail.F_05_FJMC = dt.Rows[0]["附件名称"]==DBNull.Value?"": dt.Rows[0]["附件名称"].ToString();
}
return edimail;
}
/// <summary>
/// BC报文与业务系统数据对比
/// </summary>
/// <param name="iftmbc"></param>
/// <param name="bldErrorInfo"></param>
/// <param name="yfxyh1">T_OP_SEAE表中的[运费协议号]</param>
/// <param name="wtdw"></param>
/// <returns></returns>
private bool BcContrastSea(TOp_seae_edi_rp_iftmbc iftmbc, out StringBuilder bldErrorInfo, TOP_Task tsk,out string yfxyh1,out string wtdw)
{
bool isContrastOK = true;
yfxyh1 = "";
wtdw="";
//对比情况
bldErrorInfo = new StringBuilder();
//0 如果是拒绝状态,则直接不允许转发 程建波2018-03-29
if (iftmbc.F_BW_BGM != "接受")
{
bldErrorInfo.AppendLine(string.Format("BC状态:") + iftmbc.F_BW_BGM);
isContrastOK = false;
}
//1.检查提单号是否在系统中
string sql = "select distinct top 1 t.运输条款,t.装港代码,t.卸货代码,t.运费协议号,t.客服员,t.编号 as SEA编号,t.开船日期, t.委托单位,t.设置温度,t.冷藏通风量 from t_op_seae t where t.主提单号='{0}' and 业务类型='普通货' ";
DataTable tbl = DbHelperSQL.QueryTable(string.Format(sql, iftmbc.F_RFF_BN));
if (tbl == null || tbl.Rows.Count < 1)
{
bldErrorInfo.AppendLine(string.Format("订舱号{0}在业务系统中未找到", iftmbc.F_RFF_BN));
tsk.F_18RWXGRY = "";
tsk.F_19SEABH = "";
tsk.F_17SFGG = true;
isContrastOK = false;
return isContrastOK;
}
tsk.F_18RWXGRY = tbl.Rows[0]["客服员"] == DBNull.Value ? "" : tbl.Rows[0]["客服员"].ToString();
tsk.F_19SEABH = tbl.Rows[0]["SEA编号"].ToString();
//运费协议号
yfxyh1 = tbl.Rows[0]["运费协议号"] == DBNull.Value ? "" : tbl.Rows[0]["运费协议号"].ToString();
//委托单位
wtdw = tbl.Rows[0]["委托单位"] == DBNull.Value ? "" : tbl.Rows[0]["委托单位"].ToString();
//相关人员为空则为公共
tsk.F_17SFGG = !string.IsNullOrEmpty(tsk.F_18RWXGRY);
//2.对比
//对比温度
string mysql = "select distinct top 1 t.湿度,t.设置温度,t.冷藏通风量 from t_op_seae t where t.主提单号='{0}' and 业务类型='普通货' and 货物标识='R' ";
DataTable mytbl = DbHelperSQL.QueryTable(string.Format(mysql, iftmbc.F_RFF_BN));
if (mytbl != null && mytbl.Rows.Count > 0)
{
string LocTemp1 = iftmbc.F_WP_TMP.Trim();
string LocTemp2 = mytbl.Rows[0]["设置温度"] == DBNull.Value ? "" : mytbl.Rows[0]["设置温度"].ToString();
double temp1 = Convert.ToDouble(LocTemp1 == "" ? "0" : LocTemp1);
double temp2 = Convert.ToDouble(LocTemp2 == "" ? "0" : LocTemp2);
if (temp1 !=temp2)
{
bldErrorInfo.AppendLine(string.Format("温度与业务系统不一致:{0}~{1}", LocTemp1, LocTemp2));
isContrastOK = false;
}
}
//2.1 对比运输条款/交接方式
string cycy1 = iftmbc.F_TSR_TSR.Trim();
string cycy2 = tbl.Rows[0]["运输条款"] == DBNull.Value ? "" : tbl.Rows[0]["运输条款"].ToString();
if (cycy1 != cycy2)
{
if (cycy1.Replace("或其他", "") != cycy2.Replace("或其他", ""))
{
bldErrorInfo.AppendLine(string.Format("运输条款与业务系统不一致:{0}~{1}", cycy1, cycy2));
isContrastOK = false;
}
}
//2.2 装货港代码
string LocZ1 = iftmbc.F_DC0_LOC_ZAddrCode.Trim();
string LocZ2 = tbl.Rows[0]["装港代码"] == DBNull.Value ? "" : tbl.Rows[0]["装港代码"].ToString();
if (LocZ1 != LocZ2)
{
bldErrorInfo.AppendLine(string.Format("装港代码与业务系统不一致:{0}~{1}", LocZ1, LocZ2));
isContrastOK = false;
}
//2.3 卸货代码
string LocX1 = iftmbc.F_DC0_LOC_XAddrCode.Trim();
string LocX1b = iftmbc.F_DC1_LOC_XAddrCode==null?"":iftmbc.F_DC1_LOC_XAddrCode.Trim();
string LocX1c = iftmbc.F_DC2_LOC_XAddrCode == null ? "" : iftmbc.F_DC2_LOC_XAddrCode.Trim();
string LocX2 = tbl.Rows[0]["卸货代码"] == DBNull.Value ? "" : tbl.Rows[0]["卸货代码"].ToString();
//卸货港比较1程/2程/3程卸货港 2018-02-26
if ((LocX1 == LocX2 || LocX1b == LocX2 || LocX1c == LocX2 )==false)
{
if (!string.IsNullOrEmpty(LocX1b))
{
LocX1 += "," + LocX1b;
}
if (!string.IsNullOrEmpty(LocX1c))
{
LocX1 += "," + LocX1c;
}
bldErrorInfo.AppendLine(string.Format("卸货代码与业务系统不一致:{0}~{1}", LocX1, LocX2));
isContrastOK = false;// 程建波 2018-03-30
}
//2.4 约号/合同号/运输协议号
//不再对比BC里的运费协议号 cjb 2018-03-20
//string ct1 = iftmbc.F_RFF_CT == null ? "" : iftmbc.F_RFF_CT.Trim();
//string ct2 = tbl.Rows[0]["运费协议号"] == DBNull.Value ? "" : tbl.Rows[0]["运费协议号"].ToString().Trim();
//if (ct1 != ct2)
//{
// bldErrorInfo.AppendLine(string.Format("约号(合同号)与业务系统运费协议号不一致:{0}~{1}", ct1, ct2));
// isContrastOK = false;
//}
//开船日期
string kcrq1 = iftmbc.F_DC0_DTM133 == null ? "" : (iftmbc.F_DC0_DTM133.Length >= 8 ? iftmbc.F_DC0_DTM133.Substring(0, 8) : iftmbc.F_DC0_DTM133);
string kcrq2 = tbl.Rows[0]["开船日期"] == DBNull.Value ? "" : DateTime.Parse(tbl.Rows[0]["开船日期"].ToString()).ToString("yyyyMMdd");
if (kcrq1!=kcrq2)
{
bldErrorInfo.AppendLine(string.Format("开船日期与业务系统中开船日期不一致:{0}~{1}", kcrq1, kcrq2));
isContrastOK = false;
}
//2.5 对比型号和数量
sql = @"select vtj.编号,vtj.主提单号,vtj.EDI代码, sum(数量) as 数量 from
( select v0.*,cctn.EDI代码 from
( SELECT ctn.[编号],s.主提单号,[数量],[表现形式]
FROM (select te.编号,te.主提单号 from t_op_seae te where 业务类型='普通货' AND 主提单号='{0}') s
join [dbo].[t_op_ctn] ctn on ctn.编号=s.编号) v0 join t_code_ctn cctn on v0.表现形式=cctn.表现形式
) vtj group by vtj.编号,vtj.主提单号,vtj.EDI代码";
tbl = DbHelperSQL.QueryTable(string.Format(sql, iftmbc.F_RFF_BN));
//
if (tbl == null || tbl.Rows.Count < 1)
{
bldErrorInfo.AppendLine(string.Format("{0}在业务系统中的箱型信息不存在!", iftmbc.F_RFF_BN));
isContrastOK = false;
}
string[] listXXXL = iftmbc.F_WP_EQN_Type_Num.Split(' ');
if (listXXXL.Count() != tbl.Rows.Count)
{
//箱型不一致
bldErrorInfo.AppendLine(string.Format("{0}的箱型信息{1}与业务系统中的箱型信息不一致!", iftmbc.F_RFF_BN, iftmbc.F_WP_EQN_Type_Num));
isContrastOK = false;
}
else
{
//查找业务系统中的箱型和箱数是否与报文一致
string[] listXXXL2 = new string[tbl.Rows.Count];
int jCRstOk = 0;
for (int i = 0; i < tbl.Rows.Count; i++)
{
string tmp = tbl.Rows[i]["EDI代码"].ToString() + "*" + tbl.Rows[i]["数量"].ToString();
listXXXL2[i] = tmp;
if (listXXXL.Contains(tmp))
{
jCRstOk++;
}
else
{
//兼容22G0-->22G1
// 45G0-->45G1
// 42G0-->42G1
// 42U1-->45U1
var tmparr = tmp.Split('*');
switch (tmparr[0])
{
case "22G0":
if (listXXXL.Contains("22G1*"+tmparr[1]))
{
jCRstOk++;
continue;
}
break;
case "45G0":
if (listXXXL.Contains("45G1*" + tmparr[1]))
{
jCRstOk++;
continue;
}
break;
case "42G0":
if (listXXXL.Contains("42G1*" + tmparr[1]))
{
jCRstOk++;
continue;
}
break;
case "42U1":
if (listXXXL.Contains("45U1*" + tmparr[1]))
{
jCRstOk++;
continue;
}
break;
default:
//业务系统中箱型和数量未在报文中找到
bldErrorInfo.AppendLine(string.Format("{0}的业务系统中的箱型箱数{1}未在报文中找到!", iftmbc.F_RFF_BN, tmp));
isContrastOK = false;
break;
}
}
}//end for
if (jCRstOk != tbl.Rows.Count)
{
int jCRstOK2 = 0;
//检查报文中的箱型和数量是否存在业务系统中
for (int i = 0; i < tbl.Rows.Count; i++)
{
if (listXXXL2.Contains(listXXXL[i]))
{
jCRstOK2++;
}
else
{
//兼容22G0-->22G1
// 45G0-->45G1
// 42G0-->42G1
// 42U1-->45U1
var tmparr = listXXXL[i].Split('*');
switch (tmparr[0])
{
case "22G1":
if (listXXXL.Contains("22G0*" + tmparr[1]))
{
jCRstOK2++;
continue;
}
break;
case "45G1":
if (listXXXL.Contains("45G0*" + tmparr[1]))
{
jCRstOK2++;
continue;
}
break;
case "42G1":
if (listXXXL.Contains("42G0*" + tmparr[1]))
{
jCRstOK2++;
continue;
}
break;
case "45U1":
if (listXXXL.Contains("42U1*" + tmparr[1]))
{
jCRstOK2++;
continue;
}
break;
default:
//
bldErrorInfo.AppendLine(string.Format("{0}的箱型信息{1}未在业务系统中的找到!", iftmbc.F_RFF_BN, listXXXL[i]));
isContrastOK = false;
break;
}
}
}//end for
}//end if
}//end if 报文的箱型数量于业务系统中的箱型数量 个数一致时的处理
if (isContrastOK)
{
bldErrorInfo.Append("匹配BC报文无异常");
}
return isContrastOK;
}
/// <summary>
/// BL报文 的pdf 文件
/// </summary>
/// <param name="filename"></param>
/// <param name="rptid"></param>
/// <param name="errorinfo"></param>
/// <returns></returns>
private bool AnalyzeBLEdi_InsertSql(string filename, string rptid, out string errorinfo)
{
//检查Bl文件是否已经存在任务列表中,如果存在则返回false
//此方法只针对BL文件
errorinfo = "";
string sql = "SELECT COUNT(1) as ncount FROM [t_op_task] where 电子档案路径 like '%{0}'";
string filenameShrt = Path.GetFileName(filename);
int ncount = int.Parse(DbHelperSQL.GetSingle(string.Format(sql, filenameShrt)).ToString());
if (ncount > 0)
{
errorinfo = string.Format("报文{0}已处理:", filenameShrt);
return false;
}
bool isok = true;
string analyzesql = string.Format(@"INSERT INTO [t_op_task]
([任务编号] ,[上级任务号],[任务类型],[任务来源],[任务状态],[任务说明]
,[发起人] ,[录入日期] ,[任务开始时间] ,[完成方式] ,[完成时间] ,[KPI值]
,[提单号],[文件编号],[邮件编号],[电子档案路径],[是否公共],[任务相关人员],[SEA编号])
select v1.*,case when sea.客服员 IS null then 1 else 0 end as 是否公共, sea.客服员,sea.编号 from
(
SELECT newid() as [任务编号],null as [上级任务号], [fileType] as [任务类型],
'FTP' as [任务来源],
case [fileType] when 'ADVANCE' then '未开始' when 'APPROVED' then '挂单待确认'
when 'ORIGINAL' then '等待挂单' when 'SEAWAY' then '挂单待确认' else '未开始' end as [任务状态],
case [fileType] when 'ADVANCE' then 'Verify Copy' when 'APPROVED' then '已获得贵司确认的copy'
when 'ORIGINAL' then '正本提单' when 'SEAWAY' then 'Seaway Bill' else [fileType] end [任务说明],
'DEMO-SA' as [发起人],GETDATE() as [录入日期],lastmodi_date as[任务开始时间], '手动' as [完成方式],null as [完成时间] ,null as [KPI值] ,
SUBSTRING(ftp_filename, CHARINDEX('-',ftp_filename , 1)+1,CHARINDEX('-',ftp_filename , 10)- (CHARINDEX('-',ftp_filename , 1)+1)) as [业务编号],
ReportID as [文件编号], null as [邮件编号],
[local_path] +'\'+ [ftp_filename] as [电子档案路径] from t_op_seae_ftpfile_bc
where ReportID='{0}'
) v1 left join (select s.主提单号,s.业务编号,s.客服员,s.编号 from t_op_seae s where s.业务类型='普通货' ) sea on v1.[业务编号]=sea.主提单号", rptid);
try
{
int iresut = MailAnalyzeTools.DbHelperSQL.ExecuteSql(analyzesql);
isok = (iresut > 0);
UpdateMultiGuadanstate(rptid);
}
catch (Exception ex)
{
errorinfo = "分析BC结果出错501:" + ex.Message;
LogHelper.WriteLog(this.GetType(), errorinfo);
}
return isok;
}
/// <summary>
/// 插入Invoice 任务
/// </summary>
/// <param name="filename"></param>
/// <param name="feeEdiList"></param>
/// <param name="reportid"></param>
/// <param name="dtmodi"></param>
/// <param name="erroinfo"></param>
/// <returns></returns>
private bool AnalyzeInvoice_InsertSql(string realfilepath, string reportid, DateTime dtmodi, out string erroinfo)
{
bool isok = true;
bool isytfee = false;
string analyzesql = "";
string sql;
erroinfo = "";
List<TCH_Fee_edi> tchfeeEdilst = new List<TCH_Fee_edi>();
StringBuilder bldError = new StringBuilder();
isok = AnalyzeInvoceEdiTool.ImportEdiFeeList(realfilepath, tchfeeEdilst, reportid, dtmodi, out erroinfo);
//
TOP_Task optsk = new TOP_Task();
//任务编号
optsk.F_01RWBH = reportid;
optsk.F_02SJRWH = null;
optsk.F_03RWLX = "INVOIC";
optsk.F_04RWLY = "FTP";
optsk.F_05RWZT = "待导入确认";
// optsk.F_06RWSM = "鸿安货运Edi提单";
optsk.F_07FQR = "DEMO-SA";
//任务开始时间,初始化值-->用实际时间替换
optsk.F_09RWKSSJ = dtmodi.ToString("yyyy-MM-dd HH:mm:ss");
optsk.F_08LRRQ = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
optsk.F_10WCFS = "手动";
optsk.F_14WJBH = reportid;
//电子档案路径-->服务器路径-->待用共享路径替换
optsk.F_16DZDALJ = realfilepath;
optsk.F_17SFGG = true;
bool isfound = false;
string seano;
if (tchfeeEdilst.Count > 0)
{
optsk.F_13TDH = tchfeeEdilst[0].F_19TDH;
optsk.F_06RWSM = tchfeeEdilst[0].F_21BWLX;
//查看主题单号是否存在业务系统中,以便进行任务分配
sql = @"select s.编号,s.客服员 from t_op_seae s where s.业务类型='普通货' and s.主提单号='{0}';";
//去掉提单号中的船公司中的关键字
string tdh = optsk.F_13TDH;
DataTable tbltmp = DbHelperSQL.QueryTable(string.Format(sql, tdh));
if (tbltmp != null && tbltmp.Rows.Count > 0)
{
isfound = true;
//业务编号
seano = tbltmp.Rows[0]["编号"].ToString();
optsk.F_19SEABH = seano;
//任务人
optsk.F_18RWXGRY = tbltmp.Rows[0]["客服员"].ToString();
optsk.F_17SFGG = false;
// edibc.F_EXT_SeaNo = seano;
foreach (var item in tchfeeEdilst)
{
item.F_05BH = seano;
}
}
}
if (string.IsNullOrWhiteSpace(erroinfo))
{
bldError.AppendLine(erroinfo);
erroinfo = "";
}
//查找业务编号和客服员
try
{
//插入报文内容
foreach (var item in tchfeeEdilst)
{
if (item.F_18FYYWMC == "3RD PARTY DAMAGE REPAIR RECOVERY") isytfee = true;
if (!isytfee)
{
analyzesql = item.GetInsertsql();
int i = DbHelperSQL.ExecuteSql(analyzesql);
}
}
}
catch (Exception ex)
{
isok = false;
LogHelper.WriteLog(typeof(ftptool), ex);
bldError.AppendLine(ex.Message);
}
//插入任务
if (!isok)
{
optsk.F_22Remark = StrUtill.GetValueString(bldError.ToString(), 100);
}
//
string sql_pre = @"INSERT INTO [t_op_task]
([任务编号] ,[任务类型],[任务来源],[任务状态],[任务说明]
,[发起人] ,[录入日期] ,[任务开始时间] ,[完成方式] ,[完成时间]
,[提单号],[文件编号],[邮件编号],[电子档案路径],
[是否公共],[任务相关人员],[SEA编号],[备注])
values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17}) ";
sql = string.Format(sql_pre,
StrUtill.GetValueString(optsk.F_01RWBH), // 0[任务编号] o
StrUtill.GetValueString(optsk.F_03RWLX), // 1任务类型 o
StrUtill.GetValueString(optsk.F_04RWLY), // 2任务来源 o
StrUtill.GetValueString(optsk.F_05RWZT), // 3任务状态 o
StrUtill.GetValueString(optsk.F_06RWSM), // 4任务说明 o ,区分报文类型:
StrUtill.GetValueString(optsk.F_07FQR), // 5发起人 o
StrUtill.GetValueString(optsk.F_08LRRQ), //6 录入日期 o
StrUtill.GetValueString(optsk.F_09RWKSSJ), //7 任务开始时间 o-->to
StrUtill.GetValueString(optsk.F_10WCFS), // 8完成方式 o
StrUtill.GetValueString(optsk.F_11WCSJ), // 9完成时间 h
StrUtill.GetValueString(optsk.F_13TDH), //10 提单号 to
StrUtill.GetValueString(optsk.F_14WJBH), //11 文件编号 o
StrUtill.GetValueString(optsk.F_15YJBH), //12 邮件编号 h
StrUtill.GetValueString(optsk.F_16DZDALJ, 180), //13 电子档案路径 o->to
optsk.F_17SFGG ? "1" : "0", // 是否公共 o--> to
StrUtill.GetValueString(optsk.F_18RWXGRY), // 任务相关人员 to
StrUtill.GetValueString(optsk.F_19SEABH), // SEA编号 to
StrUtill.GetValueString(optsk.F_22Remark, 100) //备注 to
);
try
{
if (!isytfee)
{
int i = DbHelperSQL.ExecuteSql(sql);
}
}
catch (Exception ex)
{
LogHelper.WriteLog("插入Invoice任务发生异常:", ex.Message);
bldError.AppendLine("插入Invoice任务发生异常:" + ex.Message);
}
return isok;
}
/// <summary>
/// 更新多次挂单到任务状态
/// </summary>
/// <param name="bsno"></param>
/// <param name="rptid"></param>
/// <returns></returns>
private bool UpdateMultiGuadanstate(string rptid)
{
bool isok = true;
try
{
string bsno = "";
string sql = "select isnull(SEA编号,'') as SEA编号 from t_op_task t where t.文件编号='{0}'";
DataTable dt = DbHelperSQL.QueryTable(string.Format(sql, rptid));
if (dt != null && dt.Rows.Count > 0)
{
bsno = dt.Rows[0]["SEA编号"].ToString();
}
if (string.IsNullOrEmpty(bsno))
return true;
//处理二次挂单和多次挂单
//dongshengfile 数据库
string sql_hq = "select isnull(是否换签,0) as f_shfhq from t_op_seae where 编号='{0}'";
dt = DbHelperSQL.QueryTable(string.Format(sql_hq, bsno));
bool blHQ = false;
if (dt != null && dt.Rows.Count > 0 && bool.Parse(dt.Rows[0]["f_shfhq"].ToString()))
{
blHQ = true;
}
//已挂单次数
int i = 0;
// string sql_gdcsh = @"select COUNT(fid) as ncount from dbo.t_op_file_items
// where Pid in
// (SELECT fid FROM t_op_file WHERE 编号='{0}' AND 文件类型='船公司挂单') ";
// dt = DbHelperSQL.QueryTable_NassDB(string.Format(sql_gdcsh,bsno));
// if(dt!=null&&dt.Rows.Count>0)
// {
// i = int.Parse(dt.Rows[0]["ncount"].ToString());
// }
//未处理的挂单任务数 --> AND ( 是否完成=0 or( 是否完成=1 and 任务状态='结束'))
//统计任务推送数量
string sql_wchlgd = @"select COUNT(1) as ncount from t_op_task t where t.SEA编号='{0}' and t.任务类型='ORIGINAL' ";
//+ "( 是否完成=0 or( 是否完成=1 and 任务状态='结束'))";
DataTable dtwchl = DbHelperSQL.QueryTable(string.Format(sql_wchlgd, bsno));
int nWcl = 1;
if (dtwchl != null && dtwchl.Rows.Count > 0)
{
nWcl = int.Parse(dtwchl.Rows[0]["ncount"].ToString());
if (nWcl < 1)
nWcl = 1;
}
i = i + nWcl;//已挂单数量+未处理的任务数
string csh = "多次(10次及以上)";
List<string> cshChinese = new List<string>() { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
switch (i)
{
case 0:
case 1:
return true;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
csh = cshChinese[i];
break;
default:
break;
}
string info = blHQ ? "换签:" : "非换签:" + csh + "次挂单";
string sqlUpdate = "update t_op_task set 备注='" + info + "' where 文件编号='" + rptid + "'";
int irst = DbHelperSQL.ExecuteSql(sqlUpdate);
}
catch (Exception ex)
{
LogHelper.WriteLog("更新任务备注:多次换签标记出错," + rptid, ex.Message);
return false;
}
return true;
}
/// <summary>
/// 更新业务处理的状态
/// </summary>
/// <param name="dealok"></param>
/// <param name="rptid"></param>
/// <param name="errorinfo"></param>
/// <returns></returns>
private bool UpdateFTPDealState(bool dealok, string rptid, string errorinfo, string guadanPath)
{
bool isok = true;
string updateGuadan = "";
if (!string.IsNullOrEmpty(guadanPath))
{
updateGuadan = string.Format(",guadan_fullPath='{0}' ", guadanPath);
}
try
{
string sql = string.Format(@"UPDATE [t_op_seae_ftpfile_bc]
SET [deal_ok] = {1} ,[remark] = isnull(remark,'')+'{2}' " + updateGuadan
+ "WHERE [ReportID] ='{0}';", rptid, dealok ? "1" : "0", errorinfo.Replace("'", "''"));
int iresut = MailAnalyzeTools.DbHelperSQL.ExecuteSql(sql);
isok = iresut > 0;
}
catch (Exception ex)
{
LogHelper.WriteLog(this.GetType(), ex);
isok = false;
}
return isok;
}
/// <summary>
/// 更新任务的文件路径未nass服务器路径
/// </summary>
/// <param name="taskPath"></param>
/// <param name="upway"></param>
/// <param name="rptid"></param>
/// <returns></returns>
public static bool UpdateTaskFilePath(string taskPath, int upway, string rptid)
{
bool isok = true;
// [文件编号]
//[邮件编号]
string wayfield = upway == 1 ? "文件编号" : "邮件编号";
try
{
string sql = string.Format(@"UPDATE [t_op_task] SET [电子档案路径] ='{0}' WHERE {1} ='{2}';", taskPath, wayfield, rptid);
int iresut = MailAnalyzeTools.DbHelperSQL.ExecuteSql(sql);
isok = iresut > 0;
}
catch (Exception ex)
{
LogHelper.WriteLog(typeof(ftptool), ex);
isok = false;
}
return isok;
}
/// <summary>
/// 获得ftp报文的分类
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
private string GetReporType(string filename)
{
string reporttype = "UnNownType";
if (filename.EndsWith("pdf"))
{
// bl
string SEAWAY = "SEAWAY";
string ADVANCE = "ADVANCE";
string APPROVED = "APPROVED";
string ORIGINAL = "ORIGINAL";
if (filename.ToUpper().IndexOf(SEAWAY) > 0)
reporttype = SEAWAY;
else if (filename.ToUpper().IndexOf(ADVANCE) > 0)
reporttype = ADVANCE;
else if (filename.ToUpper().IndexOf(APPROVED) > 0)
reporttype = APPROVED;
else if (filename.ToUpper().IndexOf(ORIGINAL) > 0)
reporttype = ORIGINAL;
}
else
{
// CONTRL 不处理
const string CONTRL = "CONTRL";
const string IFTMBC = "IFTMBC";
const string IFTMCS = "IFTMCS";
const string INVOIC = "INVOIC";
const string APERAK = "APERAK";
if (filename.ToUpper().IndexOf(IFTMBC) > 0)
reporttype = IFTMBC;
else if (filename.ToUpper().IndexOf(IFTMCS) > 0)
reporttype = IFTMCS;
else if (filename.ToUpper().IndexOf(INVOIC) > 0)
reporttype = INVOIC;
else if (filename.ToUpper().IndexOf(CONTRL) > 0)
reporttype = CONTRL;
else if (filename.ToUpper().IndexOf(APERAK) > 0)
reporttype = APERAK;
}
return reporttype;
}
/// <summary>
/// 文件下载
/// </summary>
/// <param name="fileName"></param>
/// <param name="localfileName"></param>
/// <param name="errInfo"></param>
/// <returns></returns>
///
private bool downloadfile(string fileName, string fullName, out string localfileName, out string errInfo)
{
bool downloadok = true;
errInfo = "";
//下载后存放的路径
string savepath = (m_curFolder != "/" && m_curFolder != "") ? Path.Combine(Path.GetFullPath(m_localpath), m_curFolder) : Path.GetFullPath(m_localpath); ;
if (!Directory.Exists(savepath))
{
DirectoryInfo dinfo = new DirectoryInfo(savepath);
dinfo.Create();
}
string FileName = savepath + Path.DirectorySeparatorChar.ToString() + fileName;
localfileName = fileName;
//创建文件流
FileStream fs = null;
try
{
if (File.Exists(FileName))
{
fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);
}
else
{
fs = File.Create(FileName);
}
var responseStream = m_session.GetFile(fullName);
if (fs != null)
{
int buffer_count = 65536;
byte[] buffer = new byte[buffer_count];
int size = 0;
while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
{
fs.Write(buffer, 0, size);
}
fs.Flush();
fs.Close();
responseStream.Close();
//删除
}
m_session.RemoveFile(fullName);
}
catch (Exception ex)
{
LogHelper.WriteLog("ftptool:", "下载文件" + FileName + "失败,请参见下面的信息:");
LogHelper.WriteLog(typeof(ftptool), ex);
downloadok = false;
errInfo = ex.Message;
}
finally
{
if (fs != null)
fs.Close();
}
return downloadok;
}
//private bool downloadfile(string fileName, out string localfileName, out string errInfo)
//{
// bool downloadok = true;
// errInfo = "";
// //需要下载的文件名 debug
// // fileName = "Z240065511-201706141510.txt";
// //需要现在的文件在ftp上的完整路径
// string fileUploadPath = m_ftpServer;// // +m_ftpDefaultUrl;
// Uri uri;
// uri = new Uri(fileUploadPath + System.Web.HttpUtility.UrlEncode("/" + fileName).Replace("+", "%20"));
// //下载后存放的路径
// string savepath = (m_curFolder != "/" && m_curFolder != "") ? Path.Combine(Path.GetFullPath(m_localpath), m_curFolder) : Path.GetFullPath(m_localpath); ;
// if (!Directory.Exists(savepath))
// {
// DirectoryInfo dinfo = new DirectoryInfo(savepath);
// dinfo.Create();
// }
// string FileName = savepath + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(uri.LocalPath);
// localfileName = fileName;
// //创建文件流
// FileStream fs = null;
// Stream responseStream = null;
// try
// {
// //创建一个与FTP服务器联系的FtpWebRequest对象
// FtpWebRequest m_reqFTP = (FtpWebRequest)WebRequest.Create(uri);
// //
// //连接登录FTP服务器
// m_reqFTP.Credentials = new NetworkCredential(m_ftpUserName, m_ftpUserPwd);
// m_reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
// //获取一个请求响应对象
// FtpWebResponse response = (FtpWebResponse)m_reqFTP.GetResponse();
// //获取请求的响应流
// responseStream = response.GetResponseStream();
// //判断本地文件是否存在,如果存在,则打开和重写本地文件
// if (File.Exists(FileName))
// {
// fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);
// }
// else
// {
// fs = File.Create(FileName);
// }
// if (fs != null)
// {
// int buffer_count = 65536;
// byte[] buffer = new byte[buffer_count];
// int size = 0;
// while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
// {
// fs.Write(buffer, 0, size);
// }
// fs.Flush();
// fs.Close();
// responseStream.Close();
// //删除
// string delinfo = DeleteFtpFile(uri.AbsoluteUri);
// if (!string.IsNullOrEmpty(delinfo))
// {
// //
// }
// }
// }
// catch (Exception ex)
// {
// LogHelper.WriteLog("ftptool:", "下载文件" + FileName + "失败,请参见下面的信息:");
// LogHelper.WriteLog(typeof(ftptool), ex);
// downloadok = false;
// errInfo = ex.Message;
// }
// finally
// {
// if (fs != null)
// fs.Close();
// if (responseStream != null)
// responseStream.Close();
// }
// return downloadok;
//}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName"></param>
private string DeleteFtpFile(string uripath)
{
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uripath));
reqFTP.Credentials = new NetworkCredential(m_ftpUserName, m_ftpUserPwd);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
LogHelper.WriteLog("ftptool:", "删除" + uripath + "失败!");
LogHelper.WriteLog(typeof(ftptool), ex);
return "删除失败 --> " + ex.Message + " 文件名:" + uripath;
}
return string.Empty;
}
/// <summary>
/// 检查下载的文件是否超过失败次数
/// </summary>
/// <param name="ftpname"></param>
/// <returns></returns>
private bool checkDownloadFtpFileOvermax(string ftpname)
{
bool overmax = false;
if (m_downloaderrList.Keys.Contains(ftpname) && m_downloaderrList[ftpname].FailurCount > 9)
overmax = true;
return overmax;
}
#endregion //私有方法
#region 私有变量和属性
public delegate void UpdateDownloadStatus(string info);
public UpdateDownloadStatus propUpdateDownloadStatus;
//状态栏标签
public ToolStripStatusLabel TSLabl_Info;
private List<fileprop> m_filelist;
private List<fileprop> m_Folderlist;
private Dictionary<string, DLDFilestruct> m_downloaderrList;
string m_curFolder;
//ftp服务器路径
string m_ftpServer;
//ftp本地路径
string m_ftpDefaultUrl;
//登入到ftp的账号
string m_ftpUserName;
//登入到ftp的密码
string m_ftpUserPwd;
//登入到ftp的端口
string m_ftpPort;
//下载后的文件存放路径
string m_localpath;
public int MyProperty { get; set; }
public int MyProperty2 { get; set; }
bool m_loged;
SessionOptions m_sessionOptions;
Session m_session;
#endregion //私有变量和属性
class DLDFilestruct
{
public DLDFilestruct(string guid)
{
ID = guid == null ? System.Guid.NewGuid().ToString("N") : guid;
}
private string id;
public string ID
{
get { return id; }
set { id = value; }
}
private string filename;
public string FileName
{
get { return filename; }
set { filename = value; }
}
private int failurcount;
public int FailurCount
{
get { return failurcount; }
set { failurcount = value; }
}
}
}
}