Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Monday, 29 October 2012

 Click Here to Download ImplementCustomException.zip
You can also called that create user defined exception class in asp.net.
There is a situations where you need to create and handle a custom exception for handling runtime’s exception for application-specific exceptions.
In this example we provide both C#.Net Example and VB.Net Example.

Let's look how this mechanism works.
For that we need to create a serializable class that extends the System.Exception class, and ass some constructors and properties to manipulate the data members.
You can throw custom exception class object exception in Try block and it will handle in catch block. Mark your custom exception class as sealed if you do not wish other exception classes to extend it. You need to Implement three public constructors with specific signature and they call base class constructor.

You also need to make custom exception class serializable so that the runtime can marshal instances of your exception. If your exception class declares custom data members, so you must override the ISerializable. GetObjectData method of the Exception class as well as implement a deserialization constructor with appropriate signature. If your exception class is sealed then mark the deserialization constructor as private, otherwise, mark it as protected. The GetObjectData method and deserialization constructor must call the equivalent base class method to allow the base class to serialize and deserialize its data correctly.

Here is example for this.

Friday, 17 August 2012

When error occurred in .Net application Asp.Net page display it's default error page with the source code and line number of the error. This approach is not good it has some issues like.
  1. If source code and the error messages are displayed to a hacker it could damage application.
  2. And this message do not able to understand normal users.
There is a solution for this in ASP.Net. You can make settings in Web.Config file using "<customErrors>" section.

Syntax :
<customErrors defaultRedirect="[url]" mode="[on/off/remote]">
<error statusCode="[statuscode]" redirect="[url]" />
</customErrors>
  • defaultRedirect : Specifies URL to which page should be redirected if an error occurs. This setting is optional.
  • mode : Specifies the status of the custom errors is enabled, disabled, or shown only to remote machines. The values are On, Off, and RemoteOnly. "On" means that the custom errors are enabled. "Off" means that the custom errors are disabled. "RemoteOnly" means that the custom errors are shown only to remote clients. 
  • customErrors : The "<customErrors>" section has multiple <error> sub-elements that are used to define custom errors. Each <error> sub-element can has a statusCode attribute and a URL.

Here is example for this.
In this example we forcefully raise error from code and after error raise page is redirected to our custom "ErrorPage.aspx". In this example we raise error using numeric value divide by zero.
Here you have to add one aspx page into your .net application.
We specify settings in "web.config" file.
You have to put  "<customErrors>" section in  "<system.web>" section.

Web.Config :
<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
</customErrors>

C# Examples :
        int a=1;
        int b = 0;
        a = a / b;

VB.net Examples :
        Dim a As Integer = 1
        Dim b As Integer = 0
        a = a / b
Output :
(To view original image , click on image)

If you do not handle error, error message display on screen. You can see in below screen shot.

.

 (To view original image , click on image)

This is very useful articles for Beginning .Net .

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




Thursday, 16 August 2012

This error occurred due to cast or convert or assign NULL value cell of data row or data table.

Error Reason :

Here is example for this.
We have datatable. This data table contains value of cusutomers, thsi data table has three columns.
Columns are customer_id, customer_firstname and customer_lastname.
Sometimes customer_lastname column has DBNULL value and we directly assign this value to string variable at that time this error occured.

Something like this.
dtCustomer.rows[0]["customer_lastname "]  has DBNULL value. and we are assigning this value to variable like this.


C# Examples :
string strCustomerLastName = dtCustomer.Rows[0]["customer_lastname "].ToString();

VB.net Examples :
Dim strCustomerLastName As String = dtCustomer.Rows(0)("customer_lastname ").ToString()

At this time this error occured.

Solution :

Before assigning or converting this DBNULL value we have make check for this.
We can make check with "System.DBNull.Value" value. We compare both "cell" and "System.DBNull.Value" value if both are same so we do not assign or convert that value. We simply use default value.

Here is Example for this.


C# Examples :
        string strCustomerLastName=string.Empty;
        if(dtCustomer.Rows[0]["customer_lastname "] != System.DBNull.Value)
        {
            strCustomerLastName = dtCustomer.Rows[0]["customer_lastname "].ToString();
        }

VB.net Examples :
        Dim strCustomerLastName As String = String.Empty
        If (dtCustomer.Rows(0)("customer_lastname ") IsNot System.DBNull.Value) Then
            strCustomerLastName = dtCustomer.Rows(0)("customer_lastname ").ToString()
        End If

This is very useful articles for Beginning .Net .

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


Friday, 1 June 2012

Sometimes you get this error when data is post on server from click of button or other postback operations.

You got this type of error message:
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (TextBox1="<a>aaa</a>").]
   System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +8730676
   System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +122
   System.Web.HttpRequest.get_Form() +114
   System.Web.HttpRequest.get_HasForm() +8896047
   System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
   System.Web.UI.Page.DeterminePostBackMode() +69
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +8431
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +253
   System.Web.UI.Page.ProcessRequest() +78
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
   System.Web.UI.Page.ProcessRequest(HttpContext context) +49
   ASP.linqtoobject_aspx.ProcessRequest(HttpContext context) in c:\Users\tempuser\AppData\Local\Temp\Temporary ASP.NET Files\sampleapplication\af2e8044\2172ed84\App_Web_pavad1h4.0.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +100
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

Error Reason :

ASP.NET do request validation against form variables , query string  and cookie data.
By default, if the current Request contains HTML-encoded elements (such as <a>, <h1> tags) or  HTML characters (Like &#151), the ASP.NET page framework raises an error.

Example , text field in the form and server side button which post this form data to server, if operator typed some text containing html tag such as <a href="aaa"> in textbox and click on button for postback at that time asp.net raise Error for request validation.

There are special configuration settings for .Net 4.0 .

There are two Possible solutions for this.

Solution 1 :
    Make server side configuration setting for this.
    If you want to allow HTML element as input from selected pages in your project than you set this page attribute.
    <%@ Page ValidateRequest="false" %>
    This ValidateRequest="false" on each page.
    If you want in all pages in you project than make changes in Web.Config file.
    Add this tag In <system.web> section.
  <pages validateRequest="false" />
    If you are using .Net 4.0 than you have to make one more change in Web.Config file.
    Add this tag In <system.web> section.
    <httpRuntime requestValidationMode="2.0" />
   
    Here are configuration for do not validate request for all pages in .Net 4.0
    <configuration>
      <system.web>
         <httpRuntime requestValidationMode="2.0" />
      </system.web>
      <pages validateRequest="false">
      </pages>
    </configuration>

Solution 2 :
    Make Client side changes.
    Encode HTML tag at client side before it submitted to server.
    Example :
        &lt;a&gt; for <a> tag.
        &lt;b&gt; for <b> tag.

These are the two possible solutions you can implement in you project.

Tuesday, 20 March 2012

Click Here to Download Sample ThreadWasBeingAbortedExample.zip
Note : In this sample application there is two pages First page "ErrorSample.aspx" This page dmostrate how this error occured you can check this by putting debug point in Catch section, you notice that when Response.Redirect method called after that error thow and page is being redirected. Second page is "ErrorResolvedExample.aspx" in this page we demostrate how to resolve this issue.

When you are using Response.End, Response.Redirect, or Server.Transfer method methods in Try Catch Block it will throw "ThreadAbortException" Exception.
Error Message like "Thread was being aborted."

The Reason for this error due to.
The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline.
The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

Solution for this Problem is as follows.

For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method
instead of Response.End to bypass the code execution to the Application_EndRequest event.

Example :
HttpContext.Current.ApplicationInstance.CompleteRequest();

For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) Method.
Pass false for the end Response parameter to suppress the internal call to Response.End.

Example :
 Response.Redirect ("otherpage.aspx", false);

For Server.Transfer, use the Server.Execute method instead.

Example :
Server.Execute("otherpage.aspx");