实例介绍
【实例简介】
监视文件大小变化(特别是数据库临时文件,临时文件变大时,查看被什么操作语句使用了),磁盘剩余空间
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.ServiceProcess;
using System.Text;
using System.Web;
using ARMS.Common;
namespace MonitorFileSizeChange
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer t = null;
Dictionary<string, string> monitorFiles = null;
ServiceDac dac = null;
bool driveStart = false;
// 送信人地址
string fromEmail = ConfigurationManager.AppSettings["FromEmail"];
// 密码
string pwdMail = ConfigurationManager.AppSettings["PassWord"];
// 收件箱
string toEmail = ConfigurationManager.AppSettings["ToEmail"];
// SmtpAddress
string smtpAddress = ConfigurationManager.AppSettings["SmtpAddress"];
// 短信发送对象
string toPhoneNos = ConfigurationManager.AppSettings["ToPhoneNos"];
List<string> ToEmailList;
string strPhoneNo;
string apiUrl = string.Empty;
string pwdSms = string.Empty;
string userName = string.Empty;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
string filePath;
monitorFiles = new Dictionary<string, string>();
dac = new ServiceDac();
DataSet ds = dac.GetMonitorFiles();
if (ds == null || ds.Tables[0].Rows.Count <= 0)
{
Log.WriteLog("未设置监视文件!", "2");
this.Stop();
return;
}
foreach (DataRow dr in ds.Tables[0].Rows)
{
filePath = Converts.ToStr(dr["FilePath"]);
if (File.Exists(filePath))
monitorFiles.Add(Converts.ToStr(dr["FileName"]), filePath);
}
if (monitorFiles.Count <= 0)
{
Log.WriteLog("无可监视文件!", "2");
this.Stop();
return;
}
ds = dac.GetCodeMstByType("75");
string cont = "CodeValue='{0}'";
if (!Checker.IsEmpty(ds))
{
apiUrl = ds.Tables[0].Select(string.Format(cont, "apiUrl"))[0]["CodeName"].ToString();
pwdSms = Converts.ToMd5(ds.Tables[0].Select(string.Format(cont, "pwd"))[0]["CodeName"].ToString());
userName = ds.Tables[0].Select(string.Format(cont, "userName"))[0]["CodeName"].ToString();
}
if (string.IsNullOrEmpty(apiUrl) || string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(pwdSms))
{
Log.WriteLog("未配置短信发送信息!", "2");
this.Stop();
return;
}
ToEmailList = new List<string>();
string[] strAry = toEmail.Split(';');
// 置空发送失败信息
foreach (string strEmail in strAry)
{
// 邮件地址是否已存在
if (!ToEmailList.Contains(strEmail))
{
ToEmailList.Add(strEmail);
}
}
List<string> phoneNoList = new List<string>();
string[] strAryP = toPhoneNos.Split(';');
string phoneNo = string.Empty;
strPhoneNo = string.Empty;
foreach (string item in strAryP)
{
phoneNo = Converts.FormatPhoneNo(item);
// 手机号是否已存在
if (!string.IsNullOrEmpty(phoneNo) && !phoneNoList.Contains(phoneNo))
{
phoneNoList.Add(phoneNo);
strPhoneNo = "," phoneNo;
}
}
strPhoneNo = strPhoneNo.Length > 0 ? strPhoneNo.Substring(1) : strPhoneNo;
dac.Dispose();
driveStart = false;
t = new System.Timers.Timer(Converts.ToInt(ConfigurationManager.AppSettings["Interval"]) * 1000);
t.AutoReset = true;
t.Enabled = true;
t.Elapsed = new System.Timers.ElapsedEventHandler(timer1_Tick);
//timer1.Interval = Converts.ToInt(ConfigurationManager.AppSettings["Interval"]) * 1000;
//timer1.Enabled = true;
}
protected override void OnStop()
{
}
private void timer1_Tick(object sender, EventArgs e)
{
dac = new ServiceDac();
FileInfoDto fDto = null;
FileInfo f = null;
SendEmail email = new SendEmail();
StringBuilder body;
string bodyText;
foreach (string fileName in monitorFiles.Keys)
{
try
{
fDto = dac.GetLastDataByFileName(fileName);
f = new FileInfo(monitorFiles[fileName]);
if (fDto == null || fDto.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss") != f.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss"))
{
if (fDto != null)
{
// 获取占用TempDb空间的SQL
dac.InsertDbSpaceUsage();
// 邮件发送
// 内容
body = new StringBuilder(monitorFiles[fileName]);
body.Append(" 最后更新时间:");
body.Append(f.LastWriteTime.ToString());
body.Append(" 文件大小:");
body.Append(fDto.FileSizeMB);
body.Append("M ->");
body.Append(f.Length / 1024 / 1024);
body.Append("M.");
bodyText = body.ToString();
// 邮件主题
email.Subject = "文件大小变化_" fileName;
// 发送目标
email.ToEmailList = ToEmailList;
//发送方法
email.SendMail(fromEmail, pwdMail, bodyText, smtpAddress);
Log.WriteLog("SendMail " bodyText, "0");
// 短信发送
SendNoticeSms("【葡萄牙】" bodyText);
}
else
{
fDto = new FileInfoDto();
fDto.No = 0;
fDto.FileName = fileName;
fDto.FileSizeMB = f.Length / 1024 / 1024;
}
// 履历
dac.InsertFileSizeChgHis(f, fDto);
}
}
catch (Exception ex)
{
Log.WriteLog(ex.Message, "0");
throw ex;
}
}
DataSet ds = dac.GetDriveFree();
Int64 size = Converts.ToInt64(ds.Tables[0].Select("drive='E'")[0][1]);
if (size < 10240)
{
if (!driveStart)
{
// 邮件发送
// 内容
bodyText = "E盘空间小于10G";
// 邮件主题
email.Subject = "E盘空间小于10G";
// 发送目标
email.ToEmailList = ToEmailList;
//发送方法
email.SendMail(fromEmail, pwdMail, bodyText, smtpAddress);
Log.WriteLog("SendMail " bodyText, "0");
// 短信发送
SendNoticeSms("【葡萄牙】" bodyText);
driveStart = true;
}
}
else
{
driveStart = false;
}
dac.Dispose();
}
/// <summary>
/// 发送提醒短信
/// </summary>
/// <param name="bodyText"></param>
/// <param name="noticeContent"></param>
/// <returns></returns>
public int SendNoticeSms(string bodyText)
{
// 总错误标志,0:正常;非0:有错
int result = 0;
// POST数据
StringBuilder param = new StringBuilder();
Encoding encoding = Encoding.GetEncoding("GBK");
param.AppendFormat("{0}={1}", "pwd", HttpUtility.UrlEncode(pwdSms, encoding));
param.AppendFormat("&{0}={1}", "username", HttpUtility.UrlEncode(userName, encoding));
param.AppendFormat("&{0}={1}", "p", strPhoneNo);
param.AppendFormat("&{0}={1}", "msg", HttpUtility.UrlEncode(bodyText, encoding));
byte[] postBytes = encoding.GetBytes(param.ToString());
HttpWebRequest request = null;
HttpWebResponse response = null;
string strResponse = string.Empty;
ShortMessage shortMsg = null;
try
{
// 请求
request = WebRequest.Create(apiUrl) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = false;
request.Accept = "text/html, application/xhtml xml, */*";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 1000 * 60; // 默认最大请求一分钟
request.ContentLength = postBytes.Length;
Stream webStream = request.GetRequestStream(); // 发送数据
webStream.Write(postBytes, 0, postBytes.Length);
webStream.Close();
//获取返回数据
response = request.GetResponse() as HttpWebResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
strResponse = reader.ReadToEnd();
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(strResponse)))
{
try
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ShortMessage));
shortMsg = json.ReadObject(ms) as ShortMessage;
}
catch
{
shortMsg = null;
}
}
}
// 是否JSON数据
if (null == shortMsg)
{
result = 1;
Log.WriteLog(param.ToString(), "2");
Log.WriteLog("请求数据转换失败!" bodyText, "2");
}
else
{
// 是否发送成功
if (!"100".Equals(shortMsg.status))
{
result = 1;
Log.WriteLog(param.ToString(), "2");
Log.WriteLog(string.Format("短信发送失败,状态CODE:{0} {1}", shortMsg.status, bodyText), "2");
}
else
{
result = 0;
Log.WriteLog(param.ToString(), "0");
foreach (ShortMsgInfo smi in shortMsg.list)
{
Log.WriteLog(smi.p "=" smi.mid, "0");
}
Log.WriteLog(string.Format("短信发送成功 {0}", bodyText), "0");
}
}
return result;
}
catch (Exception ex)
{
Log.WriteLog(string.Format("短信发送失败, {0} 出错原因:{1}", bodyText, ex.Message), "2");
throw ex;
}
}
}
}
相关软件
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论