I tried to save a login record to SQL Server.
But I get an error:
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
on the cmd.ExecuteNonQuery();
line of code when Login.aspx
is running.
What is wrong in these codes ?
My table Login
:
[Id] [int] IDENTITY(1,1) NOT NULL,
[Url] [nvarchar](150) NOT NULL,
[Time] [datetime] NOT NULL,
[Count] [int] NOT NULL,
[PcName] [nvarchar](50) NOT NULL,
[Browser] [nvarchar](50) NOT NULL,
[IpAddress] [nvarchar](50) NOT NULL
C# code:
SqlConnection conn= "...";
protected void Page_Load(object sender, EventArgs e)
{
Logins();
}
public void Logins()
{
if (!Page.IsPostBack)
{
Application["hit"] = Convert.ToInt32(Application["hit"].ToString());
}
string strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
string url = HttpContext.Current.Request.Url.AbsoluteUri;
string page = System.IO.Path.GetFileName(url);
string browser = Request.Browser.Browser;
string pcname = Convert.ToString(ipEntry.HostName);
String IP = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
IP = stream.ReadToEnd();
}
int first = IP.IndexOf("Address: ") + 9;
int last = IP.LastIndexOf("</body>");
IP = IP.Substring(first, last - first);
string sql = "INSERT INTO Login(Url, Time, Count, Browser, PcName, IpAddress) values (@Url, @Time, @Count, @Browser, @PcName, @IpAddress)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("Time", DateTime.Now.ToString());
cmd.Parameters.AddWithValue("Url", page.Trim());
cmd.Parameters.AddWithValue("Count", Convert.ToInt32(Application["hit"].ToString()));
cmd.Parameters.AddWithValue("Browser", browser.Trim());
cmd.Parameters.AddWithValue("PcName", pcname.Trim());
cmd.Parameters.AddWithValue("IpAddress", IP.Trim());
cmd.ExecuteNonQuery();
}