Click here to Skip to main content
15,881,757 members
Articles / Programming Languages / C#
Tip/Trick

Gadget to Fetch Today's Gold Rates (India)

Rate me:
Please Sign up or sign in to vote.
4.89/5 (6 votes)
10 Apr 2013CPOL2 min read 35.8K   2K   5   10
Showing current Gold/ Silver rate (India) from webpage.

Introduction 

This is my first article on CodeProject. So if there are any mistakes please forgive me. This Article explains how to fetch today's Gold/ Silver rates (India) from the web. It might not be of use for guys from other than India but, it will help you understand how you can get specific text/ data from webpage.

Background 

CodeProject has helped me a lot in my programming. So finally I have decided to contribute to CodeProject.

One of my friend in college has project on "Jewelry System". For this application he came with an idea to show the user today's Gold/ Silver rate in selected city. He came to me and asked if it is possible? At first I laughed at him. but later i thought it will be great if done. So I started Googling for it but found nothing.

So I decided to try it myself and after a week had success!

Using the code

Namespaces required-

  1. To work with Web/ HTTP classes
  2. C#
    using System.Net;
  3. To work with Stream
  4. C#
    using System.IO;

Function to get Gold/ Silver Rate

Following is the function which takes the URL as input and returns the source of the page. The variable temp is used to get only required data from the page. Substring is a function of String class which takes two arguments. first is Starting Index and second is [Optional] length. Replace is another function of String which replaces specific/ given string with given second parameter string.

C#
public string rates(string urlAddress)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;
            if (response.CharacterSet == null)
                readStream = new StreamReader(receiveStream);
            else
                readStream = new StreamReader(receiveStream, 
                                        Encoding.GetEncoding(response.CharacterSet));
            string data = readStream.ReadToEnd();
            response.Close();
            readStream.Close();
            
            temp = data.Substring(data.LastIndexOf("10g"), 30);
            temp = temp.Replace("<TD>", "");
            temp = temp.Replace("</TD>", "");
            temp = temp.Replace("\t", " ");
            temp = temp.Replace("\n", " ");
        }
    }
    catch (Exception) { MessageBox.Show("Cannot connect to the server."); }
    return temp;
} 

ComboBox's SelectionChangeCommited Event

Here I have assigned comboBox Item specific URL to get Gold and Silver rate from the page. And called the function rates with URL as argument.

C#
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    lbl_gold.Text = "Gold: ";
    lbl_silver.Text = "Silver: ";
    string temp = comboBox1.SelectedValue.ToString();
    temp = temp.Substring(0, temp.IndexOf("@"));            
    lbl_gold.Text += rates(temp);
    temp = comboBox1.SelectedValue.ToString();
    temp = temp.Substring(temp.IndexOf("@") + 1);
    lbl_silver.Text += rates(temp);
}

Close application on Form1_DoubleClick event 

Close the application on Double_Click of the form.

C#
private void Form1_DoubleClick(object sender, EventArgs e)
       {
           myDictionary = null;
           this.Dispose();
       }

Form Load event  

In this event I have wrote the code to show application at upper right corner of the screen. And checking if there is an working internet connection availability.

C#
private void Form1_Load(object sender, EventArgs e)
{
    
    // SHOWING FORM AT THE RIGHT UPPER CORNER
    this.Left = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Right - this.Width;
    this.Top = 0;            
     //CHECK IF SYSTEM HAS INTERNET CONNECTION
    if (!HasConnection())
    {
        label4.Text = "No Internet connection!";
        comboBox1.Enabled = false;
        return;
    }
    // CREATE DICTIONARY FOR COMBOBOX
    myDictionary.Add("Delhi", "http://www.indiagoldrate.com/gold-rate-in-" + 
      "delhi-today.htm@http://www.indiagoldrate.com/silver-rate-in-delhi-today.htm");
    myDictionary.Add("Mumbai", "http://www.indiagoldrate.com/gold-rate-in-" + 
      "mumbai-today.htm@http://www.indiagoldrate.com/silver-rate-in-mumbai-today.htm");
    myDictionary.Add("Nashik", "http://www.indiagoldrate.com/gold-rate-in-" + 
      "nashik.htm@http://www.indiagoldrate.com/silver-price-in-nashik.htm");
    myDictionary.Add("Chennai", 
      "http://www.indiagoldrate.com/gold-rate-in-chennai-today.htm@" + 
      "http://www.indiagoldrate.com/silver-rate-in-chennai-today.htm");
    myDictionary.Add("Kolkata", "http://www.indiagoldrate.com/gold" + 
      "-rate-in-kolkata-today.htm@http://www.indiagoldrate.com/silver-rate-in-kolkata-today.htm");
    myDictionary.Add("Kochi", "http://www.indiagoldrate.com/gold-rate" + 
      "-in-kochi.htm@http://www.indiagoldrate.com/silver-rate-in-kochi.htm");
    myDictionary.Add("Hyderabad", "http://www.indiagoldrate.com/gold-rate-in" + 
      "-hyderabad-today.htm@http://www.indiagoldrate.com/silver-rate-in-hyderabad-today.htm");
    myDictionary.Add("Bangalore", "http://www.indiagoldrate.com/gold-rate-in-" + 
      "bangalore-today.htm@http://www.indiagoldrate.com/silver-rate-in-bangalore-today.htm");
    myDictionary.Add("Pune", "http://www.indiagoldrate.com/gold-rate" + 
      "-in-pune.htm@http://www.indiagoldrate.com/silver-rate-in-pune.htm");
    myDictionary.Add("Jaipur", "http://www.indiagoldrate.com/gold-rate-" + 
      "in-jaipur.htm@http://www.indiagoldrate.com/silver-rate-in-jaipur.htm");
    myDictionary.Add("Ahmedabad", "http://www.indiagoldrate.com/gold-rate" + 
      "-in-ahmedabad.htm@http://www.indiagoldrate.com/silver-rate-in-ahmedabad.htm");
    comboBox1.DataSource = new BindingSource(myDictionary, null);
    comboBox1.DisplayMember = "Key";
    comboBox1.ValueMember = "Value";

} 

Function to check internet connection

This function checks whether the computer has a working internet connection.

C#
public static bool HasConnection()
{
    // CHECK IF SYSTEM HAS INTERNET CONNECTION
    try
    {
        System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.indiagoldrate.com");
        return true;
    }
    catch
    {
        return false;
    }
}

Points of Interest

This article gives an idea on how you can get specific data from website. I know there is a lot of things can be done. Participation in the project would be greatly appreciated and can be given in any form (direct code contributions, comments, votes, emails and such). The main point is to get ideas going and implement them which is really useful for learning.

History 

  • Initial release (9 April 2013)
  • Code Improve (10 April 2013)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to use it in html file Pin
gore nilesh8-Apr-14 1:36
gore nilesh8-Apr-14 1:36 
GeneralThanks Pin
Member 1023238227-Sep-13 0:34
Member 1023238227-Sep-13 0:34 
GeneralRe: Thanks Pin
javedsmart8-Jan-14 23:07
javedsmart8-Jan-14 23:07 
QuestionHi.. Pin
Member 1030123927-Sep-13 0:30
Member 1030123927-Sep-13 0:30 
AnswerRe: Hi.. Pin
javedsmart8-Jan-14 23:07
javedsmart8-Jan-14 23:07 
GeneralUseful tip Pin
Sampath Sridhar9-Apr-13 17:58
Sampath Sridhar9-Apr-13 17:58 
GeneralRe: Useful tip Pin
javedsmart10-Apr-13 4:09
javedsmart10-Apr-13 4:09 
SuggestionSome code refactoring Pin
Ranjan.D9-Apr-13 4:40
professionalRanjan.D9-Apr-13 4:40 
GeneralRe: Some code refactoring Pin
javedsmart10-Apr-13 4:20
javedsmart10-Apr-13 4:20 
GeneralRe: Some code refactoring Pin
Ranjan.D10-Apr-13 5:41
professionalRanjan.D10-Apr-13 5:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.