0

I want to use variable "iso3166TwoLetterCode"'s value from this class, Geolocation error with IP address 127.0.0.1

In my new test class, how do I use it? Can I even use it? If yes, how? I need this variable to use it in the if statement to check country code and based on the country code, the master page is to be changed.

Community
  • 1
  • 1
Serenity
  • 4,968
  • 19
  • 65
  • 104

2 Answers2

3

I would recommend you extracting this functionality into some utility class that you could reuse from both PageA and PageB:

public class Country
{
    public string Name { get; set; }
    public string Iso3166TwoLetterCode { get; set; }

    public static Country GetCountry(string userHost)
    {
        IPAddress ipAddress;
        if (IPAddress.TryParse(userHost, out ipAddress))
        {
            return new Country 
            {
                Name = ipAddress.Country(),
                Iso3166TwoLetterCode = ipAddress.Iso3166TwoLetterCode()
            };
        }
        return null;
    }
}

And then in your page:

protected void Page_Load(object sender, EventArgs e)
{
    //Code to fetch IP address of user begins
    string userHost = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (String.IsNullOrEmpty(userHost) ||
        String.Compare(userHost, "unknown", true) == 0)
    {
        userHost = Request.Params["REMOTE_ADDR"];
    }

    Label1.Text = userHost;
    var country = Country.GetCountry(userHost);
    if (country != null)
    {
        Label2.Text = country.Name;
        Label3.Text = country.Iso3166TwoLetterCode;
    }
}

Now you could reuse the Country class from another page. Depending on your requirements you could even further customize it by passing additional parameters to the function and the return type.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

The reason you can't use that variable as is in the first place is that it's only defined in the local scope - that is when the compiler reaches the next } after the assignment - the variable and it's value are gone. If you were to use that variable in the same class, you could have made it a class' field, since you need to use it in another class you can either make it static (which doesn't make sense in this scenario) or use Darin's solution. Go with Darin's solution (-:

Oren A
  • 5,870
  • 6
  • 43
  • 64