Monday 27 December 2010

how to find country from ip address in asp.net

Code For Default.aspx.cs Page


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

using System.IO;
using System.Xml;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
   // string ipaddress;
    DataTable dt;
   // byte[] byteArray;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Findlocation();

        }

    }

            private void Findlocation()
        {   

            WebClient wc = new WebClient();
            string baseurl = "http://checkip.dyndns.org/";
            Stream data = wc.OpenRead(baseurl);
            StreamReader reader = new StreamReader(data);
            string ipaddress = reader.ReadToEnd();
            data.Close();
            reader.Close();
            ipaddress = ipaddress.Replace("Current IP Address:", "").Replace("<html><head><title>Current IP Check</title></head><body> ", "").Replace("\r\n", "").Replace("</body></html>", "").ToString();
           

            dt = new DataTable();
            dt = GetLocation(ipaddress);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    lblCity.Text = dt.Rows[0]["City"].ToString();
                    lblRegion.Text = dt.Rows[0]["RegionName"].ToString();
                    lblCountry.Text = dt.Rows[0]["CountryName"].ToString();
                    lblCountryCode.Text = dt.Rows[0]["CountryCode"].ToString();
                }
            }
        }
   

    private DataTable GetLocation(string ipaddress)
    {
        dt = new DataTable();
        WebRequest wreq = WebRequest.Create("http://api.ipinfodb.com/v2/ip_query.php?key=4066276f57ed6431a8a1cf207d882d06187aa68edf7f2734e1942d4e45450fd5&ip=" + ipaddress + "&timezone=false");
        WebProxy proxy = new WebProxy("http://api.ipinfodb.com/v2/ip_query.php?key=4066276f57ed6431a8a1cf207d882d06187aa68edf7f2734e1942d4e45450fd5&ip=" + ipaddress + "&timezone=false", true);
        wreq.Proxy = proxy;
        wreq.Timeout = 5000;
        WebResponse wres = wreq.GetResponse();
        XmlTextReader xmlRead = new XmlTextReader(wres.GetResponseStream());
        DataSet ds = new DataSet();
        ds.ReadXml(xmlRead);
        return ds.Tables[0];
    }
   
}

 Code For Default.aspx Page

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     City        :   <asp:Label ID="lblCity" runat="server" ></asp:Label><br />
     Region      :   <asp:Label ID="lblRegion" runat="server" ></asp:Label><br />
     Country     :   <asp:Label ID="lblCountry" runat="server" ></asp:Label><br />
     CountryCode :   <asp:Label ID="lblCountryCode" runat="server" ></asp:Label>     
    </div>
    </form>
</body>
</html>



Thursday 23 December 2010

Server Error in '/' Application and Invalid postback or callback argument

Problem :
Server Error in '/' Application.

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +358
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
   System.Web.UI.WebControls.TextBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +22
   System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +381
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2965


Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42


Answer:  Add EnableEventValidation="false"  on Page directory 
<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false"  Codebehind="SearchResults.aspx.cs"
    Inherits="CartridgeSite.SearchResults" %>

Client side validation using javascript

<script language="javascript" type="text/javascript">
function validate2()
{
     
      if (document.getElementById("<%=txtName.ClientID%>").value=="")
      {
                 alert("Enter First Name");
                 document.getElementById("<%=txtName.ClientID%>").focus();
                 return false;
      }
                 
      if (document.getElementById("<%=txtEmail.ClientID%>").value=="")
      {
                 alert("Enter Email");
                 document.getElementById("<%=txtEmail.ClientID%>").focus();
                 return false;
      }
        var emailPat = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;   
        var emailid=document.getElementById("<%=txtEmail.ClientID %>").value;
        var matchArray = emailid.match(emailPat);
        if (matchArray == null)
        {               
                   alert("Enter Correct Email");
                   document.getElementById("<%=txtEmail.ClientID %>").focus();
                   return false;
        }
       
        if (document.getElementById("<%=txtSubject.ClientID%>").value=="")
      {
                 alert("Enter Subject");
                 document.getElementById("<%=txtSubject.ClientID%>").focus();
                 return false;
      }
        return true;
}
</script>

<table width="90%" border="0" align="center" cellpadding="2" cellspacing="0">
                                        <tr>
                                            <td width="30%">
                                                <strong>Name :</strong></td>
                                            <td width="70%">
                                                <asp:TextBox ID="txtName" runat="server" CssClass="text_field" Style="width: 250px"></asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <strong>Email ID :</strong></td>
                                            <td>
                                                <asp:TextBox ID="txtEmail" runat="server" CssClass="text_field" Style="width: 250px"></asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <strong>Subject :</strong></td>
                                            <td>
                                                <asp:TextBox ID="txtSubject" runat="server" CssClass="text_field" Style="width: 250px"></asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <strong>Description :</strong></td>
                                            <td>
                                                <asp:TextBox ID="txtDescription" runat="server" TextMode="MultiLine" CssClass="text_field"
                                                    Style="width: 350px"></asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                &nbsp;</td>
                                            <td>
                                                &nbsp;</td>
                                        </tr>
                                        <tr>
                                            <td>
                                                &nbsp;</td>
                                            <td>
                                                <asp:ImageButton ID="imgbtnSend" runat="server" OnClientClick="return validate2()" ImageUrl="images/send.png" Width="46"
                                                    Height="24" border="0" OnClick="imgbtnSend_Click" />
                                                <asp:ImageButton ID="imgbtnReset" runat="server" ImageUrl="images/send.png" Width="46"
                                                    Height="24" border="0" OnClick="imgbtnReset_Click" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                &nbsp;</td>
                                            <td>
                                                &nbsp;</td>
                                        </tr>
                                    </table>

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Blogger