Professional Programmer Notes

or just call this my soapbox

Archive for the ‘Uncategorized’ Category

Two ways to handle unauthorized requests to Ajax actions in ASP.NET MVC 2

leave a comment »

Problem:  I have created a view that posts to an action via Ajax with the expectation that the action will return the requested data or an empty string.  Even better, I would like it to be configurable to return whatever value I see fit.

The problem arises when I decorate the called action with the [Authorize] attribute.  If the request is not authorized and I have a loginUrl configured in my web.config, my ajax request will return the html output of my loginUrl view.  That is undesirable.

Solution #1:  I need to implement a custom ActionFilterAttribute that I can use on the ajax action to handle the request appropriately.  Here is the code for my ActionFilterAttribute:

    public class AjaxAuthorizeAttribute : ActionFilterAttribute
    {
        public string View { get; set; }
        private bool renderView;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAuthenticated && filterContext.HttpContext.Request.IsAjaxRequest())
            {
                renderView = true;
            }

            base.OnActionExecuting(filterContext);
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (renderView)
            {
                filterContext.Result = new ViewResult { ViewName = View };
                filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
                return;
            }

            base.OnResultExecuting(filterContext);
        }
    }

And, here is how I would decorate my ajax action in my controller class:

	[AjaxAuthorize(View="AjaxAuthorizeError")]
public ActionResult AjaxRequest()
{
        return View();
}

That would handle the issue by checking whether the request is authenticated.  If it isn’t authenticated and the request is being submitted via ajax, a specified view will get called.  The content of that view determines what my ajax call will receive back when the request is not authenticated.

Note:  There is no default view page being rendered if one is not passed to the ActionFilterAttribute.  That’s room for improvement.

Solution #2:  I can extend the existing Authorize attribute by inheriting from the AuthorizeAttribute class.  Here is the code that extends the Authorize attribute:

    public class AjaxAuthorizeOverrideAttribute : AuthorizeAttribute
    {
        public string View { get; set; }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAjaxRequest())
            {
                base.HandleUnauthorizedRequest(filterContext);
                return;
            }

            filterContext.Result = new ViewResult { ViewName = View };
            filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
        }
    }

Here is the decorator for the ajax action in the controller class:

[AjaxAuthorizeOverride(View="AjaxAuthorizeError")]
public ActionResult AjaxRequest()
{
     return View();
}

Note:  Again, there is no default view page being rendered.

Advertisements

Written by curtismitchell

March 22, 2010 at 4:10 pm

Posted in Uncategorized

Changing the default Virtual Directory/[TARGETVDIR] name in a Visual Studio Setup Project

with 2 comments

While working on a Visual Studio Setup Project for an ASP.NET MVC application, I ran into an interesting dilemma. The installer automatically uses the Title of your setup project as the default virtual directory value. From a user experience standpoint, it can serve as a visual indicator that this "virtual directory" is specifically for the application that you (the user) are installing.

However, it isn’t ideal. See, usually the title of an installer is human readable e.g. "My Application". However, I don’t think user would want their virtual directory to contain spaces since spaces typically get escaped to a hex value, making your site’s address http://someserver/My%20Application. Visual Studio Setup Projects do not offer a straight-forward way of editing this default value, except to edit your title to read "MyApplication".

There are a handful of solutions that have been conceived by various people that include passing command line arguments or using custom dialog windows that set the TARGETVDIR parameter explicitly – to name a couple.

For different reasons, none of the proposed solutions satisfied my dilemma.

So, here is what I did:

I opened the deployment project in notepad++ (a very handy text editor), found the line that says, "VirtualDirectory" = "My Application" and changed it to "VirtualDirectory" = "MyApplication". After saving the file, reloading it in Visual Studio, and building my installers, my dilemma was solved. I hope this is helpful to you as well.

Written by curtismitchell

February 19, 2010 at 12:14 pm

Posted in Uncategorized

Slides from Raleigh Code Camp 2009

leave a comment »

This weekend, I had the pleasure of presenting a talk on Spark View Engine at Raleigh Code Camp (#rducc).  It was a well organized event with a schedule full of great topics and presenters.  The Triangle .NET User Group (TriNUG) did a wonderful job at organizing and running the event.  Thanks, TriNUG!

As promised, I am posting the slides that I used in the Spark talk.  Although the true context of the talk is not present on the slides, I hope these are helpful to someone using the Spark View Engine or considering it.

Stay tuned, or subscribe to the rss. I am planning to post a series of short to-the-point screencasts that demonstrate how to practically use Spark in your ASP.NET MVC application.

In the meantime, checkout http://www.dimecasts.net for some great videos on Spark.

Written by curtismitchell

September 21, 2009 at 10:01 am

Hello world!

with one comment

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

Written by curtismitchell

May 16, 2009 at 5:37 pm

Posted in Uncategorized

Ruby-like Times method for Ints in C#

leave a comment »

Yesterday, @mccartsc did a presentation on Linq for a group of us at work. As part of his presentation, he demonstrated an extension method he threw together to give .NET Integers the Times method that Ruby programmers have enjoyed for years.

Basically, the n.Times methods is passed a block that it will execute n number of times. In Ruby, you could do something like this:

5.times {|x| puts x }

That trivial line of code would output integers 0 through 4.

With such a trivial use case, you may be wondering “Why would anyone want to do that?” Well, @mccartsc and I had a discussion about coding without traditional For Loops. Foreach Loops are great for enumerating IEnumerable objects, but it is not a replacement for the traditional For Loop. We thought, “Wouldn’t it be great if you could use a Ruby-like Time method to execute a block of code an arbitrary number of times?” So, @mccartsc built it as part of his Linq demonstration.

Here’s how he did it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqDemo
{
    static class Extensions
    {
        public static void Each<T>(this IEnumerable<T> collection, Action<T> action)
        {
            foreach (var item in collection)
                action(item);
        }

        public static IEnumerable<int> Range(this int max)
        {
            for (int i = 0; i < max; i++)
                yield return i;
        }

        public static void Times(this int i, Action<int> action)
        {
            i.Range().Each(action);
        }
    }
}

@mccartsc created three extension methods to implement the Times method. “Each” is an extension method for IEnumerable types. It passes each member of a collection into an Action delegate.

“Range” is an extension method for Int types. It creates a zero-based IEnumerable collection out of an integer. For instance, 5.Range();, would return a collection consisting of integers 0,1,2,3,4.

Finally, “Times” is another extension method for Int types that allows a user to execute an action an arbitrary number of times by using the aforementioned Range and Each methods. Once I have these extension methods in my C# project, I can execute code like this:

5.Times(i => Console.WriteLine(i.ToString()));

The above would output:
0
1
2
3
4

I think that’s pretty cool.
Thanks @mccartsc for the code and the demonstration.

Update: @mccartsc got a blog! Check him out at http://scmccart.wordpress.com/.

Written by curtismitchell

May 1, 2009 at 9:13 pm

Posted in Uncategorized

Tagged with , ,

BarCampRDU 2008

with one comment

I had the pleasure of attending BarCampRDU yesterday; that is BarCamp in the Raleigh/Durham N.C. region. On the BarCamp wiki, the event is described as “an ad-hoc gathering born from the desire for people to share and learn in an open environment. It is an intense event with discussions, demos and interaction from participants.”

Opening BarCampRDU 2008

Yup, that is correct.  The attendees decide on what to discuss.  There are no formal presenters, only facilitators to lead the discussions.  Once the topics have been determined, a schedule is posted and individuals decide for themselves which topics to attend.

I attended the following discussions:

  1. How to sell free software
  2. Twitter, Patterns and Anti-Patterns
  3. Fan Programming Language
  4. Bootstrapping a business in the RTP area
  5. Git

I am still gathering my thoughts on some of the discussions.  I will add links to my posts about the topics as I deem necessary.

Overall, the event was very well done.  The organizers and the sponsors took great care of us and I hope to be in attendance at the next BarCampRDU.

Written by curtismitchell

August 3, 2008 at 4:12 pm