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/JobAutoCreateFee/JobGetMscSwbData.cs

811 lines
30 KiB
C#

2 years ago
using JobAutoCreateFee.Model;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
2 years ago
2 years ago
namespace JobCreateFee
{
public class JobGetMscSwbData : IJob
{
private ILog log = LogManager.GetLogger(typeof(JobGetMscSwbData));
public void Execute(IJobExecutionContext context)
{
try
{
string connStr = context.JobDetail.JobDataMap.GetString("ConnectString");
2 years ago
string connStrFile = context.JobDetail.JobDataMap.GetString("ConnectStringFile");
2 years ago
string sqlQuery = context.JobDetail.JobDataMap.GetString("QuerySql");
string reqUrl = context.JobDetail.JobDataMap.GetString("ReqUrl");
int reqTimeout = Convert.ToInt32(context.JobDetail.JobDataMap.GetString("RequestTimeout"));
2 years ago
string tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempPath");
2 years ago
log.Debug($"连接字符串:{connStr}");
log.Debug($"查询SQL{sqlQuery}");
log.Debug($"请求URL{reqUrl}");
log.Debug($"请求超时:{reqTimeout}");
2 years ago
SqlConnection connFile = new SqlConnection(connStrFile);
2 years ago
SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlQuery, conn);
DataTable tQuery = new DataTable();
dataAdapter.Fill(tQuery);
if (tQuery.Rows.Count == 0)
{
log.Debug("没有要发送的数据!");
return;
}
2 years ago
conn.Close();
2 years ago
var json = DataTableToJsonHelper.ConvertToJson(tQuery);
log.Debug($"jsonStr{json.ToString(Formatting.None)}");
JObject reqObj = new JObject();
reqObj.Add("type", new JValue("search"));
reqObj.Add("data", json);
log.Debug($"reqObj{reqObj.ToString(Formatting.None)}");
//发送请求数据
string rtn = WebRequestHelper.DoPost(reqUrl, reqObj.ToString(Formatting.None), reqTimeout * 1000);
var objRtn = JsonConvert.DeserializeAnonymousType(rtn, new { code = "", msg = "" });
2 years ago
log.Debug($"返回jsonStr{rtn}");
2 years ago
log.Debug($"爬取服务返回:{objRtn.msg}(Code:{objRtn.code})");
if (objRtn.code == "200") {
var JsonMscSwBObj = JsonConvert.DeserializeObject<JsonMscSwBResponse>(rtn);
foreach (var item in JsonMscSwBObj.data)
{
if (item.code == 1) {
if (!string.IsNullOrEmpty(item.details.file_url)) {
var mblno = item.mbn;
var bsno = GetBsNo(mblno,conn);
var tarpath = "";
var swbfile = Path.Combine(tempPath, item.details.file_name);
WebClient wc = new WebClient();
wc.DownloadFile(item.details.file_url, swbfile);
log.Debug($"下载swb" + swbfile);
2 years ago
log.Debug($"mblno" + mblno+" "+ bsno);
//Guadan(mblno, bsno, "Seaway挂单", swbfile, conn, out tarpath, true);
bool guadanok = true;
try
{
1 year ago
guadanok = Guadan(mblno, bsno, "提单留底", swbfile, conn, connFile, out tarpath, true);
2 years ago
}
catch (Exception ex)
{
log.Debug("上传NASS出错" + ex.Message);
}
2 years ago
}
}
}
}
}
catch (Exception ex)
{
log.Error(ex.Message);
log.Error(ex.StackTrace);
}
}
static public string GetBsNo(string MBLNO, SqlConnection dbcon)
{
var headList = new List<MsChFee>();
var strSql = new StringBuilder();
2 years ago
strSql.Append("SELECT 编号 from t_op_seae where 业务类型='普通货' and 订舱单号='" + MBLNO + "'");
2 years ago
var BSNO = "";
2 years ago
if (dbcon.State!= ConnectionState.Open)
dbcon.Open();
try
2 years ago
{
2 years ago
SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
2 years ago
{
2 years ago
foreach (DataRow row in table.Rows)
{
BSNO = row["编号"].ToString();
}
2 years ago
}
2 years ago
else
{
var strSql2 = new StringBuilder();
strSql2.Append("SELECT 编号 from t_op_seae_assistant where 订舱单号='" + MBLNO + "'");
adapter = new SqlDataAdapter(strSql2.ToString(), dbcon);
table = new DataTable();
adapter.Fill(table);
2 years ago
2 years ago
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
BSNO = row["编号"].ToString();
}
}
}
}
finally {
dbcon.Close();
2 years ago
}
return BSNO;
}
2 years ago
public static DataTable QueryTable(string SQLString, SqlConnection dbcon)
{
DataSet ds = new DataSet();
try
{
if (dbcon.State != ConnectionState.Open)
dbcon.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, dbcon);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
2 years ago
2 years ago
}
finally
{
dbcon.Close();
}
DataTable dt = null;
if (ds != null && ds.Tables.Count > 0)
{
dt = ds.Tables[0];
}
return dt;
}
public static int ExecuteSql(string SQLString, SqlConnection dbcon)
{
using (SqlCommand cmd = new SqlCommand(SQLString, dbcon))
{
try
{
if (dbcon.State != ConnectionState.Open)
dbcon.Open();
cmd.CommandTimeout = 120000; //要加这一句
cmd.Transaction = dbcon.BeginTransaction();
int rows = cmd.ExecuteNonQuery();
cmd.Transaction.Commit();
return rows;
}
catch (System.Data.SqlClient.SqlException ex)
{
if (cmd.Transaction != null && dbcon.State == ConnectionState.Open)
{
cmd.Transaction.Rollback();
}
dbcon.Close();
throw new Exception(ex.Message);
}
}
}
public static string GetNassServerPath(SqlConnection dbcon)
{
//naspath:=get_parameters_value(175,'\\223.223.95.160\data');
// v_id:integer;default:string):string;
int vid = 175;
string defaultpath = @"\\223.223.95.160\data";
string sql = @"select 参数值 from t_sys_parameters_value where VL_ID=175";
if (dbcon.State != ConnectionState.Open)
dbcon.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter(sql.ToString(), dbcon);
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
defaultpath = row["参数值"].ToString();
}
}
}
finally {
dbcon.Close();
}
return defaultpath;
}
public int ExecuteSql_NassDb(string SQLString, SqlConnection connStrFile)
{
//SqlConnection connection = new SqlConnection(connStrFile);
//using (SqlConnection connection = new SqlConnection(connStrFile))
//{
using (SqlCommand cmd = new SqlCommand(SQLString, connStrFile))
{
try
{
if (connStrFile.State != ConnectionState.Open)
connStrFile.Open();
cmd.Transaction = connStrFile.BeginTransaction();
int rows = cmd.ExecuteNonQuery();
cmd.Transaction.Commit();
return rows;
}
catch (Exception ex)
{
log.Debug(SQLString + ex.Message);
if (cmd.Transaction != null && connStrFile.State == ConnectionState.Open)
{
cmd.Transaction.Rollback();
}
connStrFile.Close();
return 0;
}
finally
{
cmd.Dispose();
connStrFile.Close();
}
}
}
public static string GetNassPath(string SQLString, SqlConnection connStrFile)
{
if (SQLString == null)
{
return "";
}
//using (SqlConnection connection = new SqlConnection(connStrFile))
//{
using (SqlCommand cmd = new SqlCommand(SQLString, connStrFile))
{
try
{
if (connStrFile.State != ConnectionState.Open)
connStrFile.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return "";
}
else
{
return obj.ToString();
}
}
catch (System.Data.SqlClient.SqlException e)
{
connStrFile.Close();
throw new Exception(e.Message);
}
finally
{
cmd.Dispose();
connStrFile.Close();
}
}
//}
}
2 years ago
/// <summary>
///
/// </summary>
/// <param name="realfilepath"></param>
/// <param name="newreportid"></param>
/// <param name="fromway"></param>
/// <returns></returns>
public static bool TaskFileToNass(string realfilepath, string newreportid, int fromway)
{
bool isok = true;
return isok;
}
/// <summary>
/// 挂单之前要验证委托的业务是否存在
/// </summary>
/// <param name="mainNo"></param>
/// <param name="bsno"></param>
/// <param name="filetype"></param>
/// <param name="filename_src"></param>
/// <param name="guadanPath"></param>
/// <param name="isAddMblNoAsFilePre">是否将提单号作为目标文件前缀</param>
/// <returns></returns>
2 years ago
public bool Guadan(string mainNo, string bsno, string filetype, string filename_src, SqlConnection dbcon, SqlConnection connStrFile, out string guadanPath, bool isAddMblNoAsFilePre = false)
2 years ago
{
bool result;
double fsize;
int numunzipped;
2 years ago
DataTable qry_op_file;
2 years ago
int fid;
string naspath;
guadanPath = "";
filename_src = filename_src.Replace("/", "\\");
// 解决文件锁定的问题
try
{
result = true;
string insertsql;
//@ Undeclared identifier(3): 'get_parameters_value'
2 years ago
naspath = GetNassServerPath(dbcon);
2 years ago
string strsql = string.Format("select * from [t_op_file] where 编号='{0}'", bsno);
2 years ago
//
qry_op_file = QueryTable(strsql,dbcon);
//
2 years ago
if (qry_op_file.Rows.Count <= 0)
{
insertsql = string.Format(@"INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','托书','是');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','OK','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','COPY','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');
INSERT INTO [t_op_file] ([],[],[]) VALUES('{0}','','');", bsno);
2 years ago
int i = ExecuteSql(insertsql,dbcon);
if (i < 1)
{
log.Debug("初始化挂单类型出错(GuadanTool):" + insertsql);
}
2 years ago
}
strsql = string.Format("select * from [t_op_file] where 编号='{0}' and 文件类型='{1}'", bsno, filetype);
2 years ago
// 刷新取得FID
qry_op_file = QueryTable(strsql,dbcon);
2 years ago
if (qry_op_file.Rows.Count < 1)
{
insertsql = string.Format(@"INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','{1}','否');", bsno, filetype);
2 years ago
int i = ExecuteSql(insertsql,dbcon);
if (i < 1)
{
log.Debug("初始化挂单类型出错(GuadanTool):" + insertsql);
}
}
// 刷新取得FID
qry_op_file = QueryTable(strsql, dbcon);
if (qry_op_file.Rows.Count < 1)
{
log.Debug("初始化挂单类型出错(GuadanTool):");
return false;
2 years ago
}
// 上传附件
if (File.Exists(filename_src))
{
//// 拷贝到临时目录
////@ Undeclared identifier(3): 'GetWinTempPath'
//filename = GetWinTempPath() + Path.GetFileName(filename_src);
//if ((File.Exists(filename)))
//{
// File.Delete(filename);
//}
//File.Copy((filename_src as string), (filename as string), false);
FileInfo flinfo = new FileInfo(filename_src);
fsize = flinfo.Length;
//@ Unsupported property or method(A): 'fieldbyname'
//@ Unsupported property or method(D): 'AsInteger'
fid = int.Parse(qry_op_file.Rows[0]["FID"].ToString());
try
{
2 years ago
log.Debug("开始上传NASS");
if (UpLoadProFile(filename_src, naspath, "user", "user", mainNo, bsno, fid, filetype, dbcon, connStrFile,out guadanPath, isAddMblNoAsFilePre))
2 years ago
{
// 更新数量及任务路径
}
2 years ago
updateGuadanFilecount(fid, bsno, dbcon ,connStrFile);
2 years ago
}
finally
{
}
}
else
{
2 years ago
log.Debug("文件不存在或者不能访问 " + filename_src);
2 years ago
result = false;
return result;
}
}
catch (Exception ex)
{
result = false;
2 years ago
log.Debug("文件不存在或者不能访问 " + filename_src + ex.Message);
2 years ago
}
return result;
}
/// <summary>
/// 电子文档挂单
/// </summary>
/// <param name="filename_src"></param>
/// <param name="RemotePathName"></param>
/// <param name="Users"></param>
/// <param name="pw"></param>
/// <param name="mblNo">主提单号</param>
/// <param name="bsno"></param>
/// <param name="fid"></param>
/// <param name="filetype"></param>
/// <param name="newpath"></param>
/// <param name="isAddMblNoAsFilePre">是否在目标文件名前加[mblNo]前缀:true表示加,反之不加</param>
/// <returns></returns>
2 years ago
public bool UpLoadProFile(string filename_src, string RemotePathName, string Users, string pw, string mblNo, string bsno, int fid, string filetype, SqlConnection dbcon, SqlConnection connStrFile, out string newpath, bool isAddMblNoAsFilePre = false)
2 years ago
{
string path;
string filePath;
string filepath_pre;
string filename;
string fileExt;
// 上传文件
newpath = "";
filename = Path.GetFileName(filename_src);
fileExt = Path.GetExtension(filename);
2 years ago
bool status = true;
2 years ago
2 years ago
//连接共享文件夹
//status = connectState(RemotePathName, Users, pw);
if (status)
{
//共享文件夹的目录
DirectoryInfo theFolder = new DirectoryInfo(RemotePathName);
//相对共享文件夹的路径
//string fielpath = @"\123\456\";
// filePath = FormatDateTime("YYYYMM",DateTime.Today);
filePath = DateTime.Today.ToString("yyyyMM");
if (!Directory.Exists(RemotePathName + '\\' + filePath))
{
2 years ago
2 years ago
Directory.CreateDirectory(RemotePathName + '\\' + filePath);
}
log.Debug("开始上传NASS2");
if (!Directory.Exists(RemotePathName + '\\' + filePath + '\\' + mblNo))
{
Directory.CreateDirectory(RemotePathName + '\\' + filePath + '\\' + mblNo);
log.Debug("开始上传NASS3");
}
// 增加类型
filepath_pre = RemotePathName + '\\' + filePath + '\\' + mblNo.Trim() + '\\' + filetype;
if (!Directory.Exists(filepath_pre))
{
Directory.CreateDirectory(filepath_pre);
}
if (isAddMblNoAsFilePre)
{
filename = mblNo.Trim() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + filename;
}
newpath = filepath_pre + '\\' + filename;
log.Debug("开始上传NASS路径"+ newpath);
//获取保存文件的路径
string filePathTarget = filepath_pre;// theFolder.ToString() + fielpath;
//执行方法
Transport(filename_src, filePathTarget, filename);
}
else
2 years ago
{
2 years ago
return false;
}
FileInfo flinfo = new FileInfo(filename_src);
long fsize = flinfo.Length;
string insertsql_dbfile_pre = "INSERT INTO [t_op_file_items]([编号],[名称], [大小],[上传日期],[所有者],[类型],[文件类型],[Pid],[文件存储])"
+ "VALUES('{0}','{1}','{2}',GETDATE(),'DEMO-SA','{3}','{4}','{5}',1);";
string insertsql_dbfile = string.Format(insertsql_dbfile_pre, new object[] { bsno, newpath, fsize, fileExt, filetype, fid });
int i = ExecuteSql_NassDb(insertsql_dbfile, connStrFile);
log.Debug("更新t_op_file_items");
return i >= 0;
}
public bool updateGuadanFilecount(int fid, string bsno, SqlConnection dbcon, SqlConnection connStrFile)
{
string sqlCount;
sqlCount = string.Format("select count(fid) as ncount from t_op_file_items where PID='{0}' and 编号='{1}';", fid, bsno);
string ncount =GetNassPath(sqlCount, connStrFile);
log.Debug("更新t_op_file_items 大小");
string updatecount = string.Format("Update t_op_file set 大小='{0}' where FID='{1}'", ncount, fid);
int i = ExecuteSql(updatecount, dbcon);
log.Debug("t_op_file 大小");
return i > 0;
}
/// <summary>
/// 任务文件路径复制到Nass
/// </summary>
/// <param name="extPath"></param>
/// <param name="filename_src"></param>
/// <param name="mblNo"></param>
/// <param name="filetype"></param>
/// <param name="newpath"></param>
/// <param name="bsno"></param>
/// <param name="isAddMblNoAsFilePre">是否使用主提单号[mblNo]作为上传文件名的前缀</param>
/// <returns></returns>
public bool UpLoadFileToNass(string extPath, string filename_src, string mblNo, string filetype, out string newpath, SqlConnection dbcon, string bsno = null, bool isAddMblNoAsFilePre = false)
{
newpath = "";
string filePath;
string filepath_pre;
string filename;
string fileExt;
string RemotePathName, Users, pw;
bool isok = true;
filename_src = filename_src.Replace("/", "\\");
try
{
// 解决文件锁定的问题
string insertsql;
//@ Undeclared identifier(3): 'get_parameters_value'
RemotePathName = GetNassServerPath(dbcon);
Users = "user";
pw = "user";
// 上传文件
newpath = "";
filename = Path.GetFileName(filename_src);
fileExt = Path.GetExtension(filename);
bool status = false;
2 years ago
//连接共享文件夹
status = connectState(RemotePathName, Users, pw);
if (status)
{
//共享文件夹的目录
DirectoryInfo theFolder = new DirectoryInfo(RemotePathName);
2 years ago
//相对共享文件夹的路径:Task任务
if (!string.IsNullOrEmpty(extPath))
{
RemotePathName += '\\' + extPath;
if (!Directory.Exists(RemotePathName))
{
Directory.CreateDirectory(RemotePathName);
}
}
2 years ago
filePath = DateTime.Today.ToString("yyyyMM");
if (!Directory.Exists(RemotePathName + '\\' + filePath))
{
Directory.CreateDirectory(RemotePathName + '\\' + filePath);
}
2 years ago
if (string.IsNullOrEmpty(mblNo))
{
if (!string.IsNullOrEmpty(bsno))
mblNo = bsno.Trim();
else mblNo = "tmp" + DateTime.Today.ToString("yyyyMM");
}
2 years ago
if (!Directory.Exists(RemotePathName + '\\' + filePath + '\\' + mblNo))
{
Directory.CreateDirectory(RemotePathName + '\\' + filePath + '\\' + mblNo);
}
2 years ago
2 years ago
// 增加类型
2 years ago
if (string.IsNullOrEmpty(filetype))
{
filetype = "未指定";
}
2 years ago
filepath_pre = RemotePathName + '\\' + filePath + '\\' + mblNo.Trim() + '\\' + filetype;
if (!Directory.Exists(filepath_pre))
{
Directory.CreateDirectory(filepath_pre);
}
///newpath = filepath_pre + '\\' + filename;
if (isAddMblNoAsFilePre)
{
2 years ago
//filename = mblNo.Trim() + "_" + filename;
2 years ago
filename = mblNo.Trim() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + filename;
}
2 years ago
// out 参数,目标文件名
2 years ago
newpath = filepath_pre + '\\' + filename;
//获取保存文件的路径
string filePathTarget = filepath_pre;// theFolder.ToString() + fielpath;
2 years ago
//执行方法
2 years ago
Transport(filename_src, filePathTarget, filename);
2 years ago
isok = true;
2 years ago
}
else
{
2 years ago
isok = false;
2 years ago
}
}
catch (Exception ex)
{
2 years ago
log.Debug("复制文件到Nass服务器发生错误" + ex.Message);
isok = false;
2 years ago
}
2 years ago
return isok;
2 years ago
2 years ago
}
2 years ago
/// <summary>
/// 连接远程共享文件夹
/// </summary>
/// <param name="path">远程共享文件夹的路径</param>
/// <param name="userName">用户名</param>
/// <param name="passWord">密码</param>
/// <returns></returns>
public static bool connectState(string path, string userName, string passWord)
{
bool Flag = false;
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
/// <summary>
/// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
/// </summary>
/// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
/// <param name="dst">保存文件的路径,不含名称及扩展名</param>
/// <param name="fileName">保存文件的名称以及扩展名</param>
2 years ago
public void Transport(string src, string dst1, string fileName)
2 years ago
{
2 years ago
//FileStream inFileStream = new FileStream(src, FileMode.Open);
try
2 years ago
{
2 years ago
if (!Directory.Exists(dst1))
2 years ago
{
2 years ago
Directory.CreateDirectory(dst1);
2 years ago
}
2 years ago
string dst = Path.Combine(dst1, fileName);
if (File.Exists(dst))
2 years ago
{
2 years ago
try
{
File.Delete(dst);
}
catch (Exception)
{
File.Move(dst, dst + ".bak");
}
2 years ago
}
2 years ago
File.Copy(src, dst);
}
catch (Exception ex)
{
log.Debug("复制文件到Nass服务器发生错误" + ex.Message);
2 years ago
}
2 years ago
//FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
2 years ago
2 years ago
//byte[] buf = new byte[inFileStream.Length];
2 years ago
2 years ago
//int byteCount;
2 years ago
2 years ago
//while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
//{
2 years ago
2 years ago
// outFileStream.Write(buf, 0, byteCount);
//}
2 years ago
2 years ago
//inFileStream.Flush();
2 years ago
2 years ago
//inFileStream.Close();
2 years ago
2 years ago
//outFileStream.Flush();
2 years ago
2 years ago
//outFileStream.Close();
2 years ago
}
}
}