Hi,
Yesterday I was working and found that one of my projects was not responding from time to time for some unknown error. The problem was intranet (some network problem with database server). We were loosing connection from time to time. But I wanted to keep a check if the site is running or not. So what I basically wanted was a check if the site was working fine by some other entity, which would tell me when there is problem with the web site.
Hence I decided to make a small windows application that would check for a given URL at the given difference of time and would report back if the site is responding. I found it very useful so thought of sharing with all.
The main work that had to be done was to make a request to the site and check if the response status code is 202 (That is the status code when the site is running fine). Here is the code on how this was done.
string strURL = txtURL.Text;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(txtURL.Text);
req.AllowAutoRedirect = true;
req.UserAgent = "Something";
req.UseDefaultCredentials = true; //Required if there is authentication and redirection.
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream st = resp.GetResponseStream();
StreamReader sr = new StreamReader(st);
string buffer = sr.ReadToEnd();
if (resp.StatusCode != HttpStatusCode.OK)
{
MessageBox.Show("Site not running" + strURL);
}
sr.Close();
st.Close();
}
catch
{
MessageBox.Show("Error connecting to " + strURL);
}
Now we need to use a timer control and call this function at a definite time interval. That’s all and we have a simple but useful tool to monitor a website.
Thanks
Vikram