public static void Send(WebsiteMonitorConfiguration config,WebsiteMonitorConfiguration.WebsiteElement website,string errorMessage) { try { Console.WriteLine(website.Name + " appears to be down. Sending alert..."); MailAddress from = new MailAddress(config.FromEmailAddress, "Website Monitor"); MailMessage message = new MailMessage(from, new MailAddress(config.AlertEmailAddress)) { Body = "The website " + website.Name + " appears to be down. " + errorMessage + " This means that it either returned a non 200 http response when requested, or the page content returned was unexpected.", Subject = website.Name + " appears to be down" }; SmtpClient client = new SmtpClient(); if (config.EmailuseSsl) { client.EnableSsl = true; } client.Send(message); } catch (Exception ex) { //DOH!, couldn't send the email Console.WriteLine("Unable to send alert email "+ex); } }
private static bool CheckWebsite(WebsiteMonitorConfiguration.WebsiteElement website, Regex requiredContentRegex, Regex forbiddenContentRegex,out string message) { var request = (HttpWebRequest)WebRequest.Create(new Uri(website.Url,UriKind.Absolute)); request.AllowAutoRedirect = true; try { var response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode!=HttpStatusCode.OK) { message = "Expected 200 result, got " + (int) response.StatusCode; return false; } else { if (requiredContentRegex!=null || forbiddenContentRegex!=null) { using (TextReader reader = new StreamReader(response.GetResponseStream())) { string content = reader.ReadToEnd(); if (requiredContentRegex!=null) { //if the required content was not found, then send an alert if (!requiredContentRegex.IsMatch(content)) { message = "Required content not found"; return false; } } if (forbiddenContentRegex != null) { //if the forbidden content was found, then send an alert if (forbiddenContentRegex.IsMatch(content)) { message = "Forbidden content found"; return false; } } } } } } catch (Exception ex) { message = "Unexpected exception "+ex; return false; } message = "OK"; return true; }