Web Technologies

BLOG for Web Technologies

Freewares, Free E-Books Download, SEO, Tips, Tricks, Tweaks, Latest News, .Net, PHP, ASP, ASP.Net, CSP, MS SQL Server, MySQL, Database
earnptr.com
Thursday, September 10, 2009
Error Logging using ASP.NET 2.0
Errors and failures may occur during development and operation of a website. ASP.NET 2.0 provides tracing, instrumentation and error handling mechanisms to detect and fix issues in an application.

In this article, we will adopt a simple mechanism to log errors and exceptions in our website. We will be using a mechanism where the user will be redirected to a separate page whenever an error is encountered in the application. Simultaneously, the error will get logged in a text file on the server. The error file will be created on a daily basis, whenever the error is encountered. Having said that, let us now see some code.

Step 1: Start by creating an Error folder where all errors will be logged. Right click the website > New Folder. Rename the folder to “Error”. Also add a web.config file, if one does not already exist in your site. Right click the website > Add New Item > Web.config.

Step 2: Now we will create the error handler code. To do so, right click your website > Add New Item > select Class. Rename the class to ‘ErrHandler.cs’ and click on ‘Add’. When you do so, you will be prompted with a message to place the class in ‘App_Code’ folder. Accept the message to place the class in the 'App_Code' folder.

Step 3: Now let us add functionality to the ErrHandler class. This class will accept the error message and write the message in a text file. One text file will be created for each day. If the text file already exists, the message will be appended to the text file. If not, a new text file will be created based on today’s date and error message will be written in it.

The code will look similar to the following:

C#

/// Handles error by accepting the error message

    /// Displays the page on which the error occured

    public static void WriteError(string errorMessage)

    {

        try

        {

            string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";

            if(!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))

            {

               File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();

            }

            using (StreamWriter w =File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))

            {

                w.WriteLine("\r\nLog Entry : ");

                w.WriteLine("{0}",DateTime.Now.ToString(CultureInfo.InvariantCulture));

                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +

                              ". Error Message:" + errorMessage;

                w.WriteLine(err);

                w.WriteLine("__________________________");

                w.Flush();

                w.Close();

            }

        }

        catch (Exception ex)

        {

            WriteError(ex.Message);

        }

 

    }

VB.NET

''' Handles error by accepting the error message

    ''' Displays the page on which the error occured

    Public Shared Sub WriteError(ByVal errorMessage As String)

        Try

            Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"

            If (NotFile.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then

                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()

            End If

            Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))

                w.WriteLine(Constants.vbCrLf & "Log Entry : ")

                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))

                Dim err As String = "Error in: " & System.Web.HttpContext.Current.Request.Url.ToString() & ". Error Message:" & errorMessage

                w.WriteLine(err)

                w.WriteLine("__________________________")

                w.Flush()

                w.Close()

            End Using

        Catch ex As Exception

            WriteError(ex.Message)

        End Try

 

    End Sub

That was our ErrHandler class. We will now see how to use this Error Handler class and handle errors at the page level as well as at the application level.

Handling errors at Page Level

In the Default.aspx, drag and drop a button from the toolbox. Rename this button to btnError and set the Text as ‘Throw Handled Exception’. Here we will throw an exception. Since we have a catch block defined, the exception will be caught and the error will be logged in the Error folder. Since a text file with today’s date, does not exists, a new text file will be created by the code.

The button click handler will look similar to the following:

C#

protected void btnHandled_Click(object sender, EventArgs e)

    {

        try

        {

            throw new Exception("Sample Exception");

        }

        catch (Exception ex)

        {

            // Log the error to a text file in the Error folder

            ErrHandler.WriteError(ex.Message);

        }

    }

VB.NET

Protected Sub btnHandled_Click(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles btnHandled.Click

        Try

            Throw New Exception()

        Catch ex As Exception

            ' Log the error to a text file in the Error folder

            ErrHandler.WriteError(ex.Message)

        End Try

    End Sub

Now with the code in place, run the application and click on the button. Since we have handled the error and logged the exception in our code, you will not notice anything when the button is clicked. However, close the application and refresh the Error folder. You will see a new text file created with today’s date. The exception has been logged successfully as shown below. The date and time will differ on your machine.

Log Entry :

01/11/2008 23:33:46

Error in: http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception

__________________________

Redirecting users on unhandled errors

Let us see how to catch unhandled errors and redirect the user to a different page, whenever such an unhandled error occurs at the application level.

To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:

C#

 void Application_Error(object sender, EventArgs e)

    {

        // Code that runs when an unhandled error occurs

        Exception objErr = Server.GetLastError().GetBaseException();

        string err = "Error in: " + Request.Url.ToString() +

                          ". Error Message:" + objErr.Message.ToString();

        // Log the error

        ErrHandler.WriteError(err);       

    }

VB.NET

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

        ' Code that runs when an unhandled error occurs       

        Dim objErr As Exception = Server.GetLastError().GetBaseException()

        Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()

        ' Log the error

        ErrHandler.WriteError(err)

    End Sub

We capture the error using the Server.GetLastError(). Now to redirect users to a different page whenever an unhandled error occurs, open your web.config file and locate the <customErrors> tag and uncomment it. After removing the comment, the tag will look similar to the following code:

<!--

            The <customErrors> section enables configuration

            of what to do if/when an unhandled error occurs

            during the execution of a request. Specifically,

            it enables developers to configure html error pages

            to be displayed in place of a error stack trace.        -->

 

                  <customErrorsmode="RemoteOnly"defaultRedirect="GenericErrorPage.htm">

                        <errorstatusCode="403"redirect="NoAccess.htm" />

                        <errorstatusCode="404"redirect="FileNotFound.htm"/>

                  </customErrors>

Now change:

 mode="RemoteOnly"tomode="On"

defaultRedirect="GenericErrorPage.htm" todefaultRedirect="ErrorPage.aspx"

The modified code will now look like this:

<customErrorsmode="On"defaultRedirect="ErrorPage.aspx">

                        <errorstatusCode="403"redirect="NoAccess.htm" />

                        <errorstatusCode="404"redirect="FileNotFound.htm"/>

                  </customErrors>

This configuration will now redirect the user to an Error page when an error occurs. Let us create this error page and display some message to the user.

Right Click Project > Add New Item> Create a new ErrorPage.aspx page in the application and display a sample message on the page informing the user that an error has occurred.

To test our functionality, go back to Default.aspx, add another button and rename it to btnUnhandled and set its Text property to ‘Throw Unhandled Exception’. Here instead of throwing the exception as we did for ‘btn_Error’, we will introduce a ‘Divide By Zero’ exception and not handle it. Observe that there is no try catch block as shown below. So when the error occurs, the user will be redirected to the ‘ErrorPage.aspx’ as a result of the changes made in our web.config file.

C#

protected void btnHandled_Click(object sender, EventArgs e)

    {

        try

        {

            throw new Exception("Sample Exception");

        }

        catch (Exception ex)

        {

            // Log the error to a text file in the Error folder

            ErrHandler.WriteError(ex.Message);

        }

    }

VB.NET

Protected Sub btnUnhandled_Click(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles btnUnhandled.Click

        Dim i As Integer = 1

        Dim j As Integer = 0

        Response.Write(i \ j)

    End Sub

 

Run the application and click on the ‘Throw Unhandled Exception’ button. You will observe that the user will be automatically redirected to the Error Page and the error will be logged in the Error folder. Well that’s it.

In this article, we saw how to implement a simple error logging system in our application. Logging errors can be very useful and helps us detect errors during development and operation of a website. ASP.NET also provides some advanced options titled under ‘Health Monitoring’ where the errors can be stored in Sql Server or even emailed to the administrator based on the criticality of it.

Labels: , ,

posted by WebTeks @ 3:19 AM   3 comments
Tuesday, September 8, 2009
Adding Meta Tags to the Head in ASP.NET 2.0
How to dynamically add meta tags in ASP.NET 2.0

The HtmlMeta class is provided for just that. You can easily create a HtmlMeta object and add it to the Controls collection in the HtmlHead class exposed via Page.Header. Here's a few samples:


// Render: <meta name="keywords" content="Some words listed here" />

HtmlMeta meta = new HtmlMeta();

meta.Name = "keywords";

meta.Content = "Some words listed here";

this.Header.Controls.Add(meta);


// Render: <meta name="robots" content="noindex" />

meta = new HtmlMeta();

meta.Name = "robots";

meta.Content = "noindex";

this.Header.Controls.Add(meta);


// Render: <meta name="date" content="2006-03-25" scheme="YYYY-MM-DD" />

meta = new HtmlMeta();

meta.Name = "date";

meta.Content = DateTime.Now.ToString("yyyy-MM-dd");

meta.Scheme = "YYYY-MM-DD";

this.Header.Controls.Add(meta);





Labels: , ,

posted by WebTeks @ 9:56 PM   0 comments
Thursday, September 3, 2009
How to upload an image using ASP.NET

Introduction

This article is for beginners who want to learn how to upload images.

Step 1

First add the following HTML tag :-


<input id="Upload" style="Z-INDEX: 102; LEFT: 104px; WIDTH: 288px;
POSITION: absolute; TOP: 64px; HEIGHT: 22px"
type="file"
size="28" name="Upload" runat="server">

This control will upload your image.

Step 2

Create a Button called "Upload" and another called "LoadImage". Add the DataGrid and do required bindings.

Step 3

Lets see some sample code now.


    private void Button1_Click(object sender, System.EventArgs e)
{
//It verifies if the archive exists

if (Upload.PostedFile != null)
{
//To create a PostedFile

HttpPostedFile File = Upload.PostedFile;

//Create byte Array with file len

byte[] Data = new Byte[File.ContentLength];
//force the control to load data in array

File.InputStream.Read(Data,0,File.ContentLength);

int i = 0;

//Dysplay array data in textbox

for (i=0;i//Create procedure parameter

object[] obj = new object[1];

obj[0] = Data;

//Execute the procedure with Microsoft.ApplicationBlocks.Data

//Simple procedure

/*CREATE PROCEDURE sp_img(@img image) AS

insert into tb_img values(@img)*/


//record data

SqlHelper.ExecuteNonQuery(connectionString,"sp_img",obj);

}
}

private void Button2_Click(object sender, System.EventArgs e)
{
//Bind data to your grid

//more details consulting

//Working DataGrid TemplateColumns and Bind this Columns

DataSet ds = SqlHelper.ExecuteDataset(connectionString,
"sp_load_img",null);
grid.DataSource = ds.Tables[0].DefaultView;
grid.ObjectName = "Image1";
grid.FieldName = "img";
grid.Editable = false;
grid.DataBind();
grid.DataBindObjects(grid,ds,0,grid.PageSize);

int i =0;

for (i=0;i0].Rows.Count;i++)
{
//test your bitmap is valid

//Demonstration

byte[] bits = (byte[]) ds.Tables[0].Rows[i]
["img"];
MemoryStream memorybits = new MemoryStream(bits);
Bitmap bitmap = new Bitmap(memorybits);
}


}

private void grid_PageIndexChanged(object source,
System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
//Page your grid

//Bind data to your grid

//more details consulting

//Working DataGrid TemplateColumns and Bind this Columns

grid.CurrentPageIndex =e.NewPageIndex;
DataSet ds = SqlHelper.ExecuteDataset(connectionString,
"sp_load_img",null);
grid.DataSource = ds.Tables[0].DefaultView;
grid.ObjectName = "Image1";
grid.FieldName = "img";
grid.Editable = false;
grid.DataBind();
grid.DataBindObjects(grid,ds,e.NewPageIndex,grid.PageSize);

}
}

Labels: , ,

posted by WebTeks @ 10:31 PM   0 comments
Previous Post
Archives
Links
Template by

Free Blogger Templates

BLOGGER

Subscribe in NewsGator Online Subscribe in Rojo Add to Google Add to netvibes Subscribe in Bloglines Web Developement Blogs - BlogCatalog Blog Directory Blogarama - The Blog Directory Blog Directory & Search engine Computers Blogs - Blog Top Sites Top Computers blogs