javasocute
javasocute

Reputation: 648

Program that sends an email notification if url is down

I am attempting to write this type of program as stated in the question. I have failed miserably and after no luck on msdn or google I am asking the intelligent minds of StackOverflow. My code is below for those interested in reading it.

I would like this program, on execution, to read a url to see if it is active and working properly. If it is not, and I get a bad response, an email is sent notifying someone that the website is down.

Im writing this is visual studio 2010 with C# and 3.5net. The program is reading the information (URLS and Email Addresses) from my Database from SQL Server 2008, the database will update with information based upon the sites reading per the HttpResponse (OK or NOTOK). If the website is NOTOK, then an email is sent. I am using a direct link library for the XOUlitities.Email.

The main issue is, it does not work and I have no clue why. It goes out and reads the website and comes back, but I receive no email. My question is, is there an easier way for the email function? Can I just write the entire command inside the program without using the XOUtilities dll? I am basically looking for advice. When I run the .exe, there are no errors, but I believe the problem may lye within the email function. If anyone can shed any light on this issue, that would be great. Thank you in advance!

using System;
using System.Collections.Generic;
using System.Text;
using XOUtilities;
using System.Web;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace WebsiteStatusCheck
{
class Program
{
    static string errorMsg;

    static void Main(string[] args)
    {
        string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
        string tableName = ConfigurationManager.AppSettings["WebsiteListTableName"];
        string mailServer = ConfigurationManager.AppSettings["MailServer"];
        string replyToEmail = ConfigurationManager.AppSettings["ReplyToEmail"];

        string query = "SELECT * FROM " + tableName;
        SqlDataAdapter sDA = new SqlDataAdapter(query, connectionString);
        DataTable table = new DataTable();
        sDA.Fill(table);
        string[][] websites = new string[table.Rows.Count][];
        int i = 0;
        table.Columns.Add("isSiteAlive");
        table.Columns.Add("isDBAlive");
        foreach (DataRow row in table.Rows)
        {
            string[] temp = CheckURL(row["URL"].ToString());
            row["isSiteAlive"] = temp[0];
            row["isDBAlive"] = temp[1];
        }

        XOUtilities.Email email = new XOUtilities.Email();
        email.fromAddress = replyToEmail;
        email.server = mailServer;
        email.subject = "Website needs IMMEDIATE action";
        email.isHtml = true;
        email.body = @"The following website looks to be down:<br /><br /><table><tr><th>URL</th><th>Website</th><th>Database</th>";
        foreach(DataRow row in table.Rows)
        {
            if (row["isSiteAlive"].ToString().Trim() != "OK" || row["isDBAlive"].ToString().Trim() != "OK")
            {
                string tempbody = email.body;
                email.body += @"<tr><td><center>" + row["URL"].ToString() + @"</center></td><td><center>" + row["isSiteAlive"].ToString() + @"</center></td><td><center>" + row["isDBAlive"].ToString() + @"</center></td></tr>";
                email.toAddresses = row["EMAILS_CSV"].ToString().Split(new char[] { ',' });
                email.SendEmail();
                email.body = tempbody;
            }
        }
    }

    //string[0] = website value
    //string[1] = database value
    static string[] CheckURL(string url)
    {
        string[] ret = new string[2];
        try
        {
            WebClient client = new WebClient();
            Stream resp = client.OpenRead(url);
            StreamReader reader = new StreamReader(resp);
            string result = reader.ReadToEnd();
            ret[0] = "OK";
            ret[1] = result;
        }
        catch (WebException e)
        {
            errorMsg = e.Status.ToString();
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                errorMsg = ((HttpWebResponse)e.Response).StatusDescription;
            }
            ret[0] = errorMsg;
            ret[1] = "unreachable";
        }
        catch (Exception e)
        {
            errorMsg = e.Message;
            ret[0] = errorMsg;
            ret[1] = "unreachable";
        }
        return ret;
    }
}

}

Upvotes: 0

Views: 2165

Answers (3)

Jason Meckley
Jason Meckley

Reputation: 7591

you may want to check for a different status. for example. if the Status is Success then do nothing, otherwise send email.

you can configure the default host, port and from address from the config file and then new up a smtpclient to send a message

using(var email = new MailMessage {Subject = "", Body = ""})
{
   email.To.Add(recipient);
   new SmtpClient().Send(email);
}

you may also run into OOM (out of memory) depending on the number of records returned from the database. I would recommend iterating over the data reader instead of loading a datatable.

and finally, you'll want to dispose of objects implementing IDisposable. StreamReader and SqlConnection/Command are the most obvious.

Upvotes: 1

apiguy
apiguy

Reputation: 5362

I've never used XOUtilities, why not just use the libraries included in .NET? Just make sure your project has a reference to System.Net and then you can do something like this:

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("[email protected]");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("[email protected]");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");
smtp.Send(message);

Source of this snippet: http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/a75533eb-131b-4ff3-a3b2-b6df87c25cc8

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101604

You don't like the System.Net.Mail namespace and using a MailMessage? Then you use an SmtpClient and send it off (all from the comforts of your very own .NET environment)

BTW, I'd post examples but msdn has some good ones.

Upvotes: 1

Related Questions