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; 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"); string connStrFile = context.JobDetail.JobDataMap.GetString("ConnectStringFile"); string sqlQuery = context.JobDetail.JobDataMap.GetString("QuerySql"); string reqUrl = context.JobDetail.JobDataMap.GetString("ReqUrl"); int reqTimeout = Convert.ToInt32(context.JobDetail.JobDataMap.GetString("RequestTimeout")); string tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempPath"); log.Debug($"连接字符串:{connStr}"); log.Debug($"查询SQL:{sqlQuery}"); log.Debug($"请求URL:{reqUrl}"); log.Debug($"请求超时:{reqTimeout}"); SqlConnection connFile = new SqlConnection(connStrFile); 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; } conn.Close(); 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 = "" }); log.Debug($"返回jsonStr:{rtn}"); log.Debug($"爬取服务返回:{objRtn.msg}(Code:{objRtn.code})"); if (objRtn.code == "200") { var JsonMscSwBObj = JsonConvert.DeserializeObject(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); log.Debug($"mblno" + mblno+" "+ bsno); //Guadan(mblno, bsno, "Seaway挂单", swbfile, conn, out tarpath, true); bool guadanok = true; try { guadanok = Guadan(mblno, bsno, "提单留底", swbfile, conn, connFile, out tarpath, true); } catch (Exception ex) { log.Debug("上传NASS出错:" + ex.Message); } } } } } } catch (Exception ex) { log.Error(ex.Message); log.Error(ex.StackTrace); } } static public string GetBsNo(string MBLNO, SqlConnection dbcon) { var headList = new List(); var strSql = new StringBuilder(); strSql.Append("SELECT 编号 from t_op_seae where 业务类型='普通货' and 订舱单号='" + MBLNO + "'"); var BSNO = ""; if (dbcon.State!= ConnectionState.Open) dbcon.Open(); try { SqlDataAdapter adapter = new SqlDataAdapter(strSql.ToString(), dbcon); DataTable table = new DataTable(); adapter.Fill(table); if (table.Rows.Count > 0) { foreach (DataRow row in table.Rows) { BSNO = row["编号"].ToString(); } } 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); if (table.Rows.Count > 0) { foreach (DataRow row in table.Rows) { BSNO = row["编号"].ToString(); } } } } finally { dbcon.Close(); } return BSNO; } 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) { } 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(); } } //} } /// /// /// /// /// /// /// public static bool TaskFileToNass(string realfilepath, string newreportid, int fromway) { bool isok = true; return isok; } /// /// 挂单之前要验证委托的业务是否存在 /// /// /// /// /// /// /// 是否将提单号作为目标文件前缀 /// public bool Guadan(string mainNo, string bsno, string filetype, string filename_src, SqlConnection dbcon, SqlConnection connStrFile, out string guadanPath, bool isAddMblNoAsFilePre = false) { bool result; double fsize; int numunzipped; DataTable qry_op_file; int fid; string naspath; guadanPath = ""; filename_src = filename_src.Replace("/", "\\"); // 解决文件锁定的问题 try { result = true; string insertsql; //@ Undeclared identifier(3): 'get_parameters_value' naspath = GetNassServerPath(dbcon); string strsql = string.Format("select * from [t_op_file] where 编号='{0}'", bsno); // qry_op_file = QueryTable(strsql,dbcon); // 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); int i = ExecuteSql(insertsql,dbcon); if (i < 1) { log.Debug("初始化挂单类型出错(GuadanTool):" + insertsql); } } strsql = string.Format("select * from [t_op_file] where 编号='{0}' and 文件类型='{1}'", bsno, filetype); // 刷新取得FID qry_op_file = QueryTable(strsql,dbcon); if (qry_op_file.Rows.Count < 1) { insertsql = string.Format(@"INSERT INTO [t_op_file] ([编号],[文件类型],[备注]) VALUES('{0}','{1}','否');", bsno, filetype); 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; } // 上传附件 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 { log.Debug("开始上传NASS"); if (UpLoadProFile(filename_src, naspath, "user", "user", mainNo, bsno, fid, filetype, dbcon, connStrFile,out guadanPath, isAddMblNoAsFilePre)) { // 更新数量及任务路径 } updateGuadanFilecount(fid, bsno, dbcon ,connStrFile); } finally { } } else { log.Debug("文件不存在或者不能访问 !" + filename_src); result = false; return result; } } catch (Exception ex) { result = false; log.Debug("文件不存在或者不能访问 !" + filename_src + ex.Message); } return result; } /// /// 电子文档挂单 /// /// /// /// /// /// 主提单号 /// /// /// /// /// 是否在目标文件名前加[mblNo]前缀:true表示加,反之不加 /// 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) { string path; string filePath; string filepath_pre; string filename; string fileExt; // 上传文件 newpath = ""; filename = Path.GetFileName(filename_src); fileExt = Path.GetExtension(filename); bool status = true; //连接共享文件夹 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)) { 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 { 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; } /// /// 任务文件路径复制到Nass /// /// /// /// /// /// /// /// 是否使用主提单号[mblNo]作为上传文件名的前缀 /// 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; //连接共享文件夹 status = connectState(RemotePathName, Users, pw); if (status) { //共享文件夹的目录 DirectoryInfo theFolder = new DirectoryInfo(RemotePathName); //相对共享文件夹的路径:Task任务 if (!string.IsNullOrEmpty(extPath)) { RemotePathName += '\\' + extPath; if (!Directory.Exists(RemotePathName)) { Directory.CreateDirectory(RemotePathName); } } filePath = DateTime.Today.ToString("yyyyMM"); if (!Directory.Exists(RemotePathName + '\\' + filePath)) { Directory.CreateDirectory(RemotePathName + '\\' + filePath); } if (string.IsNullOrEmpty(mblNo)) { if (!string.IsNullOrEmpty(bsno)) mblNo = bsno.Trim(); else mblNo = "tmp" + DateTime.Today.ToString("yyyyMM"); } if (!Directory.Exists(RemotePathName + '\\' + filePath + '\\' + mblNo)) { Directory.CreateDirectory(RemotePathName + '\\' + filePath + '\\' + mblNo); } // 增加类型 if (string.IsNullOrEmpty(filetype)) { filetype = "未指定"; } filepath_pre = RemotePathName + '\\' + filePath + '\\' + mblNo.Trim() + '\\' + filetype; if (!Directory.Exists(filepath_pre)) { Directory.CreateDirectory(filepath_pre); } ///newpath = filepath_pre + '\\' + filename; if (isAddMblNoAsFilePre) { //filename = mblNo.Trim() + "_" + filename; filename = mblNo.Trim() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + filename; } // out 参数,目标文件名 newpath = filepath_pre + '\\' + filename; //获取保存文件的路径 string filePathTarget = filepath_pre;// theFolder.ToString() + fielpath; //执行方法 Transport(filename_src, filePathTarget, filename); isok = true; } else { isok = false; } } catch (Exception ex) { log.Debug("复制文件到Nass服务器发生错误" + ex.Message); isok = false; } return isok; } /// /// 连接远程共享文件夹 /// /// 远程共享文件夹的路径 /// 用户名 /// 密码 /// 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; } /// /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地 /// /// 要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi" /// 保存文件的路径,不含名称及扩展名 /// 保存文件的名称以及扩展名 public void Transport(string src, string dst1, string fileName) { //FileStream inFileStream = new FileStream(src, FileMode.Open); try { if (!Directory.Exists(dst1)) { Directory.CreateDirectory(dst1); } string dst = Path.Combine(dst1, fileName); if (File.Exists(dst)) { try { File.Delete(dst); } catch (Exception) { File.Move(dst, dst + ".bak"); } } File.Copy(src, dst); } catch (Exception ex) { log.Debug("复制文件到Nass服务器发生错误" + ex.Message); } //FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate); //byte[] buf = new byte[inFileStream.Length]; //int byteCount; //while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0) //{ // outFileStream.Write(buf, 0, byteCount); //} //inFileStream.Flush(); //inFileStream.Close(); //outFileStream.Flush(); //outFileStream.Close(); } } }