Sunday, August 17, 2008

ASP.NET MVC Framework Controller Action Security

Introduction:

ASP.NET MVC Framework allows the developers to build their web application in a more flexible way. Using MVC framework you by passes the headaches of ViewState and Postbacks and also enable your application for testing. In this article we are going to take a look at the Controller Action Role-Based Security.

Prerequisite:

If this is your first encounter with ASP.NET MVC Framework then I strongly suggest that you check out the introductory article using the link below:

Getting Started with the ASP.NET MVC Framework

Scenario:

The scenario is really simple. A list of categories is displayed on the page and when the user clicks on the category it will be deleted. But we need to make sure that the user is authorized to delete the items.

Populating the Page with List of Categories:

The first task is to populate the page with a list of categories. Let’s see how this can be implemented.

[ControllerAction]
public void List()
{
NorthwindDataContext northwind = new NorthwindDataContext();
var list = northwind.Categories;
RenderView("Categories", list);
}

The List action is responsible for populating the Categories view with the required data. Let’s check out the Categories view.

public partial class Categories : ViewPage>
{

}

<% foreach (var category in ViewData) { %>

<%= Html.ActionLink(c => c.Delete(category.id),
category.CategoryName, new { onclick = "return confirmDelete(" + category.id + ")" })%>



<%} %>

The first thing to note is the Categories class inherits from the ViewPage which is of IEnumerable type. This means that we will have the strong type support for IEnumerable in the HTML view of the page. Now, let’s discuss the HTML part of the Categories view.

The foreach loop is used to iterate through the categories. The Html.ActionLink method is used to create hyperlinks which are directed to particular controllers. The first argument to the Html.ActionLink is the Linq expression for the action. The argument c => c.Delete(category.id) means that we are attaching the Delete action to all the categories in the ViewData object. The Delete operation will take a single parameter which is categoryId. The next parameter is the text to appear for the hyperlink. The final parameter is the HTML attributes. We are using onclick attribute of the hyperlink which will popup a confirmation box.

The HTML generated for the page might look something like this:



<a href="/Category/Delete/1" onclick="return confirmDelete(1)" >Beverages Edite</a>
<br />

<a href="/Category/Delete/2" onclick="return confirmDelete(2)" >Condiments</a>
<br />

<a href="/Category/Delete/3" onclick="return confirmDelete(3)" >Confections</a>
<br />

<a href="/Category/Delete/4" onclick="return confirmDelete(4)" >Dairy Products</a>
<br />




Now, looking at the URL’s above anyone can easily delete the item by simply copying the URL in the address bar. So, the question is how do we secure the controller actions so only authorized users would be able to delete the items.

Controller Action Security:

ASP.NET MVC Framework is still in its development phases and there is still a lot on the wish list. Maybe in few months the framework will provide us the flexibility to configure action based security easily.

For now let’s use another approach to add security to our controller actions. The OnPreAction event is fired before the action is executed and this seems to be an ideal place to authorize the user. You can override the OnPreAction of the controller class but this solution is not scalable since then you will need to override all the controllers for security purposes. A better approach is to introduce a BaseController and override the OnPreAction of the BaseController. All the controllers will derive from the BaseController class instead of the Controller class. And the BaseController will derive from the Controller class.

protected override bool OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo)
{
string controllerName = methodInfo.DeclaringType.Name;

if(!IsAuthorized(controllerName,actionName)) throw new SecurityException("not authenticated");

return base.OnPreAction(actionName, methodInfo);
}

The IsAuthorized custom method is responsible for performing the actual authorization.

private bool IsAuthorized (string controllerName, string actionName)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;

XDocument xDoc = null;

if (context.Cache["ControllerActionsSecurity"] == null)
{
xDoc = XDocument.Load(context.Server.MapPath("~/ControllerActionsSecurity.xml"));
context.Cache.Insert("ControllerActionsSecurity",xDoc);
}

xDoc = (XDocument) context.Cache["ControllerActionsSecurity"];
IEnumerable elements = xDoc.Element("ControllerSecurity").Elements();

var role = (from e in elements
where ((string)e.Attribute("controllerName")) == controllerName
&& ((string)e.Attribute("actionName")) == actionName
select new { RoleName = e.Attribute("Roles").Value }).SingleOrDefault();

if (role == null) return true;

if (!User.IsInRole(role.RoleName))
return false;


return true;
}

Nothing too complicated! The authorization details are stored in an XML file called ControllerActionsSecurity.xml. Here are the contents of the file:



controllerName: The name of the controller
actionName: The action of the controller
Roles: Authorized roles

If you need to add authorization to a different controller then simply make an entry in the XML file with the appropriate controllerName and the actionName.

Conclusion:

In this article we learned how to authorize the user based on the controller and the action. Hopefully, ASP.NET team will introduce more flexible ways to authorize the users based on their actions.

I hope you liked the article happy coding!

[Download]

Monday, August 11, 2008

Tip/Trick: Optimizing ASP.NET 2.0 Web Project Build Performance with VS 2005

This posts covers how to best optimize the build performance with Visual Studio 2005 when using web projects. If you are experiencing slow builds or want to learn how to speed them up please read on.

Quick Background on VS 2005 Web Site Project and VS 2005 Web Application Project options

VS 2005 supports two project-model options: VS 2005 Web Site Projects and VS 2005 Web Application Projects.

VS 2005 Web Site Projects were built-in with the initial VS 2005 release, and provide a project-less based model for doing web development that uses that same dynamic compilation system that ASP.NET 2.0 uses at runtime. VS 2005 Web Application Projects were released as a fully supported download earlier this spring, and provide a project model that uses a MSBuild based build system that compiles all code in a project into a single assembly (similar to VS 2003 -- but without many of the limitations that VS 2003 web projects had with regard to FrontPage Server Extensions, IIS dependencies, and other issues). To learn more about VS 2005 Web Application Projects, please review the tutorials I've published on my http://webproject.scottgu.com web-site. Note that VS 2005 Web Application Project support will be included in VS 2005 SP1 (so no additional download will be required going forward).

Both the VS 2005 Web Site Project option and the VS 2005 Web Application Project option will continue to be fully supported going forward with future Visual Studio releases. What we've found is that some people love one option, while disliking the other, and vice-versa. From a feature perspective there is no "one best option" to use - it really depends on your personal preferences and team dynamics as to which will work best for you. For example: a lot of enterprise developers love the VS 2005 Web Application option because it provides a lot more build control and team integration support, while a lot of web developers love the VS 2005 Web Site model because of its "just hit save" dynamic model and flexibility.

Two articles you might find useful to decide which works best for you is this MSDN whitepaper that includes some comparisons between the two models, and Rick Strahl's Web Application Projects and Web Deployment Projects are Here article that provides a good discussion of the pros/cons of the different options.

To migrate from the VS 2005 Web Site Project model to the VS 2005 Web Application Project model, please follow this C# or VB tutorial that walks-through the steps for how to-do so.

So Which Project Option Builds Faster?

When doing full builds of projects, the VS 2005 Web Application Project option will compile projects much faster that the VS 2005 Web Site Project option. By "full build" I mean cases where every class and page in a project is being compiled and re-built - either because you selected a "Rebuild" option within your "build" menu, or because you modified code within a dependent class library project or in the /app_code directory and then hit "build" or "ctrl-shift-b" to compile the solution.

There are a few reasons why the VS 2005 Web Application Project ends up being significantly faster than Web Site Projects in these "full rebuild" scenarios. The main reason is that (like VS 2003), the VS 2005 Web Application Project option only compiles your page's code-behind code and other classes within your project. It does not analyze or compile the content/controls/in-line code within your .aspx pages -- which means it does not need to parse those files. On the downside this means that during compilation it will not check for errors in those files (unlike the VS 2005 Web Site Project option which will identify any errors there). On the positive side it makes compilations much faster.

So does this mean that you should always use the VS 2005 Web Application Project option to get the fastest build times with large projects? No -- not necessarily. One nice feature that you can enable with the VS 2005 Web Site Project option is support for doing "on demand compilation". This avoids you having to always re-build an entire project when dependent changes are made -- instead you can just re-build those pages you are working on and do it on-demand. This will lead to significant build performance improvements for your solution, and can give you a very nice workflow when working on very large projects. I would definitely recommend using this option if you want to improve your build performance, while retaining the flexibility of the web-site model.

The below sections provide specific tutorials for both the VS 2005 Web Site Project Model and the VS 2005 Web Application Project Model on optimization techniques -- including the "on demand compilation" build option I described above.

Specific Tips/Tricks for Optimizing VS 2005 Web Site Project Build Times

When using the VS 2005 Web Site Project model, you can significantly improve build performance times by following these steps:

1) Verify that you are not suffering from an issue I call "Dueling Assembly References". I describe how to both detect and fix this condition in this blog post. If you are ever doing a build and see the compilation appear to pause in the "Validating Web Site" phase of compilation (meaning no output occurs in the output window for more than a few seconds), then it is likely that you are running into this problem. Use the techniques outlined in this blog post to fix it.

2) Keep the number of files in your /app_code directory small. If you end up having a lot of class files within this directory, I'd recommend you instead add a separate class library project to your VS solution and move these classes within that instead since class library projects compile faster than compiling classes in the /app_code directory. This isn't usually an issue if you just have a small number of files in /app_code, but if you have lots of directories or dozens of files you will be able to get speed improvements by moving these files into a separate class library project and then reference that project from your web-site instead. One other thing to be aware of is that whenever you switch from source to design-view within the VS HTML designer, the designer causes the /app_code directory to be compiled before the designer surface loads. The reason for this is so that you can host controls defined within /app_code in the designer. If you don't have an /app_code directory, or only have a few files defined within it, the page designer will be able to load much quicker (since it doesn't need to perform a big compilation first).

3) Enable the on-demand compilation option for your web-site projects. To enable this, right-click on your web-site project and pull up the project properties page. Click the "Build" tab on the left to pull up its build settings. Within the "Build" tab settings page change the F5 Start Action from "Build Web Site" to either the "Build Page" or "No Build" option. Then make sure to uncheck the "Build Web site as part of solution" checkbox:

When you click ok to accept these changes you will be running in an on-demand compilation mode. What this means (when you select the "Build Page" option in the dialog above) is that when you edit a page and then hit F5 (run with debugging) or Ctrl-F5 (run without debugging) the solution will compile all of the class library projects like before, then compile the /app_code directory and Global.asax file, and then instead of re-verifying all pages within the web-site it will only verify the current page you are working on, and any user controls that the page references. With large (and even medium) projects with lots of pages, this can obviously lead to major performance wins. Note that ASP.NET will automatically re-compile any other page or control you access at runtime -- so you will always have an up-to-date and current running application (you don't need to worry about old code running). You can optionally also use the "No Build" option to by-pass page-level validation in the IDE, which obviously speeds up the entire process much further (I'd recommend giving both options a try to see which you prefer).

By deselecting the "Build Web site as part of solution" checkbox, you will find that the Ctrl-Shift-B keystroke (which builds the solution) will continue compiling all class library projects, but will not re-build all pages within your web-site project. You will still get full intellisense support in your pages in this scenario - so you won't lose any design-time support. You will also continue to get warning/error squiggles in code/class when they are open. If you want a way to force a re-build to occur on pages not open, or across all pages within the web-site, you can use the "Build Page" or "Build Web Site" menu options within the "Build" menu of Visual Studio:

This gives you control as to which pages on your site you want to verify (and when) - and can significantly improve build performance. One trick I recommend doing is adding a new shortcut keystroke to your environment to allow you to quickly short-cut the "Build Page" menu option to avoid you having to ever use a mouse/menu for this. You can do this by selecting the Tools->Customize menu item, and then click the "Keyboards" button on the bottom-left of the customize dialog. This will bring up a dialog box that allows you to select the VS Build.BuildPage command and associate it within any keystroke you want:

Once you do this, you can type "Ctrl-Shift-P" (or any other keystroke you set) on any page to cause VS to compile any modified class library project (effectively the same thing that Ctrl-Shift-B does), then verify all classes within the /app_code directory, and then re-build just the page or user control (and any referenced master pages or user controls it uses) that you are working on within the project.

Once the above steps are applied, you should find that your build performance and flexibility is much improved - and that you have complete control over builds happen.

Specific Tips/Tricks for Optimizing VS 2005 Web Application Project Build Times

If you are using the VS 2005 Web Application project option, here are a few optimizations you might want to consider:

1) If you have a very large project, or are working on an application with many other developers, you might want to consider splitting it up into multiple "sub-web" projects. I wouldn't necessarily recommend this for performance reasons (unless you have thousands and thousands of pages it probably doesn't make a huge difference), but it can sometimes make it easier to help manage a large project. Please read this past blog-post of mine on creating sub-web projects to learn how to use this.

2) Consider adding a VS 2005 Web Deployment project to your solution for deep verification. I mentioned above that one downside of using the VS 2005 Web Application Project option was that it only compiled the code-behind source code of your pages, and didn't do a deeper verification of the actual .aspx markup (so it will miss cases where you have a mis-typed tag in your .aspx markup). This provides the same level of verification support that VS 2003 provided (so you aren't loosing anything from that), but not as deep as the Web Site Project option. One way you can still get this level of verification with VS 2005 Web Application Projects is to optionally add a VS 2005 Web Deployment Project into your solution (web deployment projects work with both web-site and web-application solutions). You can configure this to run only when building "release" or "staging" builds of your solution (to avoid taking a build hit at development time), and use it to provide a deep verification of both your content and source code prior to shipping your app.

Common Tips/Tricks for Optimizing any VS 2005 Build Time

Here are a few things I recommend checking anytime you have poor performance when building projects/solutions (note: this list will continue to grow as I hear new ones - so check back in the future):

1) Watch out for Virus Checkers, Spy-Bots, and Search/Indexing Tools

VS hits the file-system a lot, and obviously needs to reparse any file within a project that has changed the next time it compiles. One issue I've seen reported several times are cases where virus scanners, spy-bot detecters, and/or desktop search indexing tools end up monitoring a directory containing a project a little too closely, and continually change the timestamps of these files (they don't alter the contents of the file - but they do change a last touched timestamp that VS also uses). This then causes a pattern of: you make a change, rebuild, and then in the background the virus/search tool goes in and re-searches/re-checks the file and marks it as altered - which then causes VS to have to re-build it again. Check for this if you are seeing build performance issues, and consider disabling the directories you are working on from being scanned by other programs. I've also seen reports of certain Spybot utilities causing extreme slowness with VS debugging - so you might want to verify that you aren't having issues with those either.

2) Turn off AutoToolboxPopulate in the Windows Forms Designer Options

There is an option in VS 2005 that will cause VS to automatically populate the toolbox with any controls you compile as part of your solution. This is a useful feature when developing controls since it updates them when you build, but I've seen a few reports from people who find that it can cause VS to end up taking a long time (almost like a hang) in some circumstances. Note that this applies both to Windows Forms and Web Projects. To disable this option, select the Tools->Options menu item, and then unselect the Windows Forms Designer/General/AutoToolboxPopulate checkbox option (for a thread on this see: http://forums.asp.net/1108115/ShowPost.aspx).

3) Examine which 3rd party packages are running in Visual Studio

There are a lot of great 3rd party VS packages that you can plug into Visual Studio. These deliver big productivity wins, and offer tons of features. Occasionally I've seen issues where performance or stability is being affected by them though. This is often true in cases where an older version (or beta) of one of these packages is being used (always keep an eye out for when a manufacturer updates them with bug-fixes). If you are seeing issues with performance or stability, you might want to look at trying a VS configuration where you uninstall any additional packages to see if this makes a difference. If so, you can work with the 3rd party manufacturer to identify the issue.

Visual Basic Build Performance HotFix

The Visual Basic team has released several hotfixes for compilation performance issues with large VB projects. You can learn how to obtain these hotfixes immediately from this blog post. The VB team also has a direct email address -- vbperf@microsoft.com -- that you can use to contact them directly if you are running into performance issues.

Friday, August 8, 2008

Two New Updates to Google Image Search

Google announced two new updates to Google Image Search that further help users find the information they need.

First, Google Image Search now includes more than 1.1 billion images from around the world (previously: 800 millions). With a comprehensive index of images, users can quickly and easily find relevant images of both popular and obscure queries.






In addition, Google released a new feature that displays images from Google Image Search above Google web search results when they're relevant to users' search queries. When users search for queries such as sunsets, mountains, torre eiffel, or inverno on the Google homepage, they may see relevant thumbnail images at the top of their search results marked "Image Results." When users click on the thumbnail images, they will be directed to the website that contains the original image. Users may also click on the "Image Results" link to see the complete Google Image Search results page for that query.

This new feature may only work for users in the USA (it doesn't work for now in France).