ErrorLog – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Using Exception Filters in MVC applications /exceptionfilters-mvc/ /exceptionfilters-mvc/#respond Sun, 12 Jul 2015 16:27:30 +0000 /?p=396 Introduction

Exceptions, are like part and parcel of an application. They are boon and ban for an application to. Is’nt it?This would be controversial, for developers it helps them track minor and major defects in an application, and somtimes they are frustrating when it lets users land on the Yello screen of death each time. This would make the users mundane to the application. Thus to avoid this, developers handle the exceptions. But still sometimes there are a few unhandled exceptions. Now what is to be done for them? MVC provides us with built-in filters ‘Exception Filters’ about which we will discuss. Lets start..
exceptionย cc: Google

Yellow screen of Death can be said as wadrobe malfuction of our application. ๐Ÿ˜€

Get Started

Exception filters run when some of the exceptions are unhandled and thrown from an invoked action. The reason for the exception can be anything and so is the source of the exception.

Creating an Exception Filter

Custom Exception Filters must implement the built in IExceptionFilter interface. The interface looks as :

public interface IExceptionFilter{
    void OnException(ExceptionContext filterContext)
}

Whenever an unhandled exception is encountered, the OnException method gets invoked. The parameter as we can see, ExceptionContext is derived from the ControllerContext and has a number of built in properties that can be used to get the information about the request causing the exception. There properties ExceptionContext possess are shown in the table:

Name Type Detail
Result ActionResult The result returned by the action being invoked.
Exception Exception The unhandled exceptions caused from the actions in the applications.
ExceptionHandled BOOL This is a very handy property, which returns a bool value (true/false) based on if the exception is handled by any of the filters in the applicaiton or not.

The exception being thrown from the action is detailed by the Exception property and once handled (if), then the property ExceptionHandled can be toggled, so that the other filters would know if the exception has been already handled and cancel the other filter requests to handle. The problem, lies that if the exceptions are not handled, then the default MVC behaviour shows the dreaded yellow screen of death, to the users, which puts up a very bad impact on the users and more importantly, it exposes the application’s handy and secure information to the outside world, which may have hackers and then the application gets into the road to hell. Thus, the exceptions need to be dealt very carefully.
Lets demonstrate one small custom exception filter.
This filter can be stored inside the Filters folder in the web project of the solution. Lets add a file/class called CustomExceptionFilter.cs

public class CustomExceptionFilter : FilterAttribute, IExceptionFilter {
     public void OnException(ExceptionContext filterContext) {
        if(!filterContext.ExceptionHandled && filterContext.Exception is NullReferenceException) {
            filterContext.Result = new RedirectResult("customErrorPage.html");
            filterContext.ExceptionHandled = true;   
        }
    }
 }

Now let us understand what this actually does. as we can see this implements the interface as mentioned earlier and thus implements the method, OnException. This mehtod has the parameter ExceptionContext, the properties of which is mentioned in the table. In this custom filter we have handled the most common and neglected exception “Null Reference Exception”, arises when a value returning null is not handled/checked and used in further implementations. The custom filter derives the FilterAttribute as to be used as Attribute over the action or the controller directly like [CustomExceptionFilter]. In this implementation above, we have used almost allthe important properties of the ExceptionContext. First, the check is used for the ExceptionHandled which returns a boolean value if the exception has been handled or not. If not then Check for the type of exception arisen. Since here we have used the NullReferenceException, we check for that exception. Then if the conditions are satisfied/passed we manipulate the result and return the RedirectResult (ActionResult type) and let the users land on a custom error page created in the application, to avoid the yellow dreaded screen.

The use of the filter is pretty simple as this custom filter extends from the FilterAttribute. So based on the usage, this can be used as [CustomExceptionFilter] on the Controller Levelor the individual Action level,which ever is mandate.

//Over controller
 [CustomExceptionFilter]
 public class HomeController:Controller {
    //......
 }
//Over the Action
 [CustomExceptionFilter]
 public ActionResult Index() {
    //.......
 }

Now, lets discuss about the in built HandleAttribute. This is a built in class which is used similar way as a filter attribute in MVC applications. The most important thing is this attribute works only when the custom errors in the web.config is enabledor set to true.

the default mode for this element is RemoteOnly, which willonly work out when application is deployed and request is made from some other systems.
Lets look at the properties of the HandleError Attribute.

  • ExceptionType: This property, as the name suggests tells the attribute the type of exception it needs to handle.
  • View: This is the property, which we need to specify inorder to lets the attribute, land the end users after handling the exception
  • Master: If there is a special layout, we have for the error page, then this master can be set to that layout path, if left empty, this will take the default layout of the application for the error pages.

Thus, the below code snippet shows how to use the HandleError attribute

[HandleError(ExceptionType = typeof(NullReferenceException), View = "CustomErrorPage")] {
public Action Result {
    //........
    var testVal = null;
    //Unhandled and used..
 }

Caution: While reading through the Adam Freeman, a very interesting note of caution was mentioned while using the HandleError attribute. In the custom error page, we would be using the HandleError Info like the Stack Trace, the exception message etc. Since we would not like to show this to the end user, we need to put the stack trace inside a hidden field or make the html tag invisible because The view is not displayed tothe user unless the Exception.StackTrace is included in the View..

Conclusion & References

Thus, we learnt the creation of custom exception filters as well as the built-in filters in MVC applications.There are various ways/tools now tohandle exceptions, but stillwe can make use of these filters in order to avoid detrimental effects on our applications.
References: Adam Freeman-Professional Asp.Net MVC 4 & MSDN
I hope this would help developers & beginners. The concept is interesting when we use them. So start using and enjoy Coding. ๐Ÿ™‚

]]>
/exceptionfilters-mvc/feed/ 0
The Unsung Hero ELMAH-Part 2 /the-unsung-hero-elmah-part-2/ /the-unsung-hero-elmah-part-2/#comments Sat, 07 Feb 2015 19:17:36 +0000 /?p=241 Background

As discussed in my prvious blog post i.e. ELMAH Part-1.
Now in this article I will be explaining the integration of ELMAH with Sql Server(SSMS). This is now-a-days an essential part in any application, that is error and exceptions that rise in the application are logged into the database tables that are related to ELMAH. These table scripts are providedby ELMAH itself. Dont Believe!! I also did not. But that is the truth. Lets see and discuss now..

ELMAH Configuration

Here I am specifying all the requirements for setting up ELMAH in the web.config settings. As the installationand also the setting have been explained in Part-1. Still I am specifying the blocks required in the Web.Config.

Inside the System.webServer block:

<modules runAllManagedModulesForAllRequests="true">
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
    </modules>Snippet

 &lt;handlers&gt;
      &lt;add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" /&gt;
    &lt;/handlers&gt;

above are the modules and handlers as well.

Inside system.Web:

<httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
    </httpModules>
    <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
    </httpHandlers>

The above are the common settings for the ELMAH. Now lets look into the settings required for database settings.

As we all have an access and look at the connection strings. Still lets have a quick look:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-DemoStart-20141014045047.mdf;Initial Catalog=aspnet-DemoStart-20141014045047;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

The above is the pattern of the connection strings. Donot use the same one..just kidding.. ๐Ÿ˜‰

Then the final change for the ELMAH with the Sql :

<elmah>
    <security allowRemoteAccess="yes" />
    <errorMail from="[email protected]" to="[email protected]" subject="DEMO Error" async="false" useSsl="true" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="DefaultConnection" applicationName="DemoStart"/>
  </elmah>

This was the final change required for the web.config change to integrate ELMAH with SSMS.

Queries for ELMAH

Now, let me reveal the magic to you as I mentioned earlier. Yes guys, queries we donot have to write , ready-made queries are provided by the ELMAH team. The download link for the ELMAH Queries is :-Queries for ELMAH
Capture

Just simply download the “.sql” file and run in the SSMS. After execution the tables get created for the ELMAH as well as the stored procedures shown below:

Capture2

As you can see above, the tables and stored procedures are added into the database. This is so simple and as simple it can be. Is’nt this great!!

Lets see the number of columns and what columns are being created in the tableย dbo.ELMAH_Error

Capture3Then every exceptions rising will be added into the table and can be easily used by developers for future reference.

I hope this helps developers anyway. This article covers all the setting configurations required.
Thus the setup is as simple as it can be. Thanks to Andy French.

]]>
/the-unsung-hero-elmah-part-2/feed/ 2
The Unsung Hero “ELMAH” /the-unsung-hero-elmah/ /the-unsung-hero-elmah/#respond Fri, 06 Feb 2015 21:01:28 +0000 /?p=228 Introduction

ELMAH, Error Logging Modules & Handlers is a tool for debugging mainly ASP.NET applications suggested by wiki. As we all know there is always a chance of getting exceptions while working on any applications. Handling them is a real challenge for many developers. But if we have a tool, that gives us the details of the exceptions or errors with the stack trace as well. Apart from showing the users the yellow screen of death, we show the users a customized error page, but for the developers if any exceptions occur instead of having a try catch block at every method, ELMAH provides them the details of the exceptions with the entire stack trace and solve the issue based on the error code. For more information on error codes and redirect please follow one of my other articles Custom Errors. Lets get into more details how this beautiful tool works.

What we get?

You would be wondering what this ELMAH gives us after adding this into the application? Straight from the Hanselmen’s blog, ELMAH would give us the following without changing a single peice of code. Since the ELMAH includes Modules and Handlers, it greatly supports HttpModules and Http Handlers.

  • All unhandled exceptions(Null reference, Out of bound exception, etc.) are logged in the ELMAH interface
  • A webpage can remotely view the logged detailed exceptions
  • Since this shows the entire stack trace, the so called yellow screen of death can also be seen but in the ELMAH interface
  • ELMAH also gives an opportunity to store the exceptions or log them into tables (SSMS).

<customerrors mode="On" defaultredirect="/Default/Error">
    <error statuscode="404" redirect="/Default/NotfoundError">
</error></customerrors>

When suppose the above is the case, then the user using the application, lands on the above redirect path url pages, where as the error and exception are managed by ELMAH and mailed or logged into the database for future reference for the developers.

Installation for an existing MVC project

Step 1: Go to references and right click on the Manage Nuget Packages

elmah1

Step 2: Search online for Elmah.MVC

elmah2
Step 3: After the succesful installation, you can check the package.config for the version of elmah installed shown below:

elmahpckcnfg
Step 4: You need to ensure then the below web.config configurations as shown in the images below:

<sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>

 

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
    </httpModules>
    <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
    </httpHandlers>
  </system.web>

 

<system.webServer>
    <modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
    </modules>
    <handlers>
      <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
    </handlers>
</system.webServer>

 

<elmah>
    <security allowRemoteAccess="yes" />// To allow remote access
  </elmah>

Now everything is set for developers to check for the internal exceptions occured. But how to access the ELMAH interface? It is simple, just use the path url succeding with /elmah.axd then done you see the list of exceptions/errors occured. The interface would look like below image:

elmahintrfce

Integration of ELMAH to GMAIL

Yes guys you heard h=it right as the heading says, we can integrate email settings into the ELMAH and send the entire stack trace and exception details as mail to multiple users using a subject too.

Below I would be discussing the integration and set up for the mail settings. here I use the Gmail setting. The best part here is the change is only done at the web.config level. Below are the proper configurations.

  • First in the system.webServer/modules section add the below peice of line. The final module is below:
    <modules runAllManagedModulesForAllRequests="true">
          <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
          <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
        </modules>

     
  • Then after adding this module section, we need a set up for the Gmail in the system.net/mailSettings section as below:
    <system.net>
        <mailSettings>
          <smtp from="[email protected]">
            <network host="smtp.gmail.com" port="587" userName="*****" password="***" enableSsl="true" />
          </smtp>
        </mailSettings>
      </system.net>

    Just remember you need to set your gmail username and password. Google Mail is very smart and doesnot simply ets the mail come or the application to sign in into the gmail, as that may be from an unauthenticated source. To avoid this, you need to follow the mail which Google will send you and you need to approve that you want that Ip source to use your mail settings to send mail. Thus, you make google happy. ๐Ÿ™‚
  • Then finally we need to set the elmah section with the following block:
    <elmah>
        <security allowRemoteAccess="yes" />
        <errorMail from="[email protected]" to="[email protected]" subject="DEMO Error" async="false" useSsl="true" />
      </elmah>

    Thus, all set now our application/ELMAH is smart enough to understand the configurations and send mails to the specified users. Remember in the above block “to”, you can specify more than one mail addresses separated by comma. Thus, have a look at the image below to see how the mail looks like:emailpart
  • The above is a part of how the mail looks like.

Thus, we have discussed everything related to ELMAH. In the upcoming article/blog I will be explaining how to store into tables using connection strings. The interaction of Sql server of ELMAH.

References

Scott Hanselman Blog
Wiki
CP

]]>
/the-unsung-hero-elmah/feed/ 0