Site Checker in C#–A Website health monitoring system
Below code checks the list of websites and sends a notification mail if found if any of the website is down. This I wrote for a special purpose but thought to share as this might be a helpful code snippet for small to medium companies.
You can see many places in the code are hard coded and exceptions not handled properly since I wrote this for a special purpose and I am not sharing the complete code here. So please feel free to modify.
Store all the domains in a text file (I used sites.txt) and keep in the same folder as .exe. Put one domain per line. “http://” not required.
public bool ErrorFlag = false; public StringBuilder SiteString = new StringBuilder(string.Empty); private void btnCheck_Click(object sender, EventArgs e) { CheckSites(); } private void CheckSites() { string sitestatus = "Ok"; foreach (ListViewItem lvi in listView1.Items) { lvi.UseItemStyleForSubItems = false; lvi.SubItems.Add("..."); // Use some threading methods instead of DoEvents() Application.DoEvents(); WebRequest request = WebRequest.Create(lvi.Text); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch { response = null; } if (response == null || response.StatusCode != HttpStatusCode.OK) { SiteString.Append(" - " + lvi.Text + "\n"); lvi.ForeColor = lvi.SubItems[1].ForeColor = Color.Red; sitestatus = "Error"; ErrorFlag = true; } else { response.Close(); lvi.SubItems[1].ForeColor = Color.Green; sitestatus = "Ok"; } lvi.SubItems[1].Text = sitestatus; } if (ErrorFlag) { StringBuilder message = new StringBuilder(); if (SiteString.Length > 0) { message.Append("Below website(s) may need your/IT attention:\n\n"); message.Append(SiteString.ToString()); } else { message.Append("SiteChecker application failed to load the sites.txt file. Please inform IT person"); } message.Append("\n\n\nThis is an automatic notification from SiteChecker applicaiton.\n"); message.Append("[Application created by PraVeeN under C# WinForms on VS Express 2010]"); SendMail(message.ToString()); } } private void Form1_Load(object sender, EventArgs e) { IEnumerable<string> sites; try { sites = File.ReadLines("sites.txt"); foreach (var site in sites) { listView1.Items.Add("http://" + site + "/"); } } catch { ErrorFlag = true; } //Application.DoEvents(); //CheckSites(); //Application.Exit(); } private void SendMail(string content) { // Mail sending procedure }
Recent Comments