<?xml version="1.0" encoding="utf-8"?><rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0"><channel xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"><title>Jambr - Articles</title><link>http://www.jambr.co.uk/Article</link><description>Jambr Programming Articles</description><language>en-GB</language><lastBuildDate>Mon, 31 Dec 2012 20:00:21 Z</lastBuildDate><generator>Jambr RSS Generator</generator><item><guid isPermaLink="false">8d015244-a102-4a76-a3a4-4782b1eba0bd</guid><link>http://www.jambr.co.uk/Article/form-field-encrpytion</link><category domain="http://www.jambr.co.uk/Article/?Tag=.NET">.NET</category><category domain="http://www.jambr.co.uk/Article/?Tag=MVC">MVC</category><category domain="http://www.jambr.co.uk/Article/?Tag=Security">Security</category><title>Automatic encryption of secure form field data</title><description>In this article I will show you how to handle automatic encryption and decryption of hidden form fields using Rijndael</description><pubDate>Mon, 31 Dec 2012 20:00:21 Z</pubDate><dc:creator>Karl</dc:creator><content:encoded>&lt;h3&gt;Overview&lt;/h3&gt;&lt;div&gt;My article on &lt;a href="http://www.jambr.co.uk/Article/action-filter-request-throttle"&gt;Throttling Requests&lt;/a&gt;&amp;nbsp;got quite a bit of attention, so I thought I would continue the security theme and show you a simple method of automatically encrypting hidden form fields that you don't want the user to be able to change, or know the value of. &amp;nbsp; I will be making use of an extension to the HtmlHelper, a custom ModelBinder to handle the decryption and also Rijndael&amp;nbsp;encryption&amp;nbsp;to secure your data (you&amp;nbsp;could use any method of&amp;nbsp;encryption&amp;nbsp;you so desire).&lt;/div&gt;&lt;div&gt;I must stress that this is simply one measure to ensure the security of your data, you should always still be validating the action at the code and finally database level, to ensure you have a secure application!&lt;/div&gt;&lt;h3&gt;Example&lt;/h3&gt;&lt;div&gt;A really simple example of this would be on a CMS system, lets say user can only edit posts that they created. &amp;nbsp;You may have something like this in your view:&lt;/div&gt;&lt;pre&gt;        &amp;lt;%Using Html.BeginForm  %&amp;gt;
            &amp;lt;%:Html.HiddenFor(Function(m) m.DatabaseID)%&amp;gt;
            &amp;lt;!-- Other Editing fields here--&amp;gt;
            &amp;lt;input type="submit" value="Submit!" /&amp;gt;
        &amp;lt;%end using %&amp;gt;&lt;/pre&gt;&lt;div&gt;If we inspected the code that is generated, we would get this:&lt;/div&gt;&lt;pre&gt;        &amp;lt;form action="/Home/Test" method="post"&amp;gt;
            &amp;lt;input data-val="true" id="DatabaseID" name="DatabaseID" type="hidden" value="2012" /&amp;gt;
            &amp;lt;input type="submit" value="Submit!" /&amp;gt;
        &amp;lt;/form&amp;gt;
&lt;/pre&gt;&lt;div&gt;As you can quite clearly see, the database ID is 2012, and I could quite easily edit it to be able to submit against say, record 2013, which was posted by another user, if (god forbid) there was nothing checking in the back end that the user posting back actually has permissions to edit the post, you could malliciously edit other peoples data.&lt;/div&gt;&lt;div&gt;&lt;h3&gt;Rijndael&lt;/h3&gt;&lt;/div&gt;&lt;div&gt;As I mentioned previous, I am going to be using Rijndael to handle my encryption, I'm not going to post all of the code here, you can use any&amp;nbsp;encryption&amp;nbsp;method you want, I personally grabbed &lt;a href="http://www.obviex.com/samples/Encryption.aspx" target="_blank"&gt;this example&lt;/a&gt;, and made a few modifications to suit. &amp;nbsp;Make sure you have a&amp;nbsp;suitable&amp;nbsp;encryption&amp;nbsp;class in your project before you read past here!&lt;/div&gt;&lt;h3&gt;Encryption&lt;/h3&gt;&lt;div&gt;The first thing we want to do is create the part which handles encryption. &amp;nbsp;We want to simply be able to replace the "HiddenFor()" with "EncryptedFor()". &amp;nbsp;To do this we need to create a HtmlHelper extension which accepts a Linq expression of the&amp;nbsp;targeted&amp;nbsp;field, so it works in much the same way as HiddenFor.&lt;/div&gt;&lt;pre&gt;        ''' &amp;lt;summary&amp;gt;
        ''' Creates an encrypted version of the field
        ''' &amp;lt;/summary&amp;gt;
        &amp;lt;System.Runtime.CompilerServices.Extension&amp;gt; _
        Public Function EncryptedFor(Of TModel, TProperty)(htmlHelper As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TProperty))) As MvcHtmlString
            Dim name As String
            If TypeOf expression.Body Is MemberExpression Then
                name = DirectCast(expression.Body, MemberExpression).Member.Name
            Else
                Dim op = (CType(expression.Body, UnaryExpression).Operand)
                name = DirectCast(op, MemberExpression).Member.Name
            End If

            'Get the value, and then encrypt it
            Dim value = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData)
            Dim encvalue = RijndaelSimple.Encrypt(value.Model, HttpContext.Current.User.Identity.Name)
            Return New MvcHtmlString("&amp;lt;input type=""hidden"" name=""" &amp;amp; name &amp;amp; "-encrypted"" value=""" &amp;amp; encvalue &amp;amp; """&amp;gt;")
        End Function&lt;/pre&gt;&lt;div&gt;So now, if we go back to our form, we should be able to switch to EncryptedFor, which will generate the hidden field:&lt;/div&gt;&lt;pre&gt;        &amp;lt;form action="/Home/Test" method="post"&amp;gt;
            &amp;lt;input type="hidden" name="DatabaseID-encrypted" value="3JSlRkRb98Ow11HkGRb1XQ=="&amp;gt;
            &amp;lt;!-- Other Editing fields here--&amp;gt;
            &amp;lt;input type="submit" value="Submit!" /&amp;gt;
        &amp;lt;/form&amp;gt;
&lt;/pre&gt;&lt;div&gt;As you can see, the field name has been appended with "-encrypted", and the value is the encrypted string.&lt;/div&gt;&lt;h3&gt;Decryption&lt;/h3&gt;&lt;div&gt;The next thing we need to do is to handle the decryption and setting of the value. &amp;nbsp;The MVC model binder will obviously not know that the field "DatabaseID-encrypted" is actually for the field "DatabaseID". &amp;nbsp;What we need to do is create a custom model binder, which looks for the field in the Request.Form, decrypts it, and then sets the property.&lt;/div&gt;&lt;pre&gt;Public Class EncryptedModelBinder
    Inherits DefaultModelBinder

    Protected Overrides Sub BindProperty(controllerContext As ControllerContext, 
                                         bindingContext As ModelBindingContext, propertyDescriptor As System.ComponentModel.PropertyDescriptor)

        If propertyDescriptor.Attributes.OfType(Of EncryptedAttribute)().Count &amp;gt; 0 Then
            'Look for the encrypted field
            If controllerContext.HttpContext.Request.Form(propertyDescriptor.Name &amp;amp; "-encrypted") IsNot Nothing Then
                Dim decvalue = controllerContext.HttpContext.Request.Form(propertyDescriptor.Name &amp;amp; "-encrypted")
                decvalue = RijndaelSimple.Decrypt(decvalue, "Some unique key")
                propertyDescriptor.SetValue(bindingContext.Model, If(IsNumeric(decvalue), CInt(decvalue), decvalue))
                MyBase.BindProperty(controllerContext, bindingContext, propertyDescriptor)
            End If
        Else
            'Normal binding
            MyBase.BindProperty(controllerContext, bindingContext, propertyDescriptor)
        End If

    End Sub
End Class&lt;/pre&gt;&lt;div&gt;You'll notice here that I am looking for an EncryptedAttribute. &amp;nbsp;This is because we want to prevent people just inspecting the code and posting back to the database ID. &amp;nbsp;We decorate the properties that are expected to be encrypted with a simple attribute which basically says "Only set me using the -encrypted post back value, ignore anything else"&lt;/div&gt;&lt;pre&gt;Public Class EncryptedAttribute
    Inherits Attribute
End Class&lt;/pre&gt;&lt;div&gt;We just need to register this in our Gloabl.asax.vb file as well:&lt;br&gt;&lt;pre&gt;ModelBinders.Binders.DefaultBinder = New EncryptedModelBinder&lt;/pre&gt;And that's it!&lt;/div&gt;&lt;h3&gt;The Result&lt;/h3&gt;&lt;div&gt;&lt;div&gt;I created a simple method which dumps out the request.form contents from the post back, and also outputs the value of the field. &amp;nbsp;As you can see the encrypted value was passed back, but the property has correctly been set!&lt;/div&gt;&lt;pre&gt;Content of the request.form: 
DatabaseID-encrypted: SVwvHJ8kzCeIjIN4VZeJLw==

The DatabaseID on the model is set to: 2012&lt;/pre&gt;&lt;h3&gt;Conclusion&lt;/h3&gt;&lt;/div&gt;&lt;div&gt;The aim of this article was to give you another tool to secure your websites, and that's all it is, a tool. &amp;nbsp;You should be secure your website every step of the way! &amp;nbsp;As usual, any questions, please leave a comment.&lt;/div&gt;</content:encoded></item><item><guid isPermaLink="false">1f0d6506-82c0-4b35-96e7-a5febeae3709</guid><link>http://www.jambr.co.uk/Article/generate-google-bing-sitemap</link><category domain="http://www.jambr.co.uk/Article/?Tag=.NET">.NET</category><category domain="http://www.jambr.co.uk/Article/?Tag=MVC">MVC</category><title>Generating a valid sitemap automatically with .NET</title><description>In this article I will show how to generate an approved sitemap automatically for use with search engines</description><pubDate>Sun, 30 Dec 2012 14:29:33 Z</pubDate><dc:creator>Karl</dc:creator><content:encoded>&lt;h3&gt;Overview&lt;/h3&gt;&lt;div&gt;Jambr is still a baby, as such it's content and structure is changing.&amp;nbsp;&lt;/div&gt;&lt;div&gt;It originally existed on two urls (www and non-www), and google was indexing both of them and to add to it not long ago I changed the url structure for Articles to be more, SEO friendly.&amp;nbsp;&lt;/div&gt;&lt;div&gt;All of these changes confuse search engine indexers and one way to help them out is to provide them with a &lt;a href="http://www.sitemaps.org/" target="_blank"&gt;Sitemap&lt;/a&gt;. &amp;nbsp;My rough list of requirements were:&lt;/div&gt;&lt;div&gt;&lt;ul class="standard-list"&gt;&lt;li&gt;To comply fully with the &lt;a href="http://www.sitemaps.org/schemas/sitemap/0.9" target="_blank"&gt;Sitemap protocol&lt;/a&gt;&lt;/li&gt;&lt;li&gt;To generate automatically, when /sitemap.xml was called&lt;/li&gt;&lt;li&gt;To be able to decorate fixed controller actions with an attribute which would include them in the map.&lt;/li&gt;&lt;li&gt;To provide a simple way of adding the dynamic content&lt;/li&gt;&lt;li&gt;To cache the output for a period of time&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;h3&gt;Implementation&lt;/h3&gt;&lt;div&gt;First things first, we need to create an XML document which matches the Sitemap protocol. &amp;nbsp;So we create a new XmlDocument and from there, we add the xmlns for the Sitemap protocol, and add the root element "urlset"&lt;/div&gt;&lt;pre&gt;        ''' &amp;lt;summary&amp;gt;
        ''' The scheme we add to the document
        ''' &amp;lt;/summary&amp;gt;
        Private Const SiteMapSchemaURL As String = "http://www.sitemaps.org/schemas/sitemap/0.9"

        ''' &amp;lt;summary&amp;gt;
        ''' The full URL to your website, for example http://www.jambr.co.uk
        ''' &amp;lt;/summary&amp;gt;
        Private Property FullyQualifiedUrl As String

        Private _document As XmlDocument
        ''' &amp;lt;summary&amp;gt;
        ''' Returns the XML document
        ''' &amp;lt;/summary&amp;gt;
        Private ReadOnly Property Document As XmlDocument
            Get
                Return _document
            End Get
        End Property

        ''' &amp;lt;summary&amp;gt;
        ''' Create a new instance of the SiteMapGenerator, initialise the XML document
        ''' and add the required namespaces
        ''' &amp;lt;/summary&amp;gt;
        ''' &amp;lt;param name="FullyQualifiedUrl"&amp;gt;The full URL to your website, for example http://www.jambr.co.uk&amp;lt;/param&amp;gt;
        Public Sub New(ByVal FullyQualifiedUrl As String)

            Me.FullyQualifiedUrl = FullyQualifiedUrl.Replace("\", "/")

            _document = New XmlDocument
            Document.AppendChild(Document.CreateNode(XmlNodeType.XmlDeclaration, Nothing, Nothing))

            'Create the root element and add the sitemap namespace
            Dim rootelement = Document.CreateElement("urlset", SiteMapSchemaURL)
            Document.AppendChild(rootelement)

        End Sub&lt;/pre&gt;&lt;div&gt;Next I wanted to create a flexible method to add new urls, that accepted all the valid options for the url child elements, on an optional basis, and only adding them if they're passed:&lt;/div&gt;&lt;pre&gt;        ''' &amp;lt;summary&amp;gt;
        ''' Adds a URL to the site map
        ''' &amp;lt;/summary&amp;gt;
        ''' &amp;lt;param name="Location"&amp;gt;The URL to the page, will check for your domain and add if required.&amp;lt;/param&amp;gt;
        ''' &amp;lt;param name="LastModified"&amp;gt;Optional: The date the URL was last modified&amp;lt;/param&amp;gt;
        ''' &amp;lt;param name="ChangeFrequency"&amp;gt;Optional: The expected change frequency of the URL&amp;lt;/param&amp;gt;
        ''' &amp;lt;param name="Priority"&amp;gt;Optional: The priority of the page, ranging from 0.0 to 1.0, default is 0.5&amp;lt;/param&amp;gt;
        Public Sub AddUrl(ByVal Location As String,
                          Optional ByVal ChangeFrequency As ChangeFrequency = Nothing,
                          Optional ByVal Priority As Decimal = Nothing,
                          Optional LastModified As DateTime = Nothing)

            'sanitise the url
            Location = Location.Replace("\", "/")
            If Not Location.ToLower.Contains(FullyQualifiedUrl.ToLower) Then
                Location = FullyQualifiedUrl &amp;amp; If(Left(Location, 1) = "/", Location, "/" &amp;amp; Location)
            End If

            'check we haven't added it already in a stored list of urls we've added
            If AddedUrls.Contains(Location) Then Exit Sub
            AddedUrls.Add(Location)

            'Required elements
            Dim newUrl = Document.CreateElement("url", SiteMapSchemaURL)
            newUrl.AppendChild(CreateTextElement("loc", Location))

            'Optional Elements
            If Not LastModified = Nothing Then
                newUrl.AppendChild(CreateTextElement("lastmod", LastModified.ToW3C))
            End If

            If Not ChangeFrequency = Nothing Then
                newUrl.AppendChild(CreateTextElement("changefreq", ChangeFrequency.ToString))
            End If

            If Not Priority = Nothing Then
                newUrl.AppendChild(CreateTextElement("priority", Priority))
            End If

            Document.DocumentElement.AppendChild(newUrl)

        End Sub
&lt;/pre&gt;&lt;h3&gt;Reflection&lt;/h3&gt;&lt;div&gt;I mentioned previously that I wanted an easy way to add URLs, I didn't want to create a class which needed me to call AddUrl() over and over for all my pages. &amp;nbsp;I decided to go down the route of creating a custom SettingAttribute, that I could just stick at the top of the controller actions I wanted to map, like this:&lt;/div&gt;&lt;pre&gt;    &amp;lt;SiteMap(ChangeFrequency:=ChangeFrequency.daily, Priority:=0.7)&amp;gt;
    Function Index() As ActionResult
        Return View(New HomeViewModel)
    End Function&lt;/pre&gt;&lt;div&gt;Next huh? &amp;nbsp;Now you've probably realised that this would only work for static URL's, dynamic actions that require parameters &lt;a href="http://www.jambr.co.uk/Article/generate-google-bing-sitemap"&gt;like this&lt;/a&gt;, wouldn't work. &amp;nbsp;In the context of &lt;a href="http://www.jambr.co.uk"&gt;Jambr &lt;/a&gt;I have two controllers which serve dynamic content, Articles and News. &amp;nbsp;I decided to go down the route of creating an interface, which allowed me to have a sub routine that could be called by the site map generator, like this:&lt;/div&gt;&lt;pre&gt;    ''' &amp;lt;summary&amp;gt;
    ''' Populate the site map with the dynamic data
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;param name="generator"&amp;gt;the generate object that gets passed&amp;lt;/param&amp;gt;
    Public Sub PopulateSiteMap(ByRef generator As SiteMapGenerator) Implements ISiteMap.PopulateSiteMap

        'We need to initialise the UrlHelper because of the way we've invokved this method
        Url = New UrlHelper(System.Web.HttpContext.Current.Request.RequestContext)

        Using db As New JambrDBContext

            'Lets add dynamic data, starting with my articles
            Dim articles = (db.
                           ArticlePosts.
                           Where(Function(w) w.IsLive = True).
                           OrderByDescending(Function(o) o.LastUpdated).
                           Select(Function(s) New With {.SEOUrl = s.SEOUrl,
                                                        .LastUpdated = s.LastUpdated})).tolist

            'Add my root element, with a last modified date of the latest article
            generator.AddUrl(Url.Action("Index", "Article"), ChangeFrequency.daily, Nothing, articles.First.LastUpdated)
            'Add the RSS feed, as it has the same last udpated date
            generator.AddUrl(Url.Action("RSS", "Article"), ChangeFrequency.daily, Nothing, articles.First.LastUpdated)

            'Add my other elements
            For Each post In articles
                generator.AddUrl(Url.Action("View", "Article", New With {.SEOUrl = post.SEOUrl}), Nothing, Nothing, post.LastUpdated)
            Next
            articles = Nothing

        End Using

    End Sub&lt;/pre&gt;&lt;div&gt;We just look for either the SiteMapAttribute, or the Implementation of ISiteMap using reflection and get the associated details like so:&lt;/div&gt;&lt;pre&gt;    ''' &amp;lt;summary&amp;gt;
    ''' When called, the site map generator will attempt to load any action methods
    ''' that are decorated with the SiteMapAttribute from your controller classes and
    ''' add a url for them based on it
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;remarks&amp;gt;&amp;lt;/remarks&amp;gt;
    Public Sub LoadFromAttribute()

        'Get all the controllers in the project
        Dim controllers = Assembly.
                          GetExecutingAssembly.
                          GetTypes().
                          Where(Function(t) GetType(System.Web.Mvc.ControllerBase).IsAssignableFrom(t))

        'First we want to get all controllers that implement the ISiteMap interface and fire the method
        For Each c In controllers.Where(Function(t) GetType(ISiteMap).IsAssignableFrom(t))

            'Create an instance
            Dim obj As ISiteMap = Activator.CreateInstance(c, True)
            obj.PopulateSiteMap(Me)

        Next

        'Now get all the methods which are decorated with the SiteMapAttribute
        Dim objs = (From c In controllers
                   From act In c.GetMembers
                   Where act.GetCustomAttributes(True).OfType(Of SiteMapAttribute)().Count &amp;gt; 0
                   Select New With {.controller = c,
                                    .action = act,
                                    .actionnameattribute = act.GetCustomAttributes(True).OfType(Of ActionNameAttribute)().FirstOrDefault,
                                    .sitemapattribute = act.GetCustomAttributes(True).OfType(Of SiteMapAttribute)().FirstOrDefault}).ToList

        'We need a url helper to help us generate the url path
        Dim UrlHelper = New UrlHelper(HttpContext.Current.Request.RequestContext)

        For Each p In objs
            'Now we have the objects, we need to build the url.  We need to look out for the ActionNameAttribute in case people are using it
            'to name their action methods, we also need to remove Controller from the name of the controller
            Dim url As String = UrlHelper.Action(If(p.actionnameattribute Is Nothing, p.action.Name, p.actionnameattribute.Name),
                                                 p.controller.Name.Replace("Controller", ""))

            'Add the object
            AddUrl(url,
                   p.sitemapattribute.ChangeFrequency,
                   p.sitemapattribute.Priority,
                   If(p.sitemapattribute.LastModified Is Nothing,
                      Nothing,
                      DateTime.Parse(p.sitemapattribute.LastModified, (New CultureInfo("en-us")))
                      )
                   )
        Next

    End Sub
&lt;/pre&gt;&lt;div&gt;Now add a route for sitemap.xml (remember this programming article is based around .Net MVC) in your RouteConfig.vb&lt;/div&gt;&lt;pre&gt;        'This is to overwrite the sitemap request
        routes.MapRoute( _
            name:="SiteMap", _
            url:="sitemap.xml", _
            defaults:=New With {.controller = "SiteMap", .action = "Index"})&lt;/pre&gt;&lt;div&gt;Set the controller and action to wherever you're going to put your method, I decided to put mine in a new controller. &amp;nbsp;Finally create your action method, I've decorated mine with the OutputCache attribute and set it to 6 hours, with the ability to clear the cache by using the&amp;nbsp;query string&amp;nbsp;parameter ClearCache&lt;/div&gt;&lt;pre&gt;    ''' &amp;lt;summary&amp;gt;
    ''' Returns the site map
    ''' &amp;lt;/summary&amp;gt;
    &amp;lt;OutputCache(Duration:=21600, VaryByParam:="ClearCache", Location:=OutputCacheLocation.Server)&amp;gt;
    Function Index() As ActionResult

        'Create our site map
        Dim p As New SiteMapGenerator("http://www.jambr.co.uk")

        'Load any methods which are tagged with the attribute
        p.LoadFromAttribute()

        'Return the content
        Return Content(p.ToString, "text\xml")

    End Function&lt;/pre&gt;Something to note here is that I have created a ToString method, which takes the XmlDocument and outputs it as a UTF8 string, UTF8 is important so there is another class in the &lt;a href="http://jambr.blob.core.windows.net/articledownloads/SiteMapGenerator.vb"&gt;source code &lt;/a&gt;which creates a UTF8 based string writer.
&lt;h3&gt;Conclusion&lt;/h3&gt;&lt;div&gt;I hope this article has shown you a clean way to implement a dynamic site map in .NET MVC using flexible attributes, full source code can be downloaded from &lt;a href="http://jambr.blob.core.windows.net/articledownloads/SiteMapGenerator.vb" target="_blank"&gt;Here&lt;/a&gt;, if you want to see my sitemap, check it &lt;a href="http://www.jambr.co.uk/sitemap.xml" target="_blank"&gt;Here &lt;/a&gt;and as usual - any questions please drop me a comment!&lt;/div&gt;</content:encoded></item><item><guid isPermaLink="false">cbc69566-b489-4965-989d-2c8130104cb2</guid><link>http://www.jambr.co.uk/Article/action-filter-request-throttle</link><category domain="http://www.jambr.co.uk/Article/?Tag=.NET">.NET</category><category domain="http://www.jambr.co.uk/Article/?Tag=MVC">MVC</category><category domain="http://www.jambr.co.uk/Article/?Tag=Security">Security</category><title>Throttle requests to a .NET MVC action with a custom Action Filter</title><description>In this programming article I will show you how to create a custom action filter for .NET MVC which will throttle repeat requests</description><pubDate>Fri, 28 Dec 2012 11:38:36 Z</pubDate><dc:creator>Karl</dc:creator><content:encoded>&lt;h3&gt;Overview&lt;/h3&gt;&lt;div&gt;In my day job I work for HP Enterprise Security Services, part of my role is building secure and robust web applications which do everything possible to prevent malicious attacks.&lt;/div&gt;&lt;div&gt;One of the most simple things you can do in your MVC project is to prevent repeat requests to a page. &amp;nbsp;This is primarily used in form submissions, for example in the comments box you see on &lt;a href="http://www.jambr.co.uk/Article/action-filter-request-throttle#Comment"&gt;Jambr&lt;/a&gt;, I don't want people to be able to&amp;nbsp;repeatedly post to it over and over again, I want to introduce a time limit&amp;nbsp;in-between&amp;nbsp;these requests.&lt;/div&gt;&lt;div&gt;Also, there are going to be a lot of places on a typical site you want to limit such behaviour, but don't want to repeat the code everywhere. &amp;nbsp;This is where custom Action Filter Attributes come in.&lt;/div&gt;&lt;h3&gt;Creating an Attribute&lt;/h3&gt;&lt;div&gt;Creating a custom attribute is easy, take a look at this piece of code, i'll explain what it does below:&lt;/div&gt;&lt;pre&gt;&amp;lt;AttributeUsage(AttributeTargets.Method, AllowMultiple:=False)&amp;gt;
Public NotInheritable Class RequestThrottleAttribute
    Inherits ActionFilterAttribute

    Public Overrides Sub OnActionExecuting(filterContext As ActionExecutingContext)
        'Do some logic in here to decide what is going to happen
    End Sub
End Class&lt;/pre&gt;&lt;div&gt;What we're doing here is inheriting from the &lt;b&gt;ActionFilterAttribute&lt;/b&gt;, class and overriding the &lt;b&gt;OnActionExecuting&lt;/b&gt;&amp;nbsp;method, which is where we will put our logic.&lt;/div&gt;&lt;div&gt;I have decorated this class with some attributes of there own, &lt;b&gt;AttributeTargets.Method&lt;/b&gt;&amp;nbsp;states that this attribute can only be used on methods, and &lt;b&gt;AllowMultiple&lt;/b&gt;&amp;nbsp;states that there can only be one instance of it.&lt;/div&gt;&lt;h3&gt;Expanding on the base Attribute&lt;/h3&gt;&lt;div&gt;The next thing to do is expand our logic out a bit. &amp;nbsp;Lets make this attribute as flexible as possible, so for example lets make the amount of time between requests flexible, give the option to either Redirect when an error occurs or simple add an error to the ModelState dictionary.&lt;/div&gt;&lt;div&gt;Start by adding some properties to represent our customisable options:&lt;/div&gt;&lt;pre&gt;    ''' &amp;lt;summary&amp;gt;
    ''' The amount of time between each request
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;value&amp;gt;&amp;lt;/value&amp;gt;
    ''' &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
    ''' &amp;lt;remarks&amp;gt;&amp;lt;/remarks&amp;gt;
    Public Property TimeBetweenRequests As Integer = 5

    ''' &amp;lt;summary&amp;gt;
    ''' The name of the object in the ModelState to add an error too
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;value&amp;gt;&amp;lt;/value&amp;gt;
    ''' &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
    ''' &amp;lt;remarks&amp;gt;&amp;lt;/remarks&amp;gt;
    Public Property ModelErrorName As String = Nothing

    ''' &amp;lt;summary&amp;gt;
    ''' The message to add to the ModelState object specified in ModelErrorName
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;value&amp;gt;&amp;lt;/value&amp;gt;
    ''' &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
    ''' &amp;lt;remarks&amp;gt;&amp;lt;/remarks&amp;gt;
    Public Property ModelErrorValue As String = "Maximum number of requests exceeded"

    ''' &amp;lt;summary&amp;gt;
    ''' A URL to redirect to
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;value&amp;gt;&amp;lt;/value&amp;gt;
    ''' &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
    ''' &amp;lt;remarks&amp;gt;&amp;lt;/remarks&amp;gt;
    Public Property RedirectOnError As String = Nothing&lt;/pre&gt;&lt;div&gt;So in order to add an error to the ModelState dictionary, we need need the name of the object to associate the error to (of course, this could just be an empty string for a generic error) - this is passed as &lt;b&gt;ModelErrorName&lt;/b&gt;, and we also need the message to set - this is passed in &lt;b&gt;ModelErrorValue&lt;/b&gt;.&amp;nbsp;&lt;/div&gt;&lt;div&gt;If we wanted to redirect instead, we would set &lt;b&gt;RedirectOnError&lt;/b&gt;.&lt;/div&gt;&lt;h3&gt;Caching and Cache Expiration&lt;/h3&gt;&lt;div&gt;Next, we need to customise the&amp;nbsp;&lt;b&gt;OnActionExecuting&lt;/b&gt;&amp;nbsp;method to do our throttling. &amp;nbsp;We need to store somewhere the fact that a given user (lets define a user by their IP address as well as their user agent) has been to the page recently. &amp;nbsp;I decided to generate a unique key from the information given, and store it in the HttpContext.Cache and set it to expire on a time which is equal to the &lt;b&gt;TimeBetweenRequests &lt;/b&gt;parameter of our attribute. &amp;nbsp; That way on the next request, all we need to do is check for the&amp;nbsp;existence&amp;nbsp;of the same key in the cache. &amp;nbsp;&lt;/div&gt;&lt;div&gt;Take a look at the code below of the &lt;b&gt;OnActionExecuting&lt;/b&gt;&amp;nbsp;method:&lt;/div&gt;&lt;pre&gt;    Public Overrides Sub OnActionExecuting(filterContext As ActionExecutingContext)

        Dim HttpContext = filterContext.HttpContext

        'Get the details of the path they're requesting
        Dim pathInfo = HttpContext.Request.ServerVariables("PATH_INFO") &amp;amp; filterContext.HttpContext.Request.ServerVariables("QUERY_STRING")
        
        'Get who requested it, get their user agent as well, as multiple people in the same room could be coming from the same IP
        Dim requestedBy = HttpContext.Request.ServerVariables("REMOTE_ADDR") &amp;amp; HttpContext.Request.ServerVariables("HTTP_USER_AGENT")

        'Generate a unique key based on it
        Dim key = MD5(pathInfo &amp;amp; requestedBy)

        'Check to see if that key is in the cache
        If HttpContext.Cache.Get(key) IsNot Nothing Then
            'Reject the request
            If ModelErrorName IsNot Nothing Then
                'Add it to the modelstate
                filterContext.Controller.ViewData.ModelState.AddModelError(ModelErrorName, ModelErrorValue)
            End If
            If RedirectOnError IsNot Nothing Then
                'Redirect
                filterContext.Result = New RedirectResult(RedirectOnError, False)
            End If
        Else
            'Add it to the cache
            HttpContext.Cache.Add(key, New Object, Nothing, Now.AddSeconds(TimeBetweenRequests), Cache.NoSlidingExpiration, CacheItemPriority.Normal, Nothing)
        End If

    End Sub&lt;/pre&gt;In case you don't already have code to create an MD5 of a string, here it is, you'll need to import System.Security.Cryptography:&lt;div&gt;&lt;pre&gt;        Public Shared Function MD5(ByVal strToHash) As String
            Dim bytToHash As Byte() = ASCIIEncoding.ASCII.GetBytes(strToHash)
            Dim tmpHash As Byte() = (New MD5CryptoServiceProvider).ComputeHash(bytToHash)
            Dim i As Integer
            Dim sOutput As New StringBuilder(tmpHash.Length)
            For i = 0 To tmpHash.Length - 1
                sOutput.Append(tmpHash(i).ToString("X2"))
            Next
            Return sOutput.ToString()
        End Function&lt;/pre&gt;&lt;h3&gt;Using the new Attribute&lt;/h3&gt;&lt;div&gt;Now that your attribute is complete, all you need to do is implement it by decorating a given method with it. &amp;nbsp;Take these two examples:&lt;/div&gt;&lt;pre&gt;    &amp;lt;HttpGet&amp;gt;
    &amp;lt;RequestThrottle(TimeBetweenRequests:=10, RedirectOnError:="/Error/Throttle")&amp;gt;
    Function TestThrottle()
        Return View(New TestThrottleViewModel)
    End Function&lt;/pre&gt;&lt;div&gt;This action method will only allow one request per 10 seconds to the url /TestThrottle, before it redirects to an error page.&lt;/div&gt;&lt;div&gt;The next example will add the error to the ModelState instead, so you can return to the user on the same page:&lt;/div&gt;&lt;pre&gt;    &amp;lt;HttpPost&amp;gt;
    &amp;lt;RequestThrottle(TimeBetweenRequests:=10, ModelErrorName:="Comment", ModelErrorValue:="There is a 10 second wait between posts")&amp;gt;
    Function TestThrottle(ByVal model As TestThrottleViewModel)
        If ModelState.IsValid Then
            Return Content("Thanks")
        Else
            Return View(model)
        End If
    End Function&lt;/pre&gt;&lt;div&gt;The simple view model that I have created for the post back contains just one item, "Comment", from there I've created a form using the .NET Html Helpers:&lt;/div&gt;&lt;pre&gt;    &amp;lt;% Using Html.BeginForm() %&amp;gt;
        &amp;lt;%: Html.ValidationSummary(True) %&amp;gt;
    
        &amp;lt;fieldset&amp;gt;
            &amp;lt;legend&amp;gt;TestThrottleViewModel&amp;lt;/legend&amp;gt;
    
            &amp;lt;div class="editor-label"&amp;gt;
                &amp;lt;%: Html.LabelFor(Function(model) model.Comment) %&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class="editor-field"&amp;gt;
                &amp;lt;%: Html.EditorFor(Function(model) model.Comment) %&amp;gt;
                &amp;lt;%: Html.ValidationMessageFor(Function(model) model.Comment) %&amp;gt;
            &amp;lt;/div&amp;gt;
    
            &amp;lt;p&amp;gt;
                &amp;lt;input type="submit" value="Create" /&amp;gt;
            &amp;lt;/p&amp;gt;
        &amp;lt;/fieldset&amp;gt;
    &amp;lt;% End Using %&amp;gt;&lt;/pre&gt;&lt;div&gt;The first post back works fine, the second will result in the user being greeted with the error:&lt;/div&gt;&lt;div&gt;&lt;img src="http://jambr.blob.core.windows.net/articleimages/requsetthrottleexample.png"&gt;&lt;/div&gt;&lt;h3&gt;Conclusion&lt;/h3&gt;&lt;div&gt;I hope this simple tutorial has helped you to think a little about your site security, as well as how to utilise custom Action Filters to reuse code across your website.&lt;/div&gt;&lt;div&gt;As always, any questions please ask.&lt;/div&gt;&lt;/div&gt;</content:encoded></item><item><guid isPermaLink="false">0bb23f67-3447-47d6-a923-aa9c916b3834</guid><link>http://www.jambr.co.uk/Article/create-rss2-feed-syndication</link><category domain="http://www.jambr.co.uk/Article/?Tag=.NET">.NET</category><category domain="http://www.jambr.co.uk/Article/?Tag=RSS">RSS</category><title>Creating an RSS 2.0 feed with .NET Syndication Namespace</title><description>A .NET Programming Article including code showing how to create a compliant RSS 2.0 feed using .NET Syndication Namespaces</description><pubDate>Thu, 27 Dec 2012 22:20:15 Z</pubDate><dc:creator>Karl</dc:creator><content:encoded>&lt;h3&gt;Overview&lt;/h3&gt;In my &lt;a href="http://www.jambr.co.uk/Article/create-rss2-feed"&gt;Previous Post&lt;/a&gt;&amp;nbsp;I demonstrated how to create an RSS feed using an XML Document.&lt;div&gt;This got some attention as it was pointed out to me that I could achieve the same result using the .NET Syndication classes. &amp;nbsp;As a result I have created this programming article with an alternate version of the class, which does away with the XMLDocument manipulation and uses these Syndication classes.&lt;/div&gt;&lt;div&gt;As with any default namespaces and classes in the .NET framework, they expose a lot of things that I quite simply don't need for my simple &lt;a href="http://www.jambr.co.uk/News"&gt;News&lt;/a&gt;&amp;nbsp;or &lt;a href="http://www.jambr.co.uk/Article"&gt;Article&lt;/a&gt;&amp;nbsp;RSS feed, so I have wrapped them up as I did last time into a utility class, which enables you to quickly and easily create your feed.&lt;/div&gt;&lt;h3&gt;Using the code&lt;/h3&gt;&lt;div&gt;The code is available for download&amp;nbsp;&lt;a href="http://jambr.blob.core.windows.net/articledownloads/RSSFeedv2.vb"&gt;here&lt;/a&gt;, simply put it into your project and add a reference to yourprojectnamespace.Syndication. &amp;nbsp;Using the code is very simple, see this example:&lt;br&gt;&lt;/div&gt;
&lt;pre&gt;'Create your feed
Dim rssfeed As New RSSFeed("Your RSS Feed Title",
                           "The description of your feed",
                           "The URL to the feed",
                           "A unique identifier for your feed",
                           Now,
                           "en-GB")

'Add a category to the main channel
rssfeed.AddFeedCategory("CodeProject", "http://www.codeproject.com", "CodeProject")

'Add an item
dim item = rssfeed.AddItem("Item Title",
                           "Item Description",
                           "Item Body",
                           "Item URL",
                           "A unique identifier for your item",
                           Now,
                           "The author name")

'Add a category to the item
item.Categories.Add(New SyndicationCategory("CodeProject","http://www.codeproject.com","CodeProject"))

'Output the result
Return Content(rssfeed.ToString(rssfeed.OutputType.RSS2), "text/xml")&lt;/pre&gt;&lt;h3&gt;Notes&lt;/h3&gt;&lt;div&gt;Because we're now using the syndication provider, you can chose to output as RSS2 or Atom1 by changing the parameter in the ToString method.&lt;/div&gt;&lt;div&gt;This is utilising the helper class as previous to ensure the xml document is UTF8, the resultant XML passes the &lt;a href="http://validator.w3.org/appc/"&gt;RSS Feed Validator&lt;/a&gt;, and works perfectly with &lt;a href="http://www.codeproject.com/script/Articles/BlogFeed.aspx"&gt;Code Project&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;As usual, any questions please ask.&lt;/div&gt;</content:encoded></item><item><guid isPermaLink="false">693fc9ed-0afb-4087-a4b6-1ee1a57e390b</guid><link>http://www.jambr.co.uk/Article/create-rss2-feed</link><category domain="http://www.jambr.co.uk/Article/?Tag=.NET">.NET</category><category domain="http://www.jambr.co.uk/Article/?Tag=RSS">RSS</category><title>Creating an RSS 2.0 feed with .NET</title><description>A .NET Programming Article including code showing how to create a compliant RSS 2.0 feed using .NET XmlDocument</description><pubDate>Wed, 26 Dec 2012 14:28:34 Z</pubDate><dc:creator>Karl</dc:creator><content:encoded>&lt;h3&gt;Overview&lt;/h3&gt;Rather than post another article about setting up and using third party tools with .NET MVC, I thought I would take a slightly different approach this time and write a Programming with .NET article based on something I have had to do whilst creating Jambr.&lt;div&gt;I had the requirement to create an RSS feed for both the &lt;a href="http://www.jambr.co.uk/Article"&gt;Articles&lt;/a&gt;&amp;nbsp;and &lt;a href="http://www.jambr.co.uk/News"&gt;News&lt;/a&gt;&amp;nbsp;sections of the site so you lovely readers could subscribe to either of them, I haven't actually had to create RSS feeds before so had to do some digging to find the best route to go down. &amp;nbsp;I read numerous programming articles on line and compiled a simple class which enables me to create an RSS2.0 compliant feed, as seen &lt;a href="http://www.jambr.co.uk/Article/Subscribe"&gt;here&lt;/a&gt;.&lt;/div&gt;&lt;h3&gt;Using the code&lt;/h3&gt;&lt;div&gt;Rather than putting all 237 lines of code in here I have uploaded the class for you, you can &lt;a href="http://jambr.blob.core.windows.net/articledownloads/RSSFeed.vb"&gt;download it from here&lt;/a&gt;. &amp;nbsp;Just pop it into your project and use it like this:&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;Firstly you need to create an instance of the object (apologies if i'm teaching you to suck eggs!):&lt;br&gt;
&lt;pre&gt;Dim rssfeed As New RSSFeed()&lt;/pre&gt;
&lt;/li&gt;&lt;li&gt;Next, you need to create the channel. &amp;nbsp;RSS2.0 feeds can only have one channel so you're only able to call this method once&lt;br&gt;
&lt;pre class="brush: vb"&gt;rssfeed.CreateChannel("Jambr - News"
"Http://www.jambr.co.uk/News",
"Jambr News",
Now,
"en-GB")&lt;/pre&gt;&lt;/li&gt;&lt;li&gt;And now, you add your items. &amp;nbsp;Obviously you need to loop through the objects you want in your feed and add them, but we'll add just one example here:&lt;br&gt;
&lt;pre class="brush: vb"&gt;rssfeed.WriteRSSItem("This is an item",
"http://www.yoursite.com",
"Karl",
Now,
"This is the description",
Guid.NewGuid.ToString)&lt;/pre&gt;&lt;/li&gt;&lt;li&gt;Finally, after you've added your items you can return the string of the XML document. &amp;nbsp;I'm coding around .NET MVC 4 so as a result I return the XML document to the user like this:&lt;br&gt;
&lt;pre class="brush: vb"&gt;Return Content(rssfeed.ToString, "text/xml")
&lt;/pre&gt;
&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;It is worth noting that I &amp;nbsp;have included additional parameters on both the CreateChannel and WriteRSSItem methods which enables you to add Categories (in the context of Jambr, I Tag all articles to enable them to be categorised) and Content (which will be added to the content:encoded tag).&amp;nbsp;&lt;/div&gt;&lt;div&gt;To add category tags, pass them as an array of KeyValuePair(of String, String) objects. &amp;nbsp;&lt;/div&gt;&lt;div&gt;To add the content, pass it as a string.&amp;nbsp;&lt;/div&gt;&lt;div&gt;
&lt;pre class="brush: vb"&gt;rssfeed.WriteRSSItem("This is an item",
"http://www.yoursite.com",
"Karl",
Now,
"This is the description",
Guid.NewGuid.ToString,
"This is the full body of the post",
{New KeyValuePair(Of String, String)("Tag1", "/Articles/?Tag=Tag1")})&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;

&lt;h3&gt;A few issues I encountered&lt;/h3&gt;&lt;/div&gt;&lt;div&gt;There were a few issues I encountered whilst trying to ensure the feed was &lt;a href="http://feed2.w3.org/docs/rss2.html"&gt;RSS 2.0 compliant&lt;/a&gt;&amp;nbsp;which are sorted in this code,&amp;nbsp;for example:&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;Date Times needed to be in the correct format (Sat, 07 Sep 2002 9:42:31 GMT), luckily .ToString("r") on a datetime object handles that.&lt;br&gt;&lt;/li&gt;&lt;li&gt;Adding custom namespaces to the root rss element of the document, and then actually enabling me to write tags which reference that namespace. &amp;nbsp;for example &amp;lt;dc:creator&amp;gt; tags&lt;/li&gt;&lt;/ol&gt;&lt;div&gt;I hope that helps! &amp;nbsp;Any questions, please ask.&lt;/div&gt;&lt;/div&gt;</content:encoded></item><item><guid isPermaLink="false">f613c165-5ae6-4e82-a06c-55ab2c3fb4ec</guid><link>http://www.jambr.co.uk/Article/elmah-installation-and-setup</link><category domain="http://www.jambr.co.uk/Article/?Tag=.NET">.NET</category><category domain="http://www.jambr.co.uk/Article/?Tag=MVC">MVC</category><title>Elmah - Installation and Setup</title><description>This .NET Tutorial explains how to set up and configure ELMAH (Error Logging Modules and Handlers) in an .NET 4.5 MVC 4 application</description><pubDate>Mon, 24 Dec 2012 11:53:57 Z</pubDate><dc:creator>Karl</dc:creator><content:encoded>&lt;h3&gt;Overview&lt;/h3&gt;&lt;div&gt;As promised, here is my next article regarding another tool I find&amp;nbsp;completely&amp;nbsp;invaluable in my life as a developer, &lt;a href="https://code.google.com/p/elmah/"&gt;Elmah&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;Basically Elmah sites quietly on your site, logging any exceptions (Code based or Web Server, for example, 404) which occur to (in this example) a database. &amp;nbsp;It then provides a nice neat GUI front end to allow you to view the details of these errors, &lt;b&gt;including stack traces&lt;/b&gt;.&lt;/div&gt;&lt;div&gt;If you're anything like me, and are tired of conversations which go like this:&lt;/div&gt;&lt;div&gt;&lt;ul&gt;&lt;li&gt;User: "Karl, the website crashed earlier"&lt;/li&gt;&lt;li&gt;Karl: "Oh right, what were you doing"&lt;/li&gt;&lt;li&gt;User: "I don't remember, I was just on it, can you fix it please"&lt;/li&gt;&lt;li&gt;Karl: "Well I could do with reproducing it...&lt;/li&gt;&lt;/ul&gt;You will be happy Elmah exists!&lt;/div&gt;&lt;h3&gt;Installation&lt;/h3&gt;&lt;div&gt;Installation is easy, just follow these steps. &amp;nbsp;Remember, this guide is based around .NET 4.5 MVC 4 and the associated caveats, it may not be exactly what is required for your configuration but should be near as dammit.&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;Ok, so firstly, install the Elmah package from the Package Manager console in Visual Studio:&lt;br&gt;
&lt;pre&gt;Install-Package elmah&lt;/pre&gt;
We use the package manager as it will handle the installation of any dependencies, and also add the required sections to your web.config (well, almost).&lt;/li&gt;&lt;li&gt;Now open your web.config and find the &amp;lt;elmah&amp;gt; section. &amp;nbsp;You'll need to modify it to use SQL logging. &amp;nbsp;Make that section look something like this:&lt;br&gt;
&lt;pre&gt;&amp;lt;elmah&amp;gt;
    &amp;lt;errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="YourConnectionStringName" applicationName="YourWebsiteName" /&amp;gt;
    &amp;lt;security allowRemoteAccess="true" /&amp;gt;
&amp;lt;/elmah&amp;gt;
&lt;/pre&gt;
It's pretty self&amp;nbsp;explanatory, the connection string name must be a valid connection string from the &amp;lt;connectionStrings&amp;gt; section of your web.config, and the application name should be the name you want to log errors for this application against.&lt;/li&gt;&lt;li&gt;As you can see in point #2, I have set allowRemoteAccess to true, this is a personal preference, but if you do this you &lt;b&gt;must&lt;/b&gt;&amp;nbsp;secure it. &amp;nbsp;If you use forms authentication with roles this is simple to do, find the&amp;nbsp;&amp;lt;location path="elmah.axd"&amp;gt; element, and make it look something like this:&lt;br&gt;
&lt;pre&gt;&amp;lt;location path="elmah.axd"&amp;gt;
    &amp;lt;system.web&amp;gt;
      &amp;lt;httpHandlers&amp;gt;
        &amp;lt;add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" /&amp;gt;
      &amp;lt;/httpHandlers&amp;gt;
      &amp;lt;authorization&amp;gt;
        &amp;lt;allow roles="Admin"/&amp;gt;
        &amp;lt;deny users="*"/&amp;gt;
      &amp;lt;/authorization&amp;gt;
    &amp;lt;/system.web&amp;gt;
    &amp;lt;system.webServer&amp;gt;
      &amp;lt;handlers&amp;gt;
        &amp;lt;add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" /&amp;gt;
      &amp;lt;/handlers&amp;gt;
    &amp;lt;/system.webServer&amp;gt;
&amp;lt;/location&amp;gt;
&lt;/pre&gt;
You'll notice here I have added a constraint which means only users which are members of the Admin group will be able to view Elmah.axd
&lt;/li&gt;&lt;li&gt;The next section you need to modify is in your system.webServer section, you need to add runAllManagedModulesForAllRequests="true" to the modules section. &amp;nbsp;Without this, elmah will not log exceptions in .NET MVC, you will simply find there is nothing logging to your SQL server:&lt;br&gt;
&lt;pre&gt;&amp;lt;modules runAllManagedModulesForAllRequests="true"&amp;gt;
      &amp;lt;add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" /&amp;gt;
      &amp;lt;add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" /&amp;gt;
      &amp;lt;add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" /&amp;gt;
&amp;lt;/modules&amp;gt;
&lt;/pre&gt;
&lt;/li&gt;&lt;/ol&gt;&lt;h3&gt;Custom Errors&lt;/h3&gt;&lt;div&gt;When you use Elmah with Custom Errors redirects, you'll notice that nothing gets logged to elmah. &amp;nbsp;This is because the framework intercepts the error prior to elmah getting hold of it. &amp;nbsp;To get around this we need to add two global filters, the code for them is fairly, simple:&lt;/div&gt;&lt;div&gt;
&lt;pre&gt;Public Class ElmahHTTPErrorAttribute
    Inherits System.Web.Http.Filters.ExceptionFilterAttribute

    Public Overrides Sub OnException(actionExecutedContext As System.Web.Http.Filters.HttpActionExecutedContext)
        If actionExecutedContext.Exception IsNot Nothing Then
            Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception)
        End If
        MyBase.OnException(actionExecutedContext)
    End Sub
End Class

Public Class ElmahMVCErrorAttribute
    Implements IExceptionFilter

    Public Sub OnException(filterContext As ExceptionContext) Implements IExceptionFilter.OnException
        If filterContext.Exception IsNot Nothing Then
            Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception)
        End If
    End Sub
End Class
&lt;/pre&gt;
&lt;/div&gt;&lt;div&gt;And then you need to modify your FilterConfig.vb. &amp;nbsp;What we're doing here is creating a new section for HTTP filter attributes, which we will call from global.asax later:&lt;/div&gt;&lt;div&gt;
&lt;pre&gt;Public Class FilterConfig
    Public Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection)

        'Add elmah attribute
        filters.Add(New ElmahMVCErrorAttribute, 1)

        'Add the standing handle error attribute
        filters.Add(New HandleErrorAttribute(), 2)

    End Sub
    Public Shared Sub RegisterHTTPFilters(ByVal filters As System.Web.Http.Filters.HttpFilterCollection)

        'Add a http filter attribute
        filters.Add(New ElmahHTTPErrorAttribute)

    End Sub
End Class
&lt;/pre&gt;
Finally, update Application_Start in your Global.asax.vb to register the new filters:&lt;/div&gt;&lt;div&gt;
&lt;pre&gt;        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
        FilterConfig.RegisterHTTPFilters(GlobalConfiguration.Configuration.Filters)
&lt;/pre&gt;

And that's it, you're all configured and ready to go, if you go to http://yoursite.com/Elmah.axd, you should see a screen similar to the following:&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;img src="http://jambr.blob.core.windows.net/articleimages/elmah_example.png" alt="Elmah GUI Example"&gt;&lt;/div&gt;&lt;div&gt;You can drill down further, by clicking details, which will show you the stack trace if one is available.&lt;/div&gt;</content:encoded></item><item><guid isPermaLink="false">7939179d-c300-4fd0-b4c5-4d67f94fae1e</guid><link>http://www.jambr.co.uk/Article/miniprofiler-installation-and-setup</link><category domain="http://www.jambr.co.uk/Article/?Tag=.NET">.NET</category><category domain="http://www.jambr.co.uk/Article/?Tag=MVC">MVC</category><title>MiniProfiler - Installation and Setup</title><description>This .NET Tutorial will tell you how to Install and Configure MiniProfiler for .NET 4.5 MVC 4 Web Application including Entity Framework logging.</description><pubDate>Fri, 21 Dec 2012 13:35:38 Z</pubDate><dc:creator>Karl</dc:creator><content:encoded>&lt;h3&gt;Overview&lt;/h3&gt;&lt;p&gt;The primary reason I started this web site was to share with you the things I come across in my day job as a Web Developer, the first batch of articles I am going to write will be around the tools I find invaluable in my role.&lt;/p&gt;&lt;p&gt;So first and foremost, let’s take a look at &lt;a href="http://miniprofiler.com/" target="_blank"&gt;MiniProfiler&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;a href="http://miniprofiler.com/" target="_blank"&gt;MiniProfiler&lt;/a&gt; is a tool created and used by the &lt;a href="http://stackexchange.com/" target="_blank"&gt;StackExchange&lt;/a&gt; group of websites and is used for profiling your .NET and Ruby applications.&lt;/p&gt;&lt;p&gt;Whilst in your development environment you can use it to get an overlay on your page detailing the code execution of your Application. &amp;nbsp;For those of you that have ever tried to identify bottlenecks in your applications you can immediately see how useful this can be. &amp;nbsp; Take a look at this screenshot from the Jambr blog page.&lt;/p&gt;&lt;p&gt;&lt;img src="http://jambr.blob.core.windows.net/articleimages/miniprofiler_overlay.png" alt="MiniProfiler Overlay"&gt;&lt;/p&gt;&lt;p&gt;As you can see, the steps needed to render my page, and most importantly the SQL that was executed in the process are clearly detailed out here, you can even click on the query to view the detail, for example:&lt;/p&gt;&lt;p&gt;&lt;img src="http://jambr.blob.core.windows.net/articleimages/miniprofiler_sql.png" alt="MiniProfiler SQL Dump"&gt;&lt;/p&gt;&lt;p&gt;I’ll go into all of this a little more in later articles, but for now let’s look at setting up and configuring MiniProfiler against a .NET 4.5 MVC 4 Application which uses Entity Framework 5 for its database connections.&lt;/p&gt;&lt;h3&gt;Installation&lt;/h3&gt;&lt;p&gt;Installation is simple and is all done through the Package Manager Console integrated into Visual Studio.&amp;nbsp;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Open the Package Manager Console (Tools -&amp;gt; Library Package Manager -&amp;gt; Package Manager Console.&lt;/li&gt;&lt;li&gt;Type “Install-Package MiniProfiler” and press enter:&lt;br&gt;&lt;img src="http://jambr.blob.core.windows.net/articleimages/miniprofiler_packagemanager.png" alt="MiniProfiler Package Manager"&gt;&lt;/li&gt;&lt;li&gt;Package Manager will now download and install MiniProfiler and add the required references to your project.&lt;/li&gt;&lt;li&gt;As I mentioned previously, we’re going to be configuring MiniProfiler to profile our Entity Framework database context, in order to do so, we’ll also need the MiniProfiler.EF package, which is installed in exactly the same way, with &lt;br&gt;&lt;pre&gt;“Install-Package MiniProfiler.EF”&lt;/pre&gt;&lt;/li&gt;&lt;li&gt;Now open your Global.asax.vb file, at the top of your Sub Application_Start, add:&lt;br&gt;&lt;pre&gt;MiniProfilerEF.Initialize_EF42()&lt;/pre&gt;
This ensures that any connections created and used by Entity Framework are captured and logged into MiniProfiler like in my screenshot above.&lt;/li&gt;&lt;li&gt;In the same file, add the following to the top of your Application_BeginRequest:&amp;nbsp;&lt;br&gt;&lt;pre&gt;MiniProfiler.Start()&lt;/pre&gt;&lt;/li&gt;&lt;li&gt;And at the top of your Application_EndRequest:&amp;nbsp;&lt;br&gt;&lt;pre&gt;MiniProfiler.Stop()&lt;/pre&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;Almost done, I promise. &amp;nbsp;We now need to add a piece of code to the page you want to see the profiler on. &amp;nbsp;Personally I have this on my Base.Master, the parent master page for all others, that way it’s available on every page. &amp;nbsp;The code you need to add, in your &amp;lt;head&amp;gt; tag is:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;pre&gt;&amp;lt;%:MiniProfiler.RenderIncludes %&amp;gt;&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;You may need to add a reference to the namespace at the top of your page like so:&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;pre&gt;&amp;lt;%@ Import Namespace="StackExchange.Profiling" %&amp;gt;&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;And that’s it. &amp;nbsp;It’s worth noting that if MiniProfiler.Start() isn’t called, the .RenderIncludes function is smart enough not to clutter your browser with the JavaScript files that are required. &amp;nbsp;I personally wrap my .Start() in a Debugger.IsAttached statement, therefore I only show the profile in my local development environment.&lt;/p&gt;&lt;p&gt;Run your application and see what happens…&lt;/p&gt;&lt;p&gt;"Oh wait, Karl, you lied – it doesn’t work and I’m getting the following error when running MVC4"&lt;/p&gt;&lt;p style="text-align: center;"&gt;&lt;font color="#ff0000"&gt;Failed to load resource: the server responded with a status of 404 (Not Found) http://*/mini-profiler-resources/results&lt;/font&gt;&lt;/p&gt;&lt;p&gt;This article wouldn’t be interesting unless it solved at least one annoyance now, would it? &amp;nbsp;To fix the above error you need to add the following to your Web.Config&lt;/p&gt;
&lt;pre&gt;&amp;lt;system.webServer&amp;gt;
    &amp;lt;handlers&amp;gt;
        &amp;lt;add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;This sorts out the routing issue which appeared in MVC4. &amp;nbsp;Now try again, and you’ll be sorted!&lt;/p&gt;&lt;h3&gt;Summary&lt;/h3&gt;&lt;p&gt;MiniProfiler is a very powerful tool, I will go into the more advanced features of it in a later Article.&amp;nbsp;&lt;/p&gt;</content:encoded></item></channel></rss>