Monday, June 13, 2011

Error Loging in ASP.NET


Error Loging in ASP.NET

Run this code to create table :

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[errorLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[errorLog]
GO

CREATE TABLE [dbo].[errorLog] (
 [errID] [int] IDENTITY (1, 1) NOT NULL ,
 [errorPage] [nvarchar] (150) ,
 [errorDate] [datetime] NULL
) ON [PRIMARY]
GO

Now we will create our stored procedure :

CREATE PROCEDURE dbo.insertLog
@page NVARCHAR(150)
AS
BEGIN
INSERT ErrorLog
( errorPage, errorDate )
VALUES
( @page, GETDATE() )
END
GO

Now if doed not exist web.config file create one or modify it  with those codes :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   
  <system.web>
    <compilation defaultLanguage="VB" debug="true" />

    <customErrors mode="On" defaultRedirect="error.aspx" />
 </system.web>
  <appSettings>
 <add key="strCon" value="server=localhost;User id=sa;password=;database=dotnet" />
  </appSettings>
</configuration>


Ok. Our hard work finished after modifying our database connection. Double check that you have run sql scripts correctly without any error. You may use SQL Query Analyzer. Do not miss to check SQL connection. After editing and upload this script to your site.

<%@ Page Language="VB" Debug="true" %>
<%@ import namespace="System.Data" %>
<%@ import namespace="System.Data.SQLClient" %>
<%@ import namespace="System.Diagnostics" %>

<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)

 Dim objCon As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("strCon"))
 Dim objCmd As SqlCommand = New SqlCommand("insertLog", objCon)
 objCmd.CommandType = CommandType.StoredProcedure
 Dim strParm As SqlParameter = objCmd.Parameters.Add("@Page", SqlDbType.NVarChar, 150)
 strParm.Value = trim(request.querystring("aspxerrorpath"))
 objCon.Open()
 objCmd.ExecuteNonQuery()
 objCon.Close()
                       
end sub
</script>
<html>
<head>
</head>
<body>


<h2>Sorry, A error has occurred in this page.</h2>
</body>
</html>

No comments:

Post a Comment