Category: .NET


Enterprise Library 5 with Oracle

Introduction

This tutorial is an update from my previous post Enterprise Library 5 with Oracle Cursor, in which I demonstrated how to use Enterprise Library 5 with Oracle but NOT using ODP.NET, using MS Client instead. That’s because ODP.NET wasn’t compatible with Enterprise Library 5 when I wrote that post.

Well, luckily things have changed and now we can use them together, so, I created this step-by-step tutorial to show you how you can setup your project to use Enterprise Library 5 with ODP.NET. The steps shown here were tested on Oracle 11g, Enterprise Library 5, ODP.NET 11.1.0.7.20, and EntLibContrib 5. Different versions of Oracle and ODP.NET may work as well.

Step 1 – Environment

Oracle

I assume you already have some Oracle installed, but in you case you don’t you can download a Pre-built Virtual Machine that will make your life easier when setting up the environment.

Oracle Data Provider for .NET – ODP.NET

It will install the .NET client which communicates with the database – pretty obvious, I know, sorry for that. You can download it here.

I recommend you to really install it and not just copy the DLLs. I’m saying because I tried it. And it works! I just don’t think it’s worth having to copy DLLs with hundreds MBs into your project. In case you still want opt for that, you will need to copy the DLLs from Oracle Instant Client into your project’s bin folder.

Step 2 – Installing Libraries

I’m going to start by creating a new Project, going to File, New Project…New project window

Give the project a name and now, we install the libraries. I’m going to do that by using NuGet. It’s the easiest and fastest way and if you’ve been avoiding using NuGet all this time, then you should stop doing that!

From the NuGet Package Manager Console, run the following command:
Install-Package EntLibContrib.Data.OdpNetInstalling ODP.NET via NuGet Command

Or, you can right click the project and click on Manage NuGet PackagesInstalling ODP.NET via NuGet Window

For those who prefer manually install everything, download the EntLibContrib and add the necessary assembly references to the project.

Also, add a reference the Oracle.DataAccess.dll (you can find it in your oracle folder), usually c:\oracle\product\11.x.xx.x\odp.net\bin.
Adding Oracle Client library

In the end, regardless the installation type you chose, you should have your references as shown below:
References added to the project

Step 3 – Configuration

In the Web.Config / App.config, we need to tell Enterprise Library not to use its default implementation of Oracle Client and use the EntLibContrib one, which will work with ODP.NET. The code below does that by setting the Provider Mapping:

<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </configSections>
  <dataConfiguration defaultDatabase="DefaultConnectionString">
    <providerMappings>
      <add databaseType="EntLibContrib.Data.OdpNet.OracleDatabase, EntLibContrib.Data.OdpNet, Version=5.0.505.0, Culture=neutral, PublicKeyToken=null" name="Oracle.DataAccess.Client"/>
    </providerMappings>
  </dataConfiguration>
</configuration>

After that, also add the Connection String to your database, below is an example:

<connectionStrings>
    <add name="DefaultConnectionString" connectionString="Data Source=127.0.0.1;User ID=scott;Password=tigger;Persist Security Info=True;" providerName="Oracle.DataAccess.Client"/>
</connectionStrings>

If you have problems configuring your connection string, see more different ways of setting it here.

Step 4 – Code

At this point, everything is set up and we can start coding. The code is pretty simple and it’s just to illustrate the concept.

First, I’m going to create a User class that will hold the user’s info.

using System;

namespace EntLib5ODP.NET
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime? BirthDate { get; set; }
        public string Phone { get; set; }
    }
}

Now, we need to ask Enterprise Library for a Database object. That Database object contains the methods that allows us to talk to the database. The line that does that is this one:

var database = EnterpriseLibraryContainer.Current.GetInstance<Database>();

With that object, we are able to call the method ExecuteReader which queries the database. One of the overloads of that method expect a Stored Procedure name and the arguments of that procedure. It will use the order of the arguments to bind them. My stored procedure has 3 arguments: id, name and result. Notice, we need to supply all parameters, so we set the ones we don’t want as null just to satisfy the parameters count, otherwise we would receive the error ”The wrong number of parameters does not match number of values for stored procedure”. Here’s how we call the procedure to return a User by Id.

database.ExecuteReader("pkg_client.sp_list", id, null, null));

This will return an IDataReader, which is a HashTable with some helper methods. Now let’s put all together:

using System;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace EntLib5ODP.NET
{
    public class UserData
    {
        private readonly Database database;

        public UserData()
        {
            database = EnterpriseLibraryContainer.Current.GetInstance<Database>();
        }

        public User GetById(int id)
        {
            User user = null;

            using(var reader = database.ExecuteReader("pkg_client.sp_list", id, null, null))
            {
                if (reader.Read())
                    user = MapUser(reader);
            }
            return user;
        }

        private static User MapUser(IDataReader reader)
        {
            var user = new User
            {
                Id = (int)reader["id"],
                Name = (string)reader["name"],
                Email = reader["email"] as string,
                BirthDate = reader["birthdate"] as DateTime?,
                Phone = reader["phone"] as string
            };
            return user;
        }
    }
}

and the program running…
Program running

Download Sample

The links below contain the sample code with all that I showed you here. If you also want to test it on your machine, you need to download the SQL scripts and execute them in your database. The scripts will create a table with 3 items and a package with one procedure to list the items from that table. In case you’re using an schema, don’t forget to set them as well.

Dropbox => http://dl.dropbox.com/u/6963935/samples/EntLib5_ODP.NET/EntLib5ODP.NET.zip
GitHub => https://github.com/stanleystl/EntLib5ODP.NET
Scripts SQL => http://dl.dropbox.com/u/6963935/samples/EntLib5_ODP.NET/scripts.zip

Other Download Links

NuGet – http://nuget.codeplex.com/
Enterprise Library – http://entlib.codeplex.com/
EntLibContrib – http://entlibcontrib.codeplex.com/
ODP.NET – http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
Oracle – http://www.oracle.com/technetwork/database/express-edition/overview/index.html
Pre-built Oracle Virtual Machine – http://www.oracle.com/technetwork/community/developer-vm/index.html

I’m developing a MVC application and there are some configurations I want to use both on client and server side but I don’t want to replicate them, I want it be DRY (Don’t Repeat Yourself). Having it gives me the hability of changing some value on both sides without deploying the application again.

I could have created my properties in my AppSettings section and then print the variables on a page, but the AppSettings would become huge and the page header a mess.

Here is the solution I end up with. I created a JSON file containing my propeties, like so:

common.json

{
	"highlightProductId": 5,
	"bannerEnabled": false,
	"passwordLength": 15,
	"adURL": "http://google.com/ad"
}

That allows me to use the Newtonsoft or any other JavaScript parser like the JavaScriptDeserializer from .Net and have that JSON as a class. You can also deserialize it as “dynamic” if you are using the Newtonsoft library.

Well, that solves the problem for the server side. The client side though would have to call jQuery.getJSON to be able to read that file but that slows the page loading down and doesn’t give the user a nice experience because the user has to wait until the ajax call gets finished, so it can continue processing the rest of the script.

What I did was to turn that JSON into a JS file. To do that, you just have to assign that JSON to a variable and then you can embed the result in the page as a JavaScript file!

var common = { };

That is a valid JS file!

Now let’s teach MVC how to do that. Create the file below:

namespace System.Web.Mvc
{
    using System;

    public class JsonToJavaScriptResult : ActionResult
    {
        public string Prefix { get; private set; }
        public string JsonFile { get; set; }

        public JsonToJavaScriptResult(string prefix, string jsonFile)
        {
            JsonFile = jsonFile;
            Prefix = prefix;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/x-javascript";

            response.Write(Prefix);            
            response.WriteFile(JsonFile);
        }
    }
}

There we are creating a custom ActionResult that concatenates the prefix – which are the part that will hold our variable name – with the content of the file – our JSON – and writes it all to the page buffer.

Now let’s make our Controller that will use the newly created class.

    public class SharedController : Controller
    {        
        //
        // GET: /Shared/Script

        public JsonToJavaScriptResult Script()
        {
            const string fileName = "common.json"
            const string prefix = "var Shared = ";
            var jsonFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);

            return new JsonToJavaScriptResult(prefix, jsonFile);
        }
    }

The last step is just insert the script tag in your page that will embed our code.

<script src="@Url.Action("Script", "Shared")" type="application/x-javascript"></script>

and you can do something like that

<script type="text/javascript">
  alert(Shared.highlightProductId);
</script>

Any new ideas or improvements are welcome.

This error occurs when you have MVC 2+ running hosted on IIS 7+, this is because ASP.NET 4 was not registered in IIS. In my case I was creating a MVC 3 project and hosting it on IIS 7.5.

To fix it, make sure you have MVC 2 or above and .Net Framework 4.0 installed, then run a command prompt as administrator and type the following line:

32bit (x86)

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

64bit (x64)

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Pattern Layout Converter is the way you tell log4net how to log something that it doesn’t know yet.

You first create your class that will get the information, for instance, this class will is to log the machine name:

using System;
using System.IO;
using log4net.Layout.Pattern;

namespace MyApplication.Logging
{
    public class MachinePatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            writer.Write(Environment.MachineName);            
        }
    }
}

Then, you edit your config file adding the converter you just created:

  <log4net>
    <appender name="Application" type="log4net.Appender.FileAppender">
      <file value="log\application.log" />
      <appendToFile value="true" />
      <maximumFileSize value="1024KB" />
      <layout type="log4net.Layout.PatternLayout">        
        <converter>
          <name value="machine" />
          <type value="MyApplication.Logging..MachinePatternConverter" />
        </converter>        
        <conversionPattern value="%date [%thread] %level %logger %machine - %message e:%exception%newline %newline" />
      </layout>
    </appender>
<!-- lines removed for brevity -->

In the code above, we added our new converter and named it “machine”. Then, In the conversionPattern line, we can use it wherever we want by adding the %machine variable.

Here are others converters you may want to use:

    public class IPPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (HttpContext.Current != null)
            {
                writer.Write(HttpContext.Current.Request.UserHostAddress);
            }
        }
    }

    public class UrlPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (HttpContext.Current != null)            
                writer.Write(HttpContext.Current.Request.Url.AbsoluteUri);
        }
    }

    public class UserAgentPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (HttpContext.Current != null)
            {
                writer.Write(HttpContext.Current.Request.UserAgent);
            }
        }
    }

Now, applying all converter in our config file:

  <log4net>
    <appender name="Application" type="log4net.Appender.FileAppender">
      <file value="log\application.log" />
      <appendToFile value="true" />
      <maximumFileSize value="1024KB" />
      <layout type="log4net.Layout.PatternLayout">
        <converter>
          <name value="url" />
          <type value="MyApplication.Logging.UrlPatternConverter" />
        </converter>
        <converter>
          <name value="ip" />
          <type value="MyApplication.Logging.IPPatternConverter" />
        </converter>
        <converter>
          <name value="machine" />
          <type value="MyApplication.Logging.MachinePatternConverter" />
        </converter>
        <converter>
          <name value="userAgent" />
          <type value="MyApplication.Logging.UserAgentPatternConverter" />
        </converter>
        <conversionPattern value="%date [%thread] %level %logger %url %ip %machine %userAgent - %message e:%exception%newline %newline" />
      </layout>
    </appender>

Do you have any interest Pattern Layout Converter you use in your application?

Logging to multiple files – Log4Net

I am going to explain how to log using Log4Net and how to separate the different types of logs from your application into different output files. The main focus of this post is not explain how log4net works in detail, however if your are interesting about learning more about it I recommend this article http://www.codeproject.com/KB/dotnet/Log4net_Tutorial.aspx.

The purpose here is to separate the log by source, for instance, caching log in one file, queries in another file, application log in another one, and also a single file for logging errors from all sources, this way we can find errors easier. The errors will still be logged in the library’s log though, because we may want to focus on that library specifically.

Take a look at this configuration file and will explain where the separation comes up later:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="Application" type="log4net.Appender.FileAppender">
    <file value="log\application.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
    <file value="log\error.log" />
    <rollingStyle value="Date" />
    <appendToFile value="true" />
    <datePattern value="ddMMyyyy" />
    <maxSizeRollBackups value="10" />
    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="ERROR"/>
    </filter>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>

  </appender>

  <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
    <bufferSize value="1" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="data source=127.0.0.1;initial catalog=Application_Log_Database;integrated security=false;persist security info=True;User ID=abc123;Password=abc123" />
    <!-- AppId parameter comes from the table Applications -->
    <commandText value="INSERT INTO application_log ([date],[thread],[level],[logger], [message], [exception]) VALUES (@log_date,@thread,@log_level,@logger, @message,@exception)" />

    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="ERROR"/>
      <levelMax value="FATAL"/>
    </filter>

    <parameter>
      <parameterName value="@log_date" />
      <dbType value="DateTime" />
      <layout type="log4net.Layout.RawTimeStampLayout" />
    </parameter>

    <parameter>
      <parameterName value="@thread" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@log_level" />
      <dbType value="String" />
      <size value="50" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@logger" />
      <dbType value="String" />
      <size value="255" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%logger" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@message" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message" />
      </layout>
    </parameter>

    <parameter>
      <parameterName value="@exception" />
      <dbType value="String" />
      <size value="4000" />
      <layout type="log4net.Layout.ExceptionLayout" />
    </parameter>    

  </appender>

  <appender name="OpenRasta" type="log4net.Appender.FileAppender">
    <file value="log\openrasta.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="Messaging" type="log4net.Appender.FileAppender">
    <file value="log\messaging.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="Queries" type="log4net.Appender.FileAppender">
    <file value="log\queries.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <appender name="Memcached" type="log4net.Appender.FileAppender">
    <file value="log\memcached.log" />
    <appendToFile value="true" />
    <maximumFileSize value="1024KB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level [%property{NDC}] - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="All" />
    <appender-ref ref="ErrorLog" />
    <appender-ref ref="AdoNetAppender" />
  </root>

  <logger name="Log4NetExample">
    <level value="INFO" />
    <appender-ref ref="Application" />
  </logger>

  <logger name="OpenRasta">
    <level value="INFO" />
    <appender-ref ref="OpenRasta" />
  </logger>

  <logger name="Spring">
    <level value="WARN" />
    <appender-ref ref="Messaging" />
  </logger>
  <logger name="NServiceBus">
    <level value="WARN" />
    <appender-ref ref="Messaging" />
  </logger>

  <logger name="System.Data.Linq">
    <level value="DEBUG" />
    <appender-ref ref="Queries" />
  </logger>

  <logger name="Enyim.Caching.Memcached">
    <level value="WARN" />
    <appender-ref ref="Memcached" />
  </logger>

</log4net>

Don’t be scared! It may look big, but that is because I’m showing a configuration with a lot of libraries and the AdoNetAppender is a little big too. What this configuration is doing is creating the Appenders, setting the root section, and then setting the level things will be logged with the loggers section.

The Appenders are most of them logging into text files, and one is logging into the database. In order to have the errors from all sources, notice we are adding the ErrorLog appender and the AdoNetAppender in the root section. This is because all the loggers must inherit those two. All the loggers will log their errors in a text file and in the database:

<root>
	<level value="All" />
	<appender-ref ref="ErrorLog" />
	<appender-ref ref="AdoNetAppender" />
</root>

The root’s log level is set to “All“, so if you don’t specify any level to a logger, it will inherit from the root and its value will be All as well.

If you look at those two appenders we are filtering their minimum level types as ERROR in the appender itself.

<appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">    
	<filter type="log4net.Filter.LevelRangeFilter">
	  <levelMin value="ERROR"/>
	</filter>
...

This is how we carry the error loggers along with the other loggers but logging only the errors. The libraries are filtered by their namespace, for instance Enyim.Caching.Memcached, and each library has its own logger set with a specific level of logging.

Log4net is a well known library and most of other libraries support it by default. For those libraries that doesn’t, for example, LinqToSql, a quick search on Google can give you the code to make it supported.

When you get data using LinqToSql and change something in the object, you expect that calling get object again will invalidate the cache and return the new objects, but it doesn’t! LinqToSql will return a reference of the object, what means, it will return the same object you had before.

The code below force LinqToSql to get new object(s), not the one(s) it has in memory:

public Order Get(int id)
{
	var order = Context.Orders.SingleOrDefault(o => o.orderId == id);
	
	if (order != null)
		// invalidate cache
		Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, order);

	return order;
}

Continuing my posts about configuration files, now I’m going to show you how to work with a list of items.

Here is the xml:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <enabled>true</enabled>
  <name>Example text name</name>
  <hosts>
    <host ip="127.0.0.1" port="80" username="test" password="pass" />
    <host ip="172.168.0.1" port="80" username="test2" password="pass2" />
  </hosts>
</main>

Is basically the same xml file I was using in the previous post but now hosts is a list and not only a single entry.

So, let’s see how we handle it in our code:

[XmlRoot("main")]
public class ModelExampleConfiguration
{
    public ModelExampleConfiguration()
    {
        this.Hosts = new List<HostConfiguration>();
    }
        
    [XmlElement("enabled")]
    public bool Enabled { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlArray("hosts")]
    [XmlArrayItem("host")]
    public List<HostConfiguration> Hosts { get; set; }
}

This is important! Note that the list had to be instantiated in the constructor so that the .NET can add the items into the list. Also, it was used to new attributes: XmlArray and XmlArrayItem. The first one defines the name of the list, and the second the name of the items of the list.

You might also need a list where you don’t have a parent item. Let’s see an example:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <enabled>true</enabled>
  <name>Example text name</name>
  <hosts>
    <host ip="127.0.0.1" port="80" username="test" password="pass" />
    <host ip="172.168.0.1" port="80" username="test2" password="pass2" />
  </hosts>
  <users groupName="admin">
    <user name="user1" />
    <user name="user2" />
  </users>
  <users groupName="guests">
    <user name="user3" />
    <user name="user4" />
  </users>
</main>

I add those two groups of users and each group of user has a list of users. Our full code then will look like:

using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [XmlRoot("main")]
    public class ModelExampleConfiguration
    {
        public ModelExampleConfiguration()
        {
            this.Hosts = new List<HostConfiguration>();
        }
        
        [XmlElement("enabled")]
        public bool Enabled { get; set; }

        [XmlElement("name")]
        public string Name { get; set; }

        [XmlArray("hosts")]
        [XmlArrayItem("host")]
        public List<HostConfiguration> Hosts { get; set; }

        [XmlElement("users")]
        public UserGroupConfiguration[] UserGroup { get; set; }
    }

    public class HostConfiguration
    {
        [XmlAttribute("ip")]
        public string IP { get; set; }

        [XmlAttribute("port")]
        public int Port { get; set; }

        [XmlAttribute("username")]
        public string Username { get; set; }

        [XmlAttribute("password")]
        public string Password { get; set; }
    }

    public class UserGroupConfiguration
    {
        [XmlAttribute("groupName")]
        public string GroupName { get; set; }

        [XmlElement("user")]
        public UserConfiguration[] Users { get; set; }
    }

    public class UserConfiguration
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
    }
}

See that now I used an array instead of a generic list. I could have used the list as well, but I think that way is simpler.

I’m currently working in a project where one need is to create easy customizable configuration files. The interest part comes when we need to read these configuration files and parsing them to .NET classes.

As I myself had to look up how some attributes work, I decided to share my experience creating those files, so this might help someone else going through the same problems.

To start off, let’s have a simple xml:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <enabled>true</enabled>
  <name>Example text name</name>
  <host ip="127.0.01" port="80" username="test" password="pass" />
</main>

Now the our model class:

using System.Xml.Serialization;

namespace ConsoleApplication1
{
    [XmlRoot("main")]
    public class ModelExampleConfiguration
    {
        [XmlElement("enabled")]
        public bool Enabled { get; set; }

        [XmlElement("name")]
        public string Name { get; set; }

        [XmlElement("host")]
        public HostConfiguration Host { get; set; }
    }

    public class HostConfiguration
    {
        [XmlAttribute("ip")]
        public string IP { get; set; }

        [XmlAttribute("port")]
        public int Port { get; set; }

        [XmlAttribute("username")]
        public string Username { get; set; }

        [XmlAttribute("password")]
        public string Password { get; set; }
    }
}

Note: If you have your class and property names exactly like your config file then you don’t need to specify the attributes, but I just prefer to always use them, this way I can name my classes however I want.

Notice I’m handling both elements and attributes, using XmlElement and XmlAttributes.

Now, the code to parse the xml into a model class:

using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var reader = XmlReader.Create("Example.xml");

            var factory = new XmlSerializerFactory();
            var serializer = factory.CreateSerializer(typeof(ModelExampleConfiguration));
            var config = serializer.Deserialize(reader) as ModelExampleConfiguration;
        }
    }
}

// config.Enabled will output true
// config.Host.Username will output test

In the next post I’ll show how to deserialize a list / array of items.

How to use CustomErrors in ASP.NET MVC 2

First, let’s see how our Web.config file will look like and after that I will show you how to create the pages.

<customErrors mode="On" defaultRedirect="~/Error">
  <error statusCode="404" redirect="~/Error/NotFound"/>
  <error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>

I’m going to show the steps to make it work for those three types of errors and also explain you about the HandleError attribute and how it handles the information specified in the customErrors. I’m also putting here the code I wrote in order to handle the AccessDenied error.

Error Page

When we are talking about the Error Page, one thing that you should understand is that without the HandleError Attribute, if an error occurs the .NET will just redirect the user to the page you specified in your Web.Config. So, if you have the “defaultRedirect” property pointing to something like “~/GenericError.aspx”, the GenericError.aspx page under the root folder of your project will be shown without any information about the Error. It could be a static HTML page that only tells the user “Hey, you’ve got an Error”.

Now, if you what you want is to show the user some information about the error, like the description or even the stackTrace but with the page looking like your default theme, then you can use the HandleError Attribute. By applying it to a Controller or a method the behavior of the customErrors changes a little bit. Instead of just pointing to some page, the exception handling will render a View, more specifically, a view called Error (if you don’t specify any other name to the Attribute) it doesn’t matter what name you’ve told the “defaultRedirect” to take you to. Along with that, it will send a HandleErrorInfo model containing the Controller name where the exception occurred, the Action name and the exception itself, so you can get the stackTrace and the description of the error.

Although it might seem obvious for some what the HandleError attribute does I’ve seen it’s a common issue people setting their customErrors to show something like GenericError.aspx and using the HandleError attribute. Or even, setting the defaultRedirect property to “Error” and expecting the Index method within the ErrorController to receive a HandleErrorInfo parameter. Remember, when using the HandleError attribute, the “Error“ View will be rendered internally, without even getting into the ErrorController.

Common mistake

Web.Config

<customErrors mode="On" defaultRedirect="Error/Ops" />

HomeController.cs

[HandleError] // using HandleError attribute
public class HomeController : Controller
{
    public ActionResult Index()
    {
		return View();
    }
}

ErrorController.cs

public class ErrorController : Controller
{
    public ActionResult Ops()
    {
        //
		// Wrong! It won't get here because
		// the HandleError will handle the error.
		return View();
    }
}

The right way

I’m going to demonstrate now how you can make it work with a page that shows some information about the error. With this example, even though someone forget using the HandleError attribute, a friendly page still shows up but without the error info (it’s better than not showing anything). It could be improved, off course, but that it’s another point.

Web.config

<customErrors mode="On" defaultRedirect="Error" />

Error.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>

<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Error
</asp:Content>

<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">       

    <h2>
        Sorry, an error occurred while processing your request.
    </h2>

	<% if (Model.Exception != null ) { %>
		<p>
		  Controller: <%= Model.ControllerName %>
		</p>
		<p>
		  Action: <%= Model.ActionName %>
		</p>
		<p>
		  Message: <%= Model.Exception.Message%>
		</p>
		<p>
		  Stack Trace: <%= Model.Exception.StackTrace%>
		</p>
	<% } %>
</asp:Content>

Place that page inside your Views folder. It can be either your Shared or Error folder. The name must be Error.aspx.

That’s it! Only the aspx file and the setting inside the Web.config.

Only if you want that whether the Controller have or not the HandleError attribute, your custom error page will still be shown, then you can add an action method into your ErrorController:

ErrorController.cs

public class ErrorController : Controller
{
    public ActionResult Index()
    {
		return View("Error");
    }
}

Now whether the page is being redirected to the defaultRedirect or rendered by the HandleError, the page will always be called.

To force an error, let’s create a code that throws an exception inside the Index of the HomeController:

int a = 0;
int b = 0;
int result = a / b;

That will throw the DivideByZeroException, see the friendly page in action:

CustomErrros Error Handling

 

404 NotFound Page

For the Not Found page we don’t have much to tell the user, so there is not much to do. It’s only the redirect to a page and, the information we can show is the wrong path. That information already comes as a query string.

Just to centralize the error handling and make it more organized, let’s put our NotFound within our ErrorController. So, add your the following method to the ErrorController:

public ActionResult NotFound(string aspxerrorpath)
{
	ViewData["error_path"] = aspxerrorpath;

	return View();
}

and the aspx page code:

NotFound.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Not Found
</asp:Content>

<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Sorry, the page <%: ViewData["error_path"] %> does not exist.
    </h2>    
</asp:Content>

and add the following line for the Not Found error into your customErrors section:

<customErrors mode="On" defaultRedirect="Error">
  <error statusCode="404" redirect="Error/NotFound"/>
</customErrors>

See the result:CustomError Page Not Found

 

403 AccessDenied

Most of the times when someone doesn’t have access to a page it’s only a login issue. But there are also times that a user has logged in but they are allowed to see something or perform some task, maybe because the lack of sufficient privileges. I’m going to show here how to handle those type of errors and the way I do that is by creating an ActionFilter attribute that you can put on a class or a method.

I’m going to hide some code for clarity:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Web.Configuration;

namespace ErrorHandling.Controllers
{
    public class AuthorizationAttribute : ActionFilterAttribute, IExceptionFilter
    {
        public string Action { get; set; }
        
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //
            // check permissions

            if (accessDenied)
            {
                throw new System.Web.HttpException((int)System.Net.HttpStatusCode.Forbidden,
                        "You are now allowed to see this page.");
            }

            base.OnActionExecuting(filterContext);
        }

        #region IExceptionFilter Members

        // this method is almost a clone of HandleErrorAttribute from MVC
        // it's just changed so that we take the error message to the page set in the <customErrors>
        public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
                return;

            Exception exception = filterContext.Exception;

            // If this is not an HTTP 403 (for example, if somebody throws an HTTP 500 from an action method),
            // ignore it.
            if (new HttpException(null, exception).GetHttpCode() != 403)
            {
                return;
            }

            // try to get the customError page for the 403 code
            string customErrorPage = GetCustomError("403");

            // if there isn't a redirect to a 403 error page then get out
            if (customErrorPage == null)
                return;

            filterContext.Result = new RedirectResult(String.Concat(customErrorPage, "?action=", this.Action));
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;            
        }

        #endregion

        public string GetCustomError(string statusCode)
        {
            CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;

            if (customErrorsSection != null)
            {
                CustomError customErrorPage = customErrorsSection.Errors[statusCode];

                if (customErrorPage != null)
                    return customErrorPage.Redirect;
            }
            return null;
        }        
    }
}

What that code does is throw an 403 Exception if the user rights are not enough, then we implement the IExceptionFilter, so we can handle the error on our own way with the OnException method. Notice we are reading the customErrors section looking for the page that is set for the 403 code and redirecting the user to that page.

With that AuthorizationAttribute you can decorate any class or method that you want to be checked when a user access it, like so:

[AuthorizationAttribute]
[HandleError]
public class HomeController : Controller

Let’s create our page inside the Views folder (again, it can be the Shared or the Errors folder) to tell the user about the error:

AccessDenied.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Access Denied
</asp:Content>

<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        Sorry, you do not have access to the action <%: ViewData["action"] %>.
    </h2>    
</asp:Content>

Add one more action method to our ErrorController:

public ActionResult AccessDenied(string action)
{
	ViewData["action"] = action;

	return View();
}

In this example, I’m passing in a parameter called “action” to the AccessDenied method, but it could be anything you want and can contain any information you want.

And finally, completing our Web.Config, we now add the treatment for the 403 error code:

<customErrors mode="On" defaultRedirect="Error">
  <error statusCode="404" redirect="Error/NotFound"/>
  <error statusCode="403" redirect="Error/AccessDenied"/>
</customErrors>

Here is how our ErrorController end up like:

namespace ErrorHandling.Controllers
{
    public class ErrorController : Controller
    {
        public ActionResult Index()
        {
            return View("Error");
        }

        public ActionResult NotFound(string aspxerrorpath)
        {
            ViewData["error_path"] = aspxerrorpath;

            return View();
        }

        public ActionResult AccessDenied(string action)
        {
            ViewData["action"] = action;

            return View();
        }
    }
}

With this structure the errors are very organized and all the things related to it are together.

I know there are other tutorials on the internet about this topic but I’m going to write here the way that worked for me.

Some tutorials I’ve seen tell you to change your Global.asax to add some routes. I didn’t have to change it at all. I only had to setup the IIS itself.

IIS 5

Configure your Virtual Directory as usual, then right click on it and select Properties. In the properties dialog, click on Configuration.  In this dialog, click on Add. Then use the settings below:

Configuring IIS 5

For Executable, use the following path:

c:\windows\microsoft.net\framework\v4.0.30319\aspnet_isapi.dll
or
c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll

depending on the version of .NET you are using on your application. You can copy the path from the other mappings that already exist.

Also make sure you uncheck the “Check that file exists” box.

Well, that is what it took for me to make it work on IIS 5.

IIS 6

For IIS 6 is not that different from what it needs on IIS 5. The process is the same until you get to the Configuration dialog. Now you add the same path showed above but the extension will change a bit. Take a look:

Configuring IIS 6

The option “Verify that file exists” must be unchecked.

After hitting OK, still in the Configuration dialog you have to add a Wildcard. Click on Insert and use the same DLL path you’ve been adding so far.

Configuring IIS 6

Once again, the option “Verify that file exists” must be unchecked – I know it’s annoying but that’s how it must be done.

See how the Configuration dialog must look like:

Configuring IIS 6

Note the extension and the wildcard added. Now, just hit OK and you’re done.

One thing I noticed is that if you name your Virtual Directory Anything.MVC it won’t work because of that “.mvc” extension you added.

Don’t worry. After doing that over and over again you get practice ;)

One good thing is that Microsoft is releasing a new Web Server called IIS Express which is as easy as the ASP.NET Development Server (that instance of Web Server that Visual Studio launches when you run a project) to configure but has almost all the features from the full version of IIS. On the new IIS Express you won’t need any extra configuration to have your ASP.NET MVC application up and running.

The new Microsoft WebMatrix – it’s like a small version of Visual Studio – already comes with the IIS Express. You can download WebMatrix here.

Follow

Get every new post delivered to your Inbox.