European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET 4 Hosting :: Global Exception Handling with ASP.NET

clock December 23, 2011 05:55 by author Scott

You can't debug a problem if you don't know that it exists. After you take your web application live, you are no longer the only one who is using it (hopefully), so you need an effective plan to track exceptions when they occur while others are surfing your site. A great way to do this is to implement an exception handler at the application level. This will allow you to consolidate the logging and notification parts of your exception handling in one convenient place. As you'll see from the code examples that follow, your global exception handler can handle both specific exceptions that you trap in your code and generic unhandled exceptions.

After your global exception handler has done its work, you'll want to redirect the users of your website to a friendly page that tells them that something has gone wrong, and then provide them with customer support information as well as a link back to your web application's home page.

Implementing the Application_Error Event Handler

The HttpApplication class in the System.Web namespace implements an Error event handler. This should not be confused with the HttpApplicationState class, which contains the definition for the Application object that you use in a typical ASP.NET page. You can implement this event handler in the global.asax file as shown in Listings 1 and 2.

Listing 1:
Application_Error Event Handler

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Diagnostics" %>

<script language="C#" runat="server">
void Application_Error(object sender, EventArgs e)
   //get reference to the source of the exception chain
   Exception ex = Server.GetLastError().GetBaseException();

   //log the details of the exception and page state to the
   //Windows 2000 Event Log
   EventLog.WriteEntry("Test Web",
     "MESSAGE: " + ex.Message +
     "\nSOURCE: " + ex.Source +
     "\nFORM: " + Request.Form.ToString() +
     "\nQUERYSTRING: " + Request.QueryString.ToString() +
     "\nTARGETSITE: " + ex.TargetSite +
     "\nSTACKTRACE: " + ex.StackTrace,

   //Insert optional email notification here...

Listing 2:
Application_Error Event Handler (VB)

<%@ Application Language="VB" %>
<%@ Import Namespace="System.Diagnostics" %>

<script language="VB" runat="server">
Sub Application_Error(sender As Object, e As EventArgs)
   'get reference to the source of the exception chain
   Dim ex As Exception = Server.GetLastError().GetBaseException()

   'log the details of the exception and page state to the
   'Windows 2000 Event Log
   EventLog.WriteEntry("Test Web", _
     "MESSAGE: " & ex.Message & _
     "\nSOURCE: " & ex.Source & _
     "\nFORM: " & Request.Form.ToString() & _
     "\nQUERYSTRING: " & Request.QueryString.ToString() & _
     "\nTARGETSITE: " & ex.TargetSite & _
     "\nSTACKTRACE: " & ex.StackTrace, _

   'Insert optional email notification here...
End Sub

First, you have to be sure to set a reference to the System.Diagnostics namespace. You'll use the EventLog class in this namespace to write exception details to the Windows 2000 event log. Inside the Application_Error event handler, you declare an Exception object and initialize it through a call to Server.GetLastError().GetBaseException().

The GetLastError() method of the Server object simply returns a reference to a generic HttpException. This is a wrapper that was placed around the original exception when it was passed from your ASP.NET page to the Application_Error event. To get access to the original exception, you need to call its GetBaseException() method. This will yield the original exception information, regardless of how many layers have been added to the exception tree.

Next, you make a call to the WriteEntry() method of the EventLog class. There are several overloaded signatures for this method. The implementation that we chose to use here accepts three parameters. The first parameter is the source of the error. It appears in the Source field of the Windows 2000 event log viewer. The second parameter is the log data itself. You can see that we have added a lot of information to help track down what caused the exception, including the exception message, the exception source, the contents of the Form collection, the contents of the QueryString collection, the name of the method that generated the error (TargetSite), and a complete stack trace.

Note that the stack trace contains the name of the file that was the source of the exception. However, it strips off the contents of the query string—hence the need to specifically include it previously. The third and final parameter to the WriteEntry() method is an enumeration of type EventLogEntryType. We chose to use the Error element of the enumeration.

At the end of the event handler, we inserted a comment block where you can optionally put code to email the exception information to your IT support staff. Discussion of the different messaging paradigms in the .NET framework is beyond the scope of this article.

After the Application_Error event has completed its work, it automatically redirects the user of your web application to your custom error page. Optionally, however, you can use the Server.ClearError() method after you have logged the exception and redirect your user using the Server.Execute() method, specifying the page that you want to load in the user's browser.

The code that you have just implemented will capture all unhandled exceptions that occur in your web application. If you need to do some cleanup in the event of an exception and you implement structured exception handling inside your ASP.NET page, you can still leverage the global exception handler. Listings 3 and 4 present examples of how you would do it.

Listing 3: Throwing a Handled Exception

<%@ Page Language="C#" %>

<script language="C#" runat="server">
protected void button1_click(object sender, EventArgs e)
     //do some complex stuff

     //generate your fictional exception
     int x = 1;
     int y = 0;
     int z = x / y;
   catch(DivideByZeroException ex)
     //put cleanup code here

<form runat="server">
   <asp:button id="button1" onclick="button1_click"
     text="click me" runat="server" />

Listing 4: Throwing a Handled Exception (VB)

<%@ Page Language="VB" %>

<script language="VB" runat="server">
Protected Sub button1_click(sender As Object, e As EventArgs)
     'do some complex stuff

     'generate your fictional exception
     Dim x As Integer = 1
     Dim y As Integer = 0
     Dim z As Integer = x / y
   Catch ex As DivideByZeroException
     'put cleanup code here
   End Try
End Sub

<form runat="server">
   <asp:button id="button1" onclick="button1_click"
     text="click me" runat="server" />

The code in these listings defines a web form with a text box and a button. When you click the button, it fires the button1_click event handler. In the event handler, you would do processing as usual. For the purposes of this demonstration, however, you intentionally generate a DivideByZeroException. This takes you to the catch block. Here, you can perform any page-specific cleanup code before calling throw(ex) to pass your exception to the global exception handler to be logged to the Windows 2000 event log.

When the global exception handler is finished logging the error, the defaultredirect attribute that you set in your config.web file (discussed in the next section) takes over, and you are redirected to the error.aspx page to display your friendly message to the user of your web application.

Setting Up the Custom Error Page

The first step in setting up a custom error page is to modify your config.web file to route the users of your web application to a friendly error page if an exception occurs. It helps to boost users' confidence in your site when it can recover gracefully from the unexpected. Add the code in Listing 5 to the config.web file of your web application.

Listing 5: Adding the <customerrors> Tag to Your Config.web File

  <customerrors mode="On" defaultredirect="error.aspx" />

Note that your config.web file might already have a <customerrors> tag, so you might only need to modify the existing one. The mode attribute of the <customerrors> tag has three settings: On, Off, and RemoteOnly. If the mode is On, users will always be redirected to the custom error page specified by the defaultredirect attribute if an unhandled exception occurs. If the mode is Off, the details of any exception that occurs will be shown to the user in the browser. The RemoteOnly mode is a hybrid of the two other modes. If you are browsing your web application while sitting at the web server itself, it behaves like the Off mode. All other browsers of the site will get the behavior of the On mode. If no defaultredirect attribute is set, a default ASP.NET "friendly, yet not so friendly" message will be displayed to the user when exceptions occur.

Next, you need to build the custom error page (error.aspx) referenced in the config.web file. This is just an ordinary ASP.NET page that includes helpful information for the user of your web application if an error occurs. An extremely simple example is the one in Listing 6.

Listing 6: Simple Custom Error Page

<title>My web application: Error page</title>
An unexpected error occurred in the application. Please contact [ccc]
customer service at (800)555-5555. Or, you can click [ccc]
<a href="home.aspx">here</a> to go back to the homepage. [ccc]
Thank you for your patience.

European ASP.NET Hosting :: How to Set Up Your .NET Web Application to Use MySQL as Your ASP.NET Membership Provider

clock December 12, 2011 08:15 by author Scott

In this tutorial, I will show you how to setting up your .NET web application to use MySQL as your ASP.NET Membership Provider.

1. Download and install MySQL Connector/Net 5.2.1 or later version

2. Add a reference to MySQL.Web to your web application.
C:\Program Files\MySQL\MySQL Connector Net 5.2.1\Web Providers\MySql.Web.dll

3. Add the autogenerateschema=”true” attribute. Since the MySQL database schema wasn’t automatically created for me, I ended up using the autogenerateschema attribute. The attribute will signal the MySQL provider to build (or upgrade) the database schema.The MySQL 5.2.1 release notes state the following…

Using the new provider schema
For this release. the only way to upgrade a given server to the new schema is to
add a configuration option for one of your providers. The option is ‘autogenerateschema’.
By setting this to true, the provider will silently upgrade the server to the new schema.
Please note that there is no reversing of this procedure so please just do this on test
setups and not on your production systems.

Personally, I found it easiest to just add autogenerateschema=”true” to my machine.config on my development machine (as opposed to web.config) and it’s under providers…

<add name=”MySQLMembershipProvider” autogenerateschema=”true” ….

Save the changes.

4. Edit your web application’s web.config.

<remove name=”LocalMySqlServer”/>
<add name=”LocalMySqlServer” connectionString=”Datasource=localhost;Database=DB;uid=Username;pwd=Password;”
providerName=”MySql.Data.MySqlClient”/> </connectionStrings>

Then, save the changes.

5. Build your Web Application.

6. Config your web application.

Under the ASP.NET Web Site Administration Tool provider tab, click “Select a Different Provider (advanced)” and change the provider to MySQLMembershipProvider.

At this point, you should be able to use MySQL as your ASP.NET Membership and Role Provider (the tables will be automatically built for you).

After the tables are built, you’ll want to setup your web application’s web.config (using your machine.config as a template) so that you will have access to all of the membership provider settings.

European ASP.NET Hosting :: How to Disable or Make a ListItem Non selectable ASP.Net DropDownList Using jQuery

clock December 5, 2011 08:19 by author Scott

Sometimes, we may want to add some ListItem that are not clickable or selectable in ASP.Net DropDownList.  The non selectable items will be an informational list items that may help users to understand the items. For example, consider a DropDownList that has list of states of different country. It will be user friendly if we have a non selectable country name before populating the list of states under that country. Something like below,

The below jQuery code will help you to do the same,

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>   
    <script type="text/javascript">      
        $(function() {
        $("#<% =DropDownList1.ClientID %> > option[value=Country]").attr("disabled", "disabled")          
    <form id="form1" runat="server">
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
            <asp:ListItem Text="Select your state" Value=""></asp:ListItem>
            <asp:ListItem Text="India" Value="Country"></asp:ListItem>
            <asp:ListItem Text="-Karnataka" Value="1"></asp:ListItem>
            <asp:ListItem Text="-TamilNadu" Value="2"></asp:ListItem>
            <asp:ListItem Text="-Maharastra" Value="3"></asp:ListItem>
            <asp:ListItem Text="-Kerala" Value="4"></asp:ListItem>
            <asp:ListItem Text="United States" Value="Country"></asp:ListItem>
            <asp:ListItem Text="-Alabama" Value="5"></asp:ListItem>
            <asp:ListItem Text="-Alaska" Value="6"></asp:ListItem>
            <asp:ListItem Text="-California" Value="7"></asp:ListItem>
            <asp:ListItem Text="-Florida" Value="8"></asp:ListItem>

The above jQuery code will disable all the list items that have Country as value and thus making it non selectable.
Happy Coding!!

European ASP.NET 4 Hosting :: How to Fix "Could not load type" error message in Visual C# .NET

clock December 2, 2011 05:46 by author Scott

Sometimes when you browse to an .aspx page, you may receive one of the following error messages:

Could not load type 'Namespace.Global'.


Could not load type 'Namespace.PageName'.

In this turorial I will show you how to fix it. This is caused by These errors occur if the .aspx page or the Global.asax page contains a reference to a code-behind module and if the application has not been built.


·         Use the C# command line compiler (CSC.exe) to run the following command:

    csc /t:library /r:System.web.dll /out:mydll.dll myfile.cs

·         In Microsoft Visual Studio .NET, click Build on the Build menu.

Hope it help

About is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.

Tag cloud

Sign in