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,
     EventLogEntryType.Error);

   //Insert optional email notification here...
}
</script>

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, _
     EventLogEntryType.Error)

   'Insert optional email notification here...
End Sub
</script>

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)
{
   try
   {
     //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
     throw(ex);
   }
}
</script>

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

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)
   Try
     '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
     Throw(ex)
   End Try
End Sub
</script>

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

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

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

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

<html>
<head>
<title>My web application: Error page</title>
</head>
<body>
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.
</body>
</html>



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…

<membership>
<providers>
<add name=”MySQLMembershipProvider” autogenerateschema=”true” ….
</providers>

Save the changes.


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

<connectionStrings>
<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")          
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
            <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>
        </asp:DropDownList>


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'.

-or-

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.

SOLUTION

·         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



European ASP.NET 4 Hosting :: HTML Encoded Expressions in ASP.NET4

clock November 18, 2011 07:51 by author Scott

Today I would like to discuss an interesting feature that is available only in ASP.NET4. It is primarily used in MVC3 applications.

ASP.NET 4.0 comes with a Encoded Expressions <%: expression %> that will automatically convert string into html encoded. Now we can replace all occurrences of <%= %> with <%: %>.

SO what is the difference between these two? Are they same?

No they are not. The main difference is when you use the new syntax our code get encoded. Any html script in side do not gets executed by the browser.


It is just treated as content. In the previous versions you might be using Server.HtmlEncode(<%=expression %>).

So this new syntax does exactly same function as this method. We can use HtmlString type to indicate encoding is unnecessary.

Proof of Concept

I have created a Test method that returns string and that string has some HTML characters like < > to be encoded


public static string Test()
{  
    return "alert('Hello World!!! returns javascript');  HTML Encoded expression";
}

Now add 2 aspx pages. In the first page add this code.

<DIV>
<form id="form1" runat="server">
    <strong><%: Test()%></strong>
</form>
</div>
</DIV>

Now In the Second aspx page use this syntax

<DIV>
<form id="form1" runat="server">
    <strong><%= Test()%></strong>
</form>
</div>
</DIV>

Run this pages on the browser one after the other. Now if you observe, first page gives a just text where as 2nd page is not encoded it returns the script alert message along with text . And look at the viewsource you can see the difference exactly.


Advantages

-    General security threats for ASP.Net Web applications are Cross-site script injection attacks and HTML encoding attacks. This feature is nice handy way to eliminate javascript injection in your web applications.

-    Now it is easy to replace <%=exp %> to <%:exp%> and make your code or data more secured.

-    Now We do not need to specify Validate-Request to validate HTML Scripts in ASP.NET, which you may be doing it in web.config or pagelevel

Is it not so interesting?. So start playing with the feature.

Hope this helps. Let me know if any questions are clarifications.



European ASP.NET Hosting :: How to Connect MySQL Server with .NET in C# or ASP.NET

clock November 8, 2011 05:18 by author Scott

In this tutorial, I will show you how to connect to MySQL Server with .NET in C# or ASP.NET. What requirements do you need?

1. Please download
MySQL Connector/Net.
2. After you add a reference to your project, it is probably in C:\Program Files\MySQL\MySQL Connector Net 5.0.7\Binaries\.NET 2.0 folder, add the MySql.Data.dll file as a reference.
3. Make your connection string, the following code will shows a standard MySQL connection string
.

using MySql.Data.MySqlClient;
public static string GetConnectionString()
{
string connStr =
String.Format("server={0};user id={1}; password={2};
database=yourdb; pooling=false", "yourserver",
"youruser", "yourpass");

return connStr;
}

4. Then create an instance from MySql.Data.MySqlClient.MySqlConnection as shown below.

MySql.Data.MySqlClient.MySqlConnection mycon
= new MySqlConnection( GetConnectionString());

5. Then try to open the MySQL connection.

if(mycon .State != ConnectionState.Open)
try
{
mycon .Open();
}
catch (MySqlException ex)
{
throw (ex);
}

Simple right?? J



European ASP.NET 4 Hosting :: Dynamic Programming in C# 4.0

clock October 10, 2011 07:21 by author Scott

C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects. The type of these objects is resolved at run-time instead of compile-time. A new keyword dynamic is introduced to declare dynamic typed object. The keyword tells the compiler that everything to do with the object, declared as dynamic, should be done dynamically at the run-time using Dynamic Language Runtime(DLR). Remember dynamic keyword is different from var keyword. When we declare an object as var, it is resolved at compile-time whereas in case of dynamic the object type is dynamic and its resolved at run-time. Let’s do some coding to see advantage of Dynamic Typed Objects :)

A year back I wrote a code of setting property of an object using Reflection:

   1: 
Assembly asmLib= Assembly.LoadFile(@"C:\temp\DemoClass\bin\Debug\DemoClass.dll");
   2:  Type demoClassType = asmLib.GetType("DemoClass.DemoClassLib");
   3:  object demoClassobj= Activator.CreateInstance(demoClassType);
   4:  PropertyInfo pInfo= demoClassType.GetProperty("Name");
   5:  pInfo.SetValue(demoClassobj, "Adil", null);

Notice line 3-5 creates instance of ‘demoClassType’ and set property ‘Name’ to ‘Adil’. Now with C# 4.0 line # 3-5 can be written as simple as:


dynamic dynamicDemoClassObj = Activator.CreateInstance(demoClassType);
dynamicDemoClassObj.Name = "Adil";

Simple isn’t it? Let’s see a slide from Anders Hejlsberg’s session at PDC 2008:



From the above slide, you can call method(s) such as x.ToString(), y.ToLower(), z.Add(1) etc and it will work smoothly :)

This feature is great and provides much flexibility for developers. In this post, we explore the dynamic typed object in C# 4.0. We will explore dynamic in detail and other features as well in the coming posts. Of course there are pros and cons of dynamic programming as well but where C# is going is something like having features of both static languages and dynamic languages.



European ASP.NET 4 Hosting :: Binding data in XML file to GridView

clock October 6, 2011 08:39 by author Scott

Let say you have an XML file and you want to show the information (data in XML file) in GridView. Here, I am going to show you, how to DataBind asp:GridView to the data contained in an XML document.

A standard XML file will look like below:

<?xml version="1.0" encoding="utf-8" ?>
<Fruits>
    <Fruit>
        <id>1</id>
        <name>Apple</name>
        <color>Red</color>
    </Fruit>
    <Fruit>
        <id>2</id>
        <name>Mango</name>
        <color>Yellow</color>
    </Fruit>
</Fruits>

The entity in this file is a Fruit. Apparently, there are three columns (sub-nodes of Fruit node) named id, name and color. However, you can’t bind the data defined in this standard XML file directly to the GridView.

First you have to transform the XML data into a format understandable to GridView (e.g. tabular or rows collection format). You can transform a standard XML document into various formats (e.g. HTML markups) by using XSLT. XML document transformation to different XML formats using XSLT demonstrates a basic data transformation for an XML document and contains the transformation template definition for XSLT file.

Once you have applied a valid XML data tranformation, you can use XmlDataSource control to make a connection to your XML file and then bind it to GridView directly. Below is the markup code to bind a GridView to an XmlDataSource.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="XmlDataSource1">
        <Columns>
            <asp:BoundField DataField="name" HeaderText="Fruit Name" />
            <asp:BoundField DataField="color" HeaderText="Fruit Color" />
        </Columns>
    </asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile1.xml" TransformFile="~/XSLTFile1.xslt">
</asp:XmlDataSource>


Here, XMLFile1.xml is the actual XML file containg the data you want to bind GridView with and XSLTFile1.xslt is the file containing the desired transformation template.

That's all, I hope you have got an idea of

1. How to bind gridview to xml data
2. How to bind gridview to xml file
3. Binding gridview to xmldocument
4. How to modify XML file in order to make it appropriate for GridView DataSource



European ASP.NET 4 Hosting :: Session State in ASP.NET 4.0

clock September 27, 2011 06:20 by author Scott

This post explains about Shrinking session state in ASP.NET 4.0.

ASP.NET Provides two options for storing session state for web applications.

1. Out of process session state
2. MS SQL server session state

In both the options session-state providers stores the data out side the web application   worker process. Session state has to be serialized before it sends it to the external storage.

ASP.NET 4.0 introduces a new compression option for both out-of-process session state providers. We can set the compressionEnabled option in configuration file to true. ASP.NET will compress the session state by using the .NET Framework System.IO.Compression.GZipStream class.

We can configure the session state as follows

<sessionState
    mode="SqlServer"
    sqlConnectionString="data source=dbserver;Initial Catalog=aspnetstate"
    allowCustomSqlDatabase="true"
    compressionEnabled="true"
/>


Advantage: With this addition of attribute to web.config file there is substantial reduction in the size of serialized session-state data.



European ASP.NET 4 Hosting :: Visualize Response.RedirectPermanent in ASP.NET 4

clock September 21, 2011 08:54 by author Scott

In ASP.NET 4.0 there are new features that enable developer to make SEO friendly websites very easily. And if you google out, you will find plenty of article which explain this feature. But I am more interested in Response.RedirectPermanent. As the name suggest it is used to redirect permanently moved resources to new location. And most of all articles on the net just explain this with some example. But how can we visualize that whether resource is redirected permanently or not. So here is the answer for that. I have used FireBug to examine the same.

Whenever we redirect with Response.Redirect, we can see following activity in FireBug console.



As we can see that page which issues Response.Redirect its response status code 302(Found) which means requested url(default.aspx) is found but it is temporarily moved to about.aspx. More information on HTTP status code can be found
here.

Now whenever we redirect with Response.RedirectPermanent, we can see following activity in FireBug console.



As we can see that page which issues Response.RedirectPermanent its response status code 301(Moved Permanently) which means requested url(default.aspx) is moved Permanently to about.aspx. 301 status code is used by search engine crawler to update search index to new moved information.

I hope information provided here would be more helpful to distinguish between Response.Redirect and Response.RedirectPermanent.



About HostForLIFE.eu

HostForLIFE.eu 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