嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元微信扫码支付:2 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
监视文件大小变化(特别是数据库临时文件,临时文件变大时,查看被什么操作语句使用了),磁盘剩余空间
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;
}
}
}
}