SFTPUploadJob.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using log4net;
  2. using Quartz;
  3. using SFTPUtils;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using System.Web.Script.Serialization;
  9. using TimedUpload.Util;
  10. namespace TimedUpload.QuartzJobs
  11. {
  12. public class SFTPUploadJob : IJob
  13. {
  14. private readonly ILog log = LogManager.GetLogger(typeof(SFTPUploadJob));
  15. private static DateTime timeStampStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  16. SqlHelper _sqlHelper = new SqlHelper("NBConn");
  17. int port = 22;
  18. string outputDirectory = Config.GetValue("outputDirectory");
  19. string serverPath = Config.GetValue("serverPath");
  20. string host = Config.GetValue("host");
  21. string username = Config.GetValue("username");
  22. string privateKeyPath = Config.GetValue("privateKeyPath");
  23. public void Execute(IJobExecutionContext context)
  24. {
  25. // 生成今天的json文件
  26. string filename = GenerateTodayFile();
  27. // 生成的数据上传给sftp
  28. UploadDataInfo(filename);
  29. }
  30. /// <summary>
  31. /// 先生成json文件
  32. /// </summary>
  33. public string GenerateTodayFile()
  34. {
  35. // 获取当前日期时间
  36. DateTime today = DateTime.Now;
  37. // 分别获取今天年、月、日
  38. int year = today.Year;
  39. int month = today.Month;
  40. int day = today.Day;
  41. string resultMonth;
  42. if (month < 10)
  43. {
  44. resultMonth = "0" + month;
  45. }
  46. else
  47. {
  48. resultMonth = month.ToString();
  49. }
  50. // 获取明天天的日期
  51. DateTime tomorrow = DateTime.Today.AddDays(+1);
  52. // 分别获取明天年、月、日
  53. int mingYear = tomorrow.Year;
  54. int mingMonth = tomorrow.Month;
  55. int mingDay = tomorrow.Day;
  56. GenerateHisFile(year, month, day, mingYear, mingMonth, mingDay);
  57. string filename = year + resultMonth + day + ".json";
  58. return filename;
  59. }
  60. /// <summary>
  61. /// 上传数据
  62. /// </summary>
  63. public void UploadDataInfo(String fileName)
  64. {
  65. var sftpClient = new SftpClientWithKey(host, port, username, privateKeyPath);
  66. try
  67. {
  68. // 获取当前日期时间
  69. DateTime today = DateTime.Now;
  70. // 分别获取今天年、月、日
  71. int year = today.Year;
  72. int month = today.Month;
  73. string resultMonth;
  74. if (month < 10)
  75. {
  76. resultMonth = "0" + month;
  77. }
  78. else
  79. {
  80. resultMonth = month.ToString();
  81. }
  82. // 上传文件
  83. bool success = sftpClient.UploadFile(
  84. outputDirectory + fileName,
  85. serverPath+year+"/"+resultMonth,
  86. null);
  87. Console.WriteLine($"上传结果: {success}");
  88. // 列出文件
  89. var files = sftpClient.ListFiles(serverPath+year+" / "+resultMonth);
  90. foreach (var file in files)
  91. {
  92. Console.WriteLine(file.Name);
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. Console.WriteLine($"错误: {ex.Message}");
  98. }
  99. finally
  100. {
  101. sftpClient.Dispose();
  102. }
  103. }
  104. /// <summary>
  105. /// 生成历史json文件
  106. /// </summary>
  107. public void GenerateHisFile(int startYear,int startMonth,int startDay,int endYear,int endMonth,int endDay)
  108. {
  109. try
  110. {
  111. try
  112. {
  113. // 方法1:使用DataExporter
  114. var jsonExporter = new JsonExporter();
  115. DateTime startDate = new DateTime(startYear, startMonth, startDay);
  116. DateTime endDate = new DateTime(endYear, endMonth, endDay);
  117. Console.WriteLine("开始获取数据...");
  118. var dailyData = GetDailyData(startDate, endDate);
  119. Console.WriteLine("开始导出JSON文件...");
  120. jsonExporter.ExportDailyDataToJson(dailyData, outputDirectory);
  121. Console.WriteLine($"成功导出 {dailyData.Count} 天的数据");
  122. // 方法2:使用批量处理(推荐大数据量)
  123. // var bulkExporter = new BulkDataExporter();
  124. // bulkExporter.ExportDirectToJsonFiles(startDate, endDate, outputDirectory);
  125. }
  126. catch (Exception ex)
  127. {
  128. Console.WriteLine($"导出失败: {ex.Message}");
  129. Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
  130. }
  131. // 先生成json文件
  132. //GenerateFile();
  133. //UploadDataInfo();
  134. }
  135. catch (Exception ex)
  136. {
  137. log.Error("上传数据错误:" + ex.Message);
  138. }
  139. }
  140. public List<DailyData> GetDailyData(DateTime startDate, DateTime endDate)
  141. {
  142. var dailyDataList = new List<DailyData>();
  143. // 获取所有日期
  144. var dates = GetDatesInRange(startDate, endDate);
  145. foreach (var date in dates)
  146. {
  147. var dailyData = new DailyData
  148. {
  149. Date = date,
  150. Records = GetRecordsForDay(date)
  151. };
  152. dailyData.RecordCount = dailyData.Records.Count;
  153. dailyDataList.Add(dailyData);
  154. }
  155. return dailyDataList;
  156. }
  157. private List<DateTime> GetDatesInRange(DateTime startDate, DateTime endDate)
  158. {
  159. var dates = new List<DateTime>();
  160. string sql =$@"
  161. SELECT DISTINCT CONVERT(date, r.ReadingDT) as Day
  162. FROM RMRS_MeterInfo m left join [dbo].[RMRS_HistoryRecord] r on m.MeterID = r.MeterID
  163. WHERE m.CompanyID = 'b9df6406-428e-4fb6-8bc7-ecc86a563bef' and m.DeleteMark = 0 and r.ReadingDT BETWEEN '{startDate}' AND '{endDate}'
  164. ORDER BY Day";
  165. DataTable dt = _sqlHelper.ExecuteDataTable(sql);
  166. foreach (DataRow row in dt.Rows)
  167. {
  168. dates.Add(Convert.ToDateTime(row["Day"]));
  169. }
  170. return dates;
  171. }
  172. private List<HistoryRecord> GetRecordsForDay(DateTime date)
  173. {
  174. var records = new List<HistoryRecord>();
  175. // 计算昨天的日期和昨天11点的时间
  176. DateTime yesterday = date.AddDays(-1);
  177. DateTime yesterday12AM = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day, 12, 0, 0);
  178. string sql = $@"
  179. SELECT r.ReadingDT, r.Reading, m.ElecAddress
  180. FROM RMRS_MeterInfo m left join [dbo].[RMRS_HistoryRecord] r on m.MeterID = r.MeterID
  181. WHERE m.CompanyID = 'b9df6406-428e-4fb6-8bc7-ecc86a563bef' and m.DeleteMark = 0 AND ( CONVERT(date, r.ReadingDT) = '{date}' OR (
  182. r.ReadingDT >= '{yesterday12AM:yyyy-MM-dd HH:mm:ss}'
  183. AND r.ReadingDT < '{date:yyyy-MM-dd}') )
  184. ORDER BY r.ReadingDT";
  185. DataTable dt = _sqlHelper.ExecuteDataTable(sql);
  186. foreach (DataRow row in dt.Rows)
  187. {
  188. var record = new HistoryRecord
  189. {
  190. ReadingDT = Convert.ToDateTime(row["ReadingDT"]),
  191. Reading = Convert.ToDecimal(row["Reading"]),
  192. ElecAddress = row["ElecAddress"].ToString()
  193. };
  194. records.Add(record);
  195. }
  196. return records;
  197. }
  198. public class HistoryRecord
  199. {
  200. [ScriptIgnore]
  201. public DateTime ReadingDT { get; set; }
  202. public string ReadingDateTime
  203. {
  204. get { return ReadingDT.ToString("yyyy-MM-dd HH:mm:ss"); }
  205. }
  206. public decimal Reading { get; set; }
  207. public string ElecAddress { get; set; }
  208. }
  209. public class DailyData
  210. {
  211. [ScriptIgnore]
  212. public DateTime Date { get; set; }
  213. public string ExportDate
  214. {
  215. get { return Date.ToString("yyyy-MM-dd"); }
  216. }
  217. public int RecordCount { get; set; }
  218. public List<HistoryRecord> Records { get; set; }
  219. }
  220. }
  221. }