Wednesday, 16 December 2015

Check url availability c#

You can use this application to check the availability of URL are there are not it can be used as the BVT test for your application.

There is the simple application you can create which will give the result of status of all URL for your application. It will give the Result as status code with URL.

Application will be look like Below;




XML Format of the URL should be like below for Check url availability;

<?xmlversion ="1.0"encoding="utf-8"?>
<urls>
  <url>https://support.microsoft.com/</url>
  <url>https://support.microsoft.com/mscomcloud/header.aspx</url>
</urls>

In application we are using the BackgroundProcess control which will display the result time to time in textbox along with the process count.
Using the OpenDialngbox control to select the file “XML”

Code snippet for it as.

Initializing the Worker Process inform Event as:

        public Form1()
        {
            InitializeComponent();
            bgw = new BackgroundWorker();
            bgw.WorkerReportsProgress = true;
            bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
        }


Code to save result in the file status of url availability

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFile();
        }

private void SaveFile()
        {
            if (backgroundWorker1.IsBusy != true)
            {
                saveFilePath = string.Empty;



                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //   saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
                saveFileDialog1.Title = "Save txt File";
                saveFileDialog1.Filter = "Txt Files|*.txt";


                saveFileDialog1.ShowDialog();
                saveFilePath = saveFileDialog1.FileName;
                if (saveFilePath != "")
                {
                    // Start the asynchronous operation.
                    bgw.RunWorkerAsync();

                }
                else
                {
                    MessageBox.Show("No selected File Find");
                }
            }
        }

1.  BackgroundWorker process work will main code of application  void bgw_DoWork
2.  Track the process from void bgw_ProgressChanged
3.  Once worker process completed void bgw_RunWorkerCompleted

Full code Snippet for application is

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace URLTest
{
    public partial class Form1 : Form
    {


        BackgroundWorker bgw;
        string str200 = string.Empty;
        string strStatus = string.Empty;
        string progress = string.Empty;
        string FilePath = string.Empty;
        string strResult = string.Empty;
        string saveFilePath = string.Empty;

        int Count200 = 1;
        int CountOthers = 1;

        System.IO.StreamWriter file;
        public Form1()
        {
            InitializeComponent();
            bgw = new BackgroundWorker();
            bgw.WorkerReportsProgress = true;
            bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveFile();
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SaveFile()
        {
            if (backgroundWorker1.IsBusy != true)
            {
                saveFilePath = string.Empty;



                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //   saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
                saveFileDialog1.Title = "Save txt File";
                saveFileDialog1.Filter = "Txt Files|*.txt";


                saveFileDialog1.ShowDialog();
                saveFilePath = saveFileDialog1.FileName;
                if (saveFilePath != "")
                {
                    // Start the asynchronous operation.
                    bgw.RunWorkerAsync();

                }
                else
                {
                    MessageBox.Show("No selected File Find");
                }
            }
        }


        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {

            if (FilePath != string.Empty)
            {
                file = new System.IO.StreamWriter(saveFilePath);
                var execPath = AppDomain.CurrentDomain.BaseDirectory;
                var baseDi1r = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
                var baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                XDocument doc = XDocument.Load(FilePath);
                var Urls = doc.Descendants("url");
                //  System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\URLTest\\result.txt");
                int count = 0;
                // string str = string.Empty;
                foreach (var url in Urls)
                {
                    progress = url.Value;
                    HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url.Value);
                    WebReq.Method = "GET";
                    try
                    {
                        using (HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse())
                        {
                            int code = (int)WebResp.StatusCode;
                            if (code == 200)
                            {
                                str200 += Count200.ToString() + "-  url = " + url.Value + "          Status = " + code + "\r\n";
                                Count200++;
                            }
                            else
                            {
                                strOthers += CountOthers.ToString() + "-    url = " + url.Value + "           Status = " + code + "\r\n";
                                CountOthers++;
                            }

                           strResult += "url = " + url.Value + "           Status = " + code + "\r\n";
                            // file.WriteLine("url = " + url.Value + " Response = " + code);

                        }
                    }
                    catch (WebException ex)
                    {
                        using (HttpWebResponse res = (HttpWebResponse)ex.Response)
                        {
                            int code = (int)res.StatusCode;
                            //    file.WriteLine("url = " + url.Value + " Response = " + code);
                            strOthers += CountOthers.ToString() + "-    url = " + url.Value + "           Status = " + code + "\r\n";
                            strResult = "url = " + url.Value + "           Status = " + code + "\r\n";
                            CountOthers++;
                        }
                    }
                    count++;
                    bgw.ReportProgress(count);
                    Thread.Sleep(2000);
                }
                file.Close();
                file.Dispose();
            }
            else
            {
                MessageBox.Show("Please select file");
            }
          

        }

        void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblTotalCount.Text = "Total URL Analysis  Completed:  " + e.ProgressPercentage.ToString().Split('|')[0];
           txtResult.Text = str200;
           txtStatus.Text = strOthers;
         
           file.WriteLine(strResult);
           lblProgress.Text = progress + "...";
        }

        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Completed Application !!");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (bgw.IsBusy != true)
            {
                this.openFileDialog1.Filter = "Xml Files|*.xml";
                // Allow the user to select multiple images.
                this.openFileDialog1.Multiselect = true;
                this.openFileDialog1.Title = "Select XML";
                openFileDialog1.ShowDialog();

                List<string> strCollection = new List<string>();

                foreach (String file in openFileDialog1.FileNames)
                {
                    strCollection.Add(file);
                }

                if(strCollection.Count > 0)
                {
                  FilePath =  strCollection.FirstOrDefault();
                }
          
            }
        }

      
    }
}
Output screen will be;


No comments:

Post a Comment

Others

You will like to read it