/// <summary> /// 发送邮件并可发送附件 /// </summary> /// <param name="isBodyHtml">发送的内容是否为html格式</param> /// <returns>是否发送成功</returns> public bool SendEmailWithAttachment(bool isBodyHtml = false) { try { // SmtpClient要发送的邮件实例 MailMessage message = new MailMessage(); message.From = new MailAddress(FromAddress); message.Subject = Subject; message.SubjectEncoding = Encoding.UTF8; //标题编码 message.Body = Body; message.BodyEncoding = Encoding.UTF8; //邮件内容编码 message.IsBodyHtml = isBodyHtml; foreach (var to in ToAddressList) { //添加接收人地址 message.To.Add(new MailAddress(to)); } //添加邮件附件 foreach (var file in FileList) { //添加附件 // 为邮件创建文件附件对象 Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); // Add time stamp information for the file. //为文件添加时间戳信息。 ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); // Add the file attachment to this e-mail message. //将文件附件添加到该电子邮件。 message.Attachments.Add(data); //data.Dispose(); } //添加纯文本格式的替代邮件内容 foreach (var body in AlternateViews) { ContentType mimeType = new System.Net.Mime.ContentType("text/html"); // Add the alternate body to the message. AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType); message.AlternateViews.Add(alternate); } //创建基于密码的身份验证方案 NetworkCredential nc = new NetworkCredential(FromAddress, Password); SmtpClient client = new SmtpClient(Server); //表示以当前登录用户的默认凭据进行身份验证 client.UseDefaultCredentials = true; client.Credentials = nc; //设置验证发件人的身份凭证 client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //待发的电子邮件通过网络发送到smtp服务器 //Send the message. //正式发送信息 client.Send(message); return(true); } catch (Exception ex) { SystemLogHelper.Error(MethodBase.GetCurrentMethod(), "发送邮件失败_SendEmailWithAttachment", ex); return(false); } }
/// <summary> /// 正式写入日志到Redis /// </summary> /// <typeparam name="TState">泛型</typeparam> /// <param name="logLevel">日志等级</param> /// <param name="eventId">日志触发事件</param> /// <param name="state">泛型实体</param> /// <param name="exception">异常信息</param> /// <param name="formatter">格式化处理</param> public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } var msg = $"日志触发ID:{eventId.Id},日志名:{eventId.Name},具体》》" + formatter(state, exception); switch (logLevel) { case LogLevel.Trace: case LogLevel.Debug: SystemLogHelper.Debug(moduleName, msg, exception); break; case LogLevel.Information: SystemLogHelper.Info(moduleName, msg, exception); break; case LogLevel.Warning: SystemLogHelper.Warn(moduleName, msg, exception); break; case LogLevel.Error: SystemLogHelper.Error(moduleName, msg, exception); break; case LogLevel.Critical: SystemLogHelper.Fatal(moduleName, msg, exception); break; default: break; } }
/// <summary> /// 输出Error的日志提示 /// </summary> /// <param name="message">日志提示消息</param> /// <param name="exception">可指定发生的异常对象</param> /// <param name="isWriteLog">是否需要记录到系统日志,默认需要</param> public void Error(string message, Exception exception = null, bool isWriteLog = true) { showLog(message + exception?.GetExceptionMsg() + $"---{DateTime.Now} ThreadId:{Thread.CurrentThread.ManagedThreadId}\r\n", Color.Red); if (isWriteLog) { SystemLogHelper.Error(MethodBase.GetCurrentMethod(), message, exception); } }
/// <summary> /// 获取临时素材 /// </summary> /// <param name="mediaId">临时素材的媒体文件ID</param> /// <param name="filePathName">指定个临时包含路径的文件名</param> /// <returns>实际保存好的包含路径的文件名</returns> public WeChatResult <string> GetTempMaterial(string mediaId, string filePathName) { string accessToken = connect.GetAccessToken(); string url = $"https://api.weixin.qq.com/cgi-bin/media/get?access_token={accessToken}&media_id={mediaId}"; try { string fileName = SimulateRequest.DownloadFile(url, filePathName); WeChatResult <string> weChatResult = new WeChatResult <string>("{\"errcode\":0,\"errmsg\":\"SUCCESS\"}"); weChatResult.resultData = fileName; return(weChatResult); } catch (Exception ex) { SystemLogHelper.Error(MethodBase.GetCurrentMethod(), $"获取临时素材GetTempMaterial,报错", ex); WeChatResult <string> errorResult = new WeChatResult <string>(ex.Message); return(errorResult); } }
/// <summary> /// 获取永久素材,返回ArticleItemsInfo、VideoMaterialResult或fileName /// </summary> /// <param name="mediaId">永久素材的媒体文件ID</param> /// <param name="filePathName">指定个临时包含路径的文件名</param> /// <returns>图文素材请解析为ArticleItemsInfo,视频素材请解析为VideoMaterialResult,其他素材为实际保存好的包含路径的文件名</returns> public WeChatResult <string> GetMaterial(string mediaId, string filePathName) { string accessToken = connect.GetAccessToken(); string url = $"https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={accessToken}"; try { string fileName = SimulateRequest.DownloadFilePost(url, filePathName, new { media_id = mediaId }); WeChatResult <string> weChatResult = new WeChatResult <string>("{\"errcode\":0,\"errmsg\":\"SUCCESS\"}"); weChatResult.resultData = fileName; return(weChatResult); } catch (Exception ex) { SystemLogHelper.Error(GetType().FullName, $"获取永久素材GetMaterial,报错", ex); WeChatResult <string> errorResult = new WeChatResult <string>(ex.Message); return(errorResult); } }
/// <summary> /// 把Redis的日志数据保存到数据库 /// </summary> /// <returns>保存到数据库的日志数量</returns> public int LogForRedisToDB() { string requestLogRemedy = redisHelper.StringGet(RedisKeyPrefix.REQUEST_LOG_REMEDY); DataTable requestLogTable = new DataTable(); requestLogTable.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(Guid)), new DataColumn("Name", typeof(string)), new DataColumn("RequestUrl", typeof(string)), new DataColumn("RequestMethod", typeof(string)), new DataColumn("RequestMsg", typeof(string)), new DataColumn("ResponseMsg", typeof(string)), new DataColumn("ExceptionMsg", typeof(string)), new DataColumn("ReferenceId", typeof(Guid)), new DataColumn("ReferenceTable", typeof(string)), new DataColumn("Level", typeof(string)), new DataColumn("Version", typeof(string)), new DataColumn("CreateTime", typeof(DateTime)), }); List <RequestLog> requestLogList = null;//临时记录redis中被删除的 if (!string.IsNullOrWhiteSpace(requestLogRemedy)) { requestLogList = JsonConvert.DeserializeObject <List <RequestLog> >(requestLogRemedy); foreach (var requestLog in requestLogList) { DataRow requestLogRow = requestLogTable.NewRow(); requestLogRow["Id"] = requestLog.Id == Guid.Empty ? Guid.NewGuid() : requestLog.Id; requestLogRow["Name"] = requestLog.Name; requestLogRow["RequestUrl"] = requestLog.RequestUrl; requestLogRow["RequestMethod"] = requestLog.RequestMethod; requestLogRow["RequestMsg"] = requestLog.RequestMsg; requestLogRow["ResponseMsg"] = requestLog.ResponseMsg; requestLogRow["ExceptionMsg"] = requestLog.ExceptionMsg; requestLogRow["ReferenceId"] = requestLog.ReferenceId; requestLogRow["ReferenceTable"] = requestLog.ReferenceTable; requestLogRow["Level"] = requestLog.Level; requestLogRow["Version"] = requestLog.Version; requestLogRow["CreateTime"] = requestLog.CreateTime; requestLogTable.Rows.Add(requestLogRow); } redisHelper.StringSet(RedisKeyPrefix.REQUEST_LOG_REMEDY, string.Empty, TimeSpan.FromTicks(100)); } else { int i = 0; requestLogList = new List <RequestLog>(); long total = redisHelper.ListLength(RedisKeyPrefix.REQUEST_LOG); long surplus = total; while (i < total && surplus > 0) { RequestLog requestLog = redisHelper.ListLeftPop <RequestLog>(RedisKeyPrefix.REQUEST_LOG); requestLogList.Add(requestLog); if (requestLog != null && !string.IsNullOrWhiteSpace(requestLog.RequestMsg)) { DataRow requestLogRow = requestLogTable.NewRow(); requestLogRow["Id"] = requestLog.Id == Guid.Empty ? Guid.NewGuid() : requestLog.Id; requestLogRow["Name"] = requestLog.Name; requestLogRow["RequestUrl"] = requestLog.RequestUrl; requestLogRow["RequestMethod"] = requestLog.RequestMethod; requestLogRow["RequestMsg"] = requestLog.RequestMsg; requestLogRow["ResponseMsg"] = requestLog.ResponseMsg; requestLogRow["ExceptionMsg"] = requestLog.ExceptionMsg; requestLogRow["ReferenceId"] = requestLog.ReferenceId; requestLogRow["ReferenceTable"] = requestLog.ReferenceTable; requestLogRow["Level"] = requestLog.Level; requestLogRow["Version"] = requestLog.Version; requestLogRow["CreateTime"] = requestLog.CreateTime; requestLogTable.Rows.Add(requestLogRow); } //redisHelper.ListRemove(RedisKeyPrefix.REQUEST_LOG, requestLog); surplus = redisHelper.ListLength(RedisKeyPrefix.REQUEST_LOG); i++; } if (i == 0) { return(0); } } try { int rows = logService.LogImportToDB(requestLogTable); return(rows); } catch (Exception ex) { if (requestLogList != null && requestLogList.Count > 0) { redisHelper.StringSet(RedisKeyPrefix.REQUEST_LOG_REMEDY, requestLogList); } SystemLogHelper.Error(MethodBase.GetCurrentMethod(), "LogImportToDB_日志入库保存失败,需要补救已删除的日志数据", ex); throw ex; } }
/// <summary> /// 把Redis的日志数据保存到数据库 /// </summary> /// <returns>保存到数据库的日志数量</returns> public int LogForRedisToDB() { string systemLogRemedy = redisHelper.StringGet(RedisKeyPrefix.SYSTEM_LOG_REMEDY); DataTable systemLogTable = new DataTable(); systemLogTable.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(Guid)), new DataColumn("Module", typeof(string)), new DataColumn("Content", typeof(string)), new DataColumn("ThreadId", typeof(int)), new DataColumn("Level", typeof(string)), new DataColumn("Version", typeof(string)), new DataColumn("CreateTime", typeof(DateTime)), }); List <SystemLog> systemLogList = null;//临时记录redis中被删除的 if (!string.IsNullOrWhiteSpace(systemLogRemedy)) { systemLogList = JsonConvert.DeserializeObject <List <SystemLog> >(systemLogRemedy); foreach (var systemLog in systemLogList) { DataRow systemLogRow = systemLogTable.NewRow(); systemLogRow["Id"] = systemLog.Id == Guid.Empty ? Guid.NewGuid() : systemLog.Id; systemLogRow["Module"] = systemLog.Module; systemLogRow["Content"] = systemLog.Content; systemLogRow["ThreadId"] = systemLog.ThreadId; systemLogRow["Level"] = systemLog.Level; systemLogRow["Version"] = systemLog.Version; systemLogRow["CreateTime"] = systemLog.CreateTime; systemLogTable.Rows.Add(systemLogRow); } redisHelper.StringSet(RedisKeyPrefix.SYSTEM_LOG_REMEDY, string.Empty, TimeSpan.FromSeconds(1)); } else { int i = 0; systemLogList = new List <SystemLog>(); long total = redisHelper.ListLength(RedisKeyPrefix.SYSTEM_LOG); long surplus = total; while (i < total && surplus > 0) { SystemLog systemLog = redisHelper.ListLeftPop <SystemLog>(RedisKeyPrefix.SYSTEM_LOG); systemLogList.Add(systemLog); if (systemLog != null && !string.IsNullOrWhiteSpace(systemLog.Content)) { DataRow systemLogRow = systemLogTable.NewRow(); systemLogRow["Id"] = systemLog.Id == Guid.Empty ? Guid.NewGuid() : systemLog.Id; systemLogRow["Module"] = systemLog.Module; systemLogRow["Content"] = systemLog.Content; systemLogRow["ThreadId"] = systemLog.ThreadId; systemLogRow["Level"] = systemLog.Level; systemLogRow["Version"] = systemLog.Version; systemLogRow["CreateTime"] = systemLog.CreateTime; systemLogTable.Rows.Add(systemLogRow); } //redisHelper.ListRemove(RedisKeyPrefix.SYSTEM_LOG, systemLog); surplus = redisHelper.ListLength(RedisKeyPrefix.SYSTEM_LOG); i++; } if (i == 0) { return(0); } } try { int rows = logService.LogImportToDB(systemLogTable); return(rows); } catch (Exception ex) { if (systemLogList != null && systemLogList.Count > 0) { redisHelper.StringSet(RedisKeyPrefix.SYSTEM_LOG_REMEDY, systemLogList); } SystemLogHelper.Error(MethodBase.GetCurrentMethod(), "LogImportToDB_日志入库保存失败,需要补救已删除的日志数据", ex); throw ex; } }