Error Log in MVC

Implement Elmah in MVC Application for error log

In Every application capture and maintain error log is very important part of the any application. That is help full to development support team as well client to make application running a smooth in live environment

So implementing different error log for every application we need to add few efforts so elmah has good common solution for that. Elmah can be fit in any .net application with below error log mechanism.

  1. Log in XML file
  2. Log in SQL database
  3. Log in Mail (sent an email to provided email address)
  4. Log in Oracle database
  5. Log in Access database

Elmah is Open source code so you also download a code also for any modification. Below is the URL for Elmah code and download.

http://code.google.com/p/elmah/

Along with this kind of feature they are providing good UI also to view all log with details along with download functionality.

In this article I am targeting to how to configure Elmah in MVC 3.0 Application

That is very simple to add Elmah in MVC application, just need to add elmah in project from package library reference.

Select Project > Click on Right Click > Select “Add Library Package Reference”  and search elmah and install that in your application.

Now you have to add below xml tag in your web.config file.

Add below ConfigSection (if tag exist then add tag in that existing tag)

 

Now Add Elmah tag in below this configSection. Where you can uncomment what ever you want and add your setting.(like database name, log file path etc…)

<elmah>
    <!--
            Use to log errors to Microsoft SQL Server 2000 or 2005
            using ASP.NET 2.0. Set value of connectionStringName attribute
            to the name of the connection string settings to use from
            the <connectionStrings> section.
        
        <errorLog type="Elmah.SqlErrorLog, Elmah" 
            connectionStringName="..." />
        -->
    <!--
            Use to log errors to Microsoft SQL Server 2000 or 2005
            using ASP.NET 1.x and adjust the value of connectionString 
            attribute to your settings.

        <errorLog type="Elmah.SqlErrorLog, Elmah" 
            connectionString="Data Source=.;Initial Catalog=ELMAH;Trusted_Connection=True" />
        -->
    <!--
            Use to log errors to MySQL 5.0+  Set value of connectionStringName attribute
            to the name of the connection string settings to use from the <connectionStrings>
            section.

        <errorLog type="Elmah.MySqlErrorLog, Elmah" 
            connectionString="..." />
        -->
    <!--
             Use to log errors to a SQL Server Compact 4 database file (requires .NET 3.5 SP1) 
             Set value of connectionStringName attribute to 
             the name of the connection string settings to 
             use from the <connectionStrings> section.
    
          <errorLog type="Elmah.SqlServerCompactErrorLog, Elmah" connectionStringName="..." />

             The format of the connection string should be as follows:
    
          <connectionStrings>
            <add name="..." connectionString="data source=[path to the database file]" />
          </connectionStrings>
    
            Replace the content of the brackets with a file name, for example:
    
          data source=C:\Elmah.sdf
    
             If the database file doesn't exist it is created automatically.
             You can also place the file in the App_Data folder, by using the |DataDirectory| macro:
    
          <connectionStrings>
             <add name="..." connectionString="data source=|DataDirectory|\Elmah.sdf" />
          </connectionStrings>

      -->
    <!--
            Use to log errors to SQLite using ASP.NET 2.0. 
            Set value of connectionStringName attribute to 
            the name of the connection string settings to 
            use from the <connectionStrings> section.
            
        <errorLog type="Elmah.SQLiteErrorLog, Elmah" connectionStringName="..." />
        
            The format of the connection string should be as follows:
            
        <connectionStrings>
          <add name="..." connectionString="data source=[path to the database file]" />
        </connectionStrings>
            
            Replace the content of the brackets with a file name, for example:
            
        data source=C:\Elmah.db
            
            If the database file doesn't exist it is created automatically.
            To specify a path relative to and below the application root, 
            start with the root operator (~) followed by a forward slash (/), 
            as it is common in ASP.NET applications. For example:
            
        data source=~/App_Data/Error.db
        -->
    <!--
            Use to log errors into separate XML files that are stored on 
            disk at the path specified in the logPath attribute.
-->
    <errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/ErrorLog" />
    <!--
            Use to log errors to Oracle
            using ASP.NET 2.0. Set value of connectionStringName attribute
            to the name of the connection string settings to use from
            the <connectionStrings> section.
        
            The schemaOwner parameter is *optional*. Use this if the owner of the
            ELMAH package (pkg_elmah$error) is not the same user that you are 
            using to connect to the database.
            
        <errorLog type="Elmah.OracleErrorLog, Elmah" 
            schemaOwner="xxx" />
            connectionStringName="..." />
        -->
    <!--
            Use to log errors to Oracle
            using ASP.NET 1.1 and adjust the value of connectionString 
            attribute to your settings.

            The schemaOwner parameter is *optional*. Use this if the owner of the
            ELMAH package (pkg_elmah$error) is not the same user that you are 
            using to connect to the database.

        <errorLog type="Elmah.OracleErrorLog, Elmah" 
            schemaOwner="xxx" />
            connectionString="Data Source=xxxx;User ID=username;Password=password" />
        -->
    <!--
            Use to log errors to Microsoft Access
            using ASP.NET 1.x and adjust the value of connectionString 
            attribute to your settings.
            Use Elmah.mdb as your database.

        <errorLog type="Elmah.AccessErrorLog, Elmah" 
            connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Elmah.mdb" />
        -->
    <!--
            Use to log errors to Microsoft Access
            using ASP.NET 2.0. Set value of connectionStringName attribute
            to the name of the connection string settings to use from
            the <connectionStrings> section.
            Use Elmah.mdb as your database.
        
        <errorLog type="Elmah.AccessErrorLog, Elmah" 
            connectionStringName="..." />
        -->
    <!--
            Use to log errors to PostgresSQL 
            using ASP.NET 2.0. Set value of connectionString to a 
			valid Npgsql connection string.
        
		<errorLog type="Elmah.PgsqlErrorLog, Elmah" 
            connectionString="Server=...;Port=...;Database=...;User Id=...;Password=...;" />
        -->
    <!--
            Use to send error reports by e-mail and adjust the attributes
            according to settings desired. Note that only the from and
            to attributes are required. The rest are optional and may
            be removed. If the SMTP server does not require authentication,
            you MUST remove the userName and password attributes or
            set them to empty values (resulting in zero-length strings).
            If you are using ELMAH compiled for .NET Framework 1.x, then
            the to attribute may contain multiple recipient addresses,
            each of which must be delimited by a semi-colon(;). If you are 
            using ELMAH compiled for .NET Framework 2.0 or later, then the
            to attribute may contain multiple recipient addresses,
            each of which must be delimited by a comma (,).

        <errorMail 
            from="elmah@example.com" 
            to="admin@example.com" 
            subject="..."
            priority="Low|Normal|High"
            async="true|false"
            smtpPort="25"
            smtpServer="smtp.example.com" 
            useSsl="true|false"
            userName="johndoe"
            password="secret" 
            noYsod="true|false" />
        -->
    <!--
            Use to send short error messages to a twitter account.
        <errorTweet 
            userName="johndoe" 
            password="secret" />
        -->
    <!--
            Use to prevent errors from being mailed or logged based on
            assertions. An assertion evaluates the current context, resulting
            in a Boolean outcome. An error is filtered if the assertion results
            in true. For a more detailed explanation, see:

http://code.google.com/p/elmah/wiki/ErrorFiltering

            The example below will filter errors when any of the
            following conditions occur:
            
            - The status code is set to 404 
            - The root/base cause is System.IO.FileNotFoundException
            - The root/base cause is System.Web.HttpRequestValidationException
            - The user agent making the request identifies itself as "crawler"
            - The request is from the local machine
            
            The assertion below is expressed as a JScript expression and is the
            most generic and simplest of the assertions to use if you are
            familiar with the JavaScript language. It can work in Medium and
            Full trust environments.

        <errorFilter>
            <test>
                <jscript>
                    <expression>
                    <![CDATA[
                    // @assembly mscorlib
                    // @assembly System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
                    // @import System.IO
                    // @import System.Web

                    HttpStatusCode == 404
                    || BaseException instanceof FileNotFoundException 
                    || BaseException instanceof HttpRequestValidationException
                    /* Using RegExp below (see http://msdn.microsoft.com/en-us/library/h6e2eb7w.aspx) */
                    || Context.Request.UserAgent.match(/crawler/i)                      
                    || Context.Request.ServerVariables['REMOTE_ADDR'] == '127.0.0.1' // IPv4 only
                    ]]>
                    </expression>
                </jscript>
            </test>
        </errorFilter>
        -->
  </elmah>

If you are using IIS 7 then add this tag in your tag.

Now you when error occurs log file will be automatically generated. And that you can access by just calling elmah.axd from your root path. That will display all logs with details description.

One more thing need to consider in MVC application, when error mode is On that error log in not captured by default because in MVC that will not execute application_error event so log is not generated in xml file.
Hence, you have to comments handler related filter in global.aspx file

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute());
}

Let me know if you have any questions or suggestion on this post.

Thanks,
Amit Patel
“Enjoy Programming”

About these ads

How to map an Entity framework model to a table name dynamically

I am working in MVC 3 with entity frame work so I am using List, create, edit and details page by razor templates of csHTML5.

But I have found one problem while creating a templates from my company model which Company table available in my existing database which I cannot change.

So all related controller and View has been created along with context, but Problem is comes that created entity framework structure is expected tables “Companies” but in my case I have table with company. Below is the code for was exists.

public class CompanyServices : DbContext
{
public CompanyServices()
{
this.Database.Connection.ConnectionString = ServiceBase.DataConnectionString;
}

public DbSet Company { get; set; }
//public DbSet Players { get; set; }

}

I have got below error by executing this code.
________________________________________
Invalid object name ‘dbo.Companies’.
Error Source
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443

To resolve this error I found in Entity framework we have automatic conversion is available and based on that that will convert company entity to map with tables Companies.

So We need to modify above class with overriding this methods. So that will remove that conversion functionality so Entity framework will point to the exact tables.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();
}

Below is completed update classs.

public class CompanyServices : DbContext
{
public CompanyServices()
{
this.Database.Connection.ConnectionString = ServiceBase.DataConnectionString;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();

}
public DbSet Company { get; set; }

public void InActive(Team oTeam)
{
this.Entry(oTeam).State = System.Data.EntityState.Modified;
this.Database.ExecuteSqlCommand("EXEC InActiveTeam {0}, {1}", oTeam.TeamId, oTeam.isActive);

}
}

Note : Below namespace required to import to run this code.
using System.Data.Entity.ModelConfiguration.Conventions;

Thanks,
Amit Patel
“Happy Programming”

Software Development Life Cycle

Below are the Stages of Software Development life cycle to make process smooth.

SDLC

Software Development Life Cycle

  1. 1. Project Plan
    1. Roles
      1. Client Team
      2.  Business Developer Team
      3.  Project manager
  • Check Project feasibility with company’s capabilities
  • Define high level requirement and stack holders goal
  • Define Business  problems and goals
  • Access Current Capabilities
  • Explore Solution approach
  • Prepare Statement of Work with estimation
  • Agreement sign with clients based on SOW and given estimation
  1. 2 . Analysis Phase
    1. Role
      1.  Client Team
      2. Business Developer Team
      3. Project Manager
      4. Architecture and Development Team
      5. QA Team
  • Analysis business process
  • Create and analyze product requirement and product quality-related matrices
  • Create Non functional prototype /Functional specification document/ Use cases / Activity diagrams
  • Create test plans and QA on all deliverables (NFP, documents)
  1. 3. Design Phase
    1. Role
      1. Development Team
  • Database Design
  • Application Architecture design
  • Adapt the design to address quality requirements and technical constraints, designing for performance.
  1. 4. Build Phase (Development)
    1. Role
      1.   Development Team
  • Based on application design and analysis develop application’s Modules
  • Integrate all the individually developed and tested components in an executable application.
  • Perform unit testing.
  1. 5. Test Phase
    1. Role
      1. QA Team
      2.  Development Team
  • Perform and executed assembly testing
  • Perform and execute product testing
  • Perform and execute performance testing
  • Application sent back to development team with test reports in bug tracker
  • Perform regression testing based on developers’ changes.
  • Perform manual and automation testing.

1.6. Deployment phase

  1. Role
    1.  Client
    2.  Architecture and development team
  • Prepare production and staging environment
  • Enable Stack holder to use or support to new application
  • Create access permission to stack holder group
  • Perform QA on new deployed application.
  1. 7. UAT
    1. Role
      1. Stack holders (Client)
      2. Development team
      3.  QA Team
      4.   Project manager
  • Client will perform Testing
  • Perform testing to check application meets on requirement specification or not.
  • If any bugs found then developer and QA team need to support on that.

1.8. Maintenance and Support

  1. Role
    1.  Stack holders (Client)
    2.  Development team
    3.   QA team
  • If Client requires supports then need to provide support based on contract agreement.

First character in upper case in SQL

Hi,
Below are the logic for Set first character in Upper case and rest of all set in lower case in MS sql code Like

input = ‘sql data’
output = ‘Sql Data’

Below are the code for that.

declare @inputString varchar(20)
set @inputString = 'AMIT PATEL'

declare @position int

set @position = 1
SET @inputString = Upper(substring(@inputString,1,1))+ LOWER(substring(@inputString,2,len(@inputString)-1))
WHILE @position < DATALENGTH(@inputString)
Begin
set @position = charindex(' ',@inputString,@position+1)
if @position = 0
goto done
SET @inputString = REPLACE(@inputString,substring(@inputString,@position,2),Upper(substring(@inputString,@position,2)))
End
DONE:
PRINT @inputString

PrintDialog in PDFSharp Control C# code

For implementing a print functionality if we want to user to choise to set their own setting while pringing so bettor option is that provide print dialig box rather then provide fix settings.

Dialog box is shows as below.

Print Dialogbox

If we are using PDFsharp control then we have to capture settings from this dialog and then need to pass it to PDFSharp controls and then execture pdfsharp document’s print command.

Below are the code for that..

PrinterSettings settings = new PrinterSettings();

PrintDialog oDiaLog = new PrintDialog();

 

 

if (oDiaLog.ShowDialog() == DialogResult.OK) 

 

{  

 

PDFPrintSettings pdfPrintSettings = new PDFPrintSettings(oDiaLog.PrinterSettings);

this.PdfDocument.Print(pdfPrintSettings); // Here PDFDocument is document of PDF sharp objects.

 

}

 

PringDialog allows user to set their own printer settings and based on that set request to selected printers.

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Follow

Get every new post delivered to your Inbox.

Join 239 other followers