Attribute Routing In MVC

26. August 2012 14:33

ASP.NET ASP.NET MVC Web 

I took a look at Stack Overflow Stack-Exchange Data Explorer that is built in MVC and is open-source application to query the Stack Exchange data dump that is being provided by Stack Exchange team in every month or few. I do have a dump, but I was more curious to know about the application that they built to query the database. And I must admit that I learned tons of things. I came to know the power of Micro-ORM (Dapper) over Entity-Framework (EF) and one more pretty thing that attracted me was the routing mechanism used in the application. I strongly recommend that you check out this tool/application and take a deep dive in the code, lot of things to learn.

Before we start writing the code, we'll take a quick look at a NuGet package AttributeRouting. You can find the source code at GitHub in case if you are interested. The documentation is simple and explains almost every bit of the package. It's incredibly easy.

The NuGet package I am using is for MVC, if you want to do the same with your Web API application then use this package.

To see how easy it is to implement routing in your MVC application. Start Visual Studio and create a new MVC4 (Internet) application and fire up the below NuGet command.

This command just don't install one single package but also some other dependent packages. Here is the output when I fire the above NuGet command:

PM> Install-Package AttributeRouting
Attempting to resolve dependency 'AttributeRouting.Core (≥ 2.5.1.0)'.
Attempting to resolve dependency 'AttributeRouting.Core.Web (≥ 2.5.1.0)'.
Attempting to resolve dependency 'WebActivator (≥ 1.0.0.0)'.
Successfully installed 'AttributeRouting.Core 2.5.1.0'.
Successfully installed 'AttributeRouting.Core.Web 2.5.1.0'.
Successfully installed 'WebActivator 1.0.0.0'.
Successfully installed 'AttributeRouting 2.5.1.0'.
Successfully added 'AttributeRouting.Core 2.5.1.0' to MVCAttrRouteTest.
Successfully added 'AttributeRouting.Core.Web 2.5.1.0' to MVCAttrRouteTest.
Successfully added 'WebActivator 1.0.0.0' to MVCAttrRouteTest.
Successfully added 'AttributeRouting 2.5.1.0' to MVCAttrRouteTest.

Now before you make any changes to the web application, hit CTRL+F5. Hover or click on the links which are on the top which are About and Contact. The URL rendered in the address bar is something like this (as what specified in your application Global.asax file).

For About View:

/Home/About

For Contact View:

/Home/Contact

The Home that we see here is the name of the controller being used. I don't want the name of the controller to be visible to my site visitors or maybe I just want a different name there. Usually, I would have switch to my application Global.asax file and register a new route there. But now I can now control my routes within controller itself. This is pretty cool for and a time saver, as I do not have to avoid working with Global.asax. This is the simplest implementation of AttributeRouting. Below are the 2 Home controller methods About and Contact:

[GET("About")]
public ActionResult About()
{
    ViewBag.Message = "Your app description page.";
    return View();
}

[GET("Contact")]
public ActionResult Contact()
{
    ViewBag.Message = "Your contact page.";
    return View();
}

There are no changes in the method, only the routing attribute has been added. The URLs for About and Contact are now free from the controller name Home. Now we look at a second condition where I want to have a totally different URL for About view or to be specific I would say I want to have outbound URLs and this will require RouteName property with the routing attribute. This is called Named Routes. I am going to change the URL to /App/AboutMe.

[GET("App/AboutMe", RouteName = "About")]
public ActionResult About()
{
    ViewBag.Message = "Your app description page.";
    return View();
}

Working with parameters without routing can lead to very ugly URLs or some un-wanted params in the URLs. Again to have a clean URL we can handle the parameters passed to the controller action. I have added a new view named Welcome (no scaffolding) in the Home controller and added a ViewBag property GreetMessage. When this view is called, it will display a greeting message in a heading. The GreetMessage will hold the name of the person, which is our parameter. Below is our controller action:

[GET("App/Greet/{name}")]
public ActionResult Welcome(string Name)
{
    ViewBag.GreetMessage = "Welcome " + Name;
    return View();
}

The URL that is rendered on the browser is:

http://domain.com/App/Greet/Prashant

/App/Greet/ is the URL we want to show and Prashant is the parameter is being passed to the Welcome view.

This is it for this tutorial but this is not it. The AttributeRouting package has to offer a lot of things and has a very powerful and easy way of routing. There are very advance topics that are documented at GitHub.

Related Links:

 No Rating

MP3APP - A Web Application To Get Lyrics, Album Name, Album Art and More

29. June 2012 20:53

ASP.NET MVC Utils Web 

I was busy in few of my freelance projects and got a very rough weekends this whole month. But still I get a bit of time to work on my so called in-house project and somehow I was able to get it completed after a bit of testing. The application I built is a simple web application which will allow you to enter artist name and the song name and let you search the lyrics, album art, artist image, album name and album release date. I hope this application help few people out there.

Now, something about the internals and history of the application. I created a windows application 2 years back and thought of porting the same application for the web. For the, web I used ASP.NET MVC 3 with jQuery but the internals of the application remains the same as it was for my windows app. To fetch the lyrics I use LyrDB and WikiLyrics web services and for album art, album name, artist image etc. I used Last.FM web service. I package the whole stuff and what I got is the application which I was running since 2 years on my machine and now the same application is out for you, use it and suggest me something new if you anything in your minds.

I am not yet finished with this application and you'll see more in coming days.

Try out the application here: http://mp3app.midnightprogrammer.net

 No Rating

Top 3 Ultimate Timepass For Developers

23. April 2012 13:55

Fundoo Web 

We have been programming a lot so we need some time to refresh our minds and get ourselves in a state where our mind processors can start working again more beautifully. When I am pushing myself hard I play 3 games that is on my favorite list. Though I do have many games but these are the 3 games that I play.

The World's Largest Pac-Mac

The legendry dot-eating games Pac-Man. I first played this game on 8-bit Atari console and I remember I used to bet with my firends. We played Pac-Man on a single maze, we don't have many options, but here we have lots and lots of mazes to choose from. The statistics is a section 

Angry Birds

One of the most playable and most addicted games at the moment available on the web. Amazing stages and awesome game play. I have spent numerous amount of effort and time on this game. I have played the offline version of this game, if you don't want to install then play it right here.

Cut The Rope

This game is more or like Angry Birds. Why? If you have played Angry Birds then you must have noticed that in Angry Birds it is not just about hitting the pillars. It's about how you kill the pigs by consuming fewer birds. Cut The Rope is the game initially written in Objective-C and later written in JavaScript by the awesome developers at Zepto Labs. I love playing this game as it allows you think before you make the move.

Currently rated 2.3 by 3 people

Awesome jQuery Image Plugins For Web Developers

22. April 2012 03:42

Jquery Web 

I am not a web developer but still I love working with jQuery, CSS3, HTML5 and other web development frameworks. But as a programmer I love collect code snippets for my ease and store them on the cloud so I can get the access when I am in need and want to save my time while I am writing code. Out of the box I have a list of few image manipulation plugins which seems pretty impressive to me. Let's take a look:

1. Image Carousels

For simple image carousels you can use rcarousel. The plugin is good if you are planning to implement a simple image carousel. If you are looking for some CSS3 taste then take a look at slideshow using jmpress. The transitions effects are awesome.

2. Adipoli jQuery Image Hover Plugin

This is the best image hover plugin I used and available on the web so far. The plugin has to offer you some amazing effects. My favorite is the greyscale and popout, both effects are good if you plan to have a web based gallery.

3. Captify

If you are looking to have a caption for your images, then do that in style. Captify is a plugin let you have pretty image captions for the image. You can have the caption on the image by default or you can show it to the user on mouseover. You can take a look at a little demo here and download it from the GitHub

4. Spritely.net

Want to work with sprites but don't know how to kick off? Don't wait and go to Spritely. Before you download check the gallery examples. In short Spritely allows you to turn your images into a movie. Simply awesome!!

5. jParallax

I will be surprised if you have not heard about this plugin. One of the most amazing and powerful plugin or I should say a library that can make your images speak or work on their own. I am not going to describe what it does, so you have to go and look for yourself. Visit the demo page.

 No Rating

Minify Your CSS & Javascript With SquishIt

15. April 2012 06:38

API ASP.NET Web 

No one likes if their favourite site is loading up slow. Using CSS sprites instead of using individual images and minify javascript and css files is a way to minimize the request send to the server and also saves you few KBs or may be even MBs. If your site is high on using javacript and CSS then you should minimize them.

I recently used SquishIt to combine/minimize my CSS and javascript files. I found 2 major benefits, first, I am able to combine all of my CSS files into one and minimize it, and second it reduces the request sent to the server to load several .css and .js files. In a typical web application I can have one style sheet and one javascript or jQuery file, but if I am planning to use some plugins then there might be more than one style sheet and javascript files which will get loaded on every page request. Here is an example of a sample web forms application loading two css and javascript files which includes the plugin code. 

Here you can see that there are 4 requests in total to load site CSS and Javascript files. Though in this case the size of the file is less but when you have really large files then it can really affect your site performance and also save MBs in a long run. So, what happens when I use SquishIt? Install the package by firing the below command at NuGet console.

 

SquishIt is not an independent package, it has dependencies which is doing all the work of minifying and compressing CSS and JS files behind the scenes.

 

After the package is installed successfully, time to squish the files. Open the web page or the master page where you are loading CSS and JS files (in my case it is site.master) and add a reference to the SquishIt assembly on the top of that page.

<%@ Import Namespace="SquishIt.Framework" %>

In the head section of your page we can then combine all the CSS and JS files and then render them into ONE single file. There are two different methods to minimize CSS and JS files i.e. Bundle.Css() for CSS files and Bundle.JavaScript() for JS files. Here is an example:

To bundle CSS:

<%= Bundle.Css()
       .Add("Styles/adipoli.css")
       .Add("Styles/Site.css")
       .Render("Styles/squishstyle#.css")
%>

To bundle JavaScript:

<%= Bundle.JavaScript()
       .Add("Scripts/jquery-1.7.1.min.js")
       .Add("Scripts/jquery.adipoli.min.js")
       .Render("Scripts/squishjs#.js")
%>

You can go on adding all the css and javascript files using the Add() method. After all the files has been added call the Render() method. You can say that the Add()method just keep all the files in a stack and the Render() method will combine and minimize the files. If you look closely in the Render() method has a new file name with a (hash) #. The hash symbol is just generates a new unique id of the bundled script.

When you run the application and check the network call stack in your browser, you'll find that the files are not combined. The page is still loading 4 files!? To overcome this set the debug mode to false in the web.config file.

<compilation debug="false" targetFramework="4.0" />

Now if you look in the network call stack, you will find the files have been squished and minimised and compressed!!

And here are my saving statistics:

Without SquishIt:

Four requests in total!!

Name/Path Type Size Content Time Latency
adipoli.css text/css 683B 62ms
/Styles 441B 55ms
Site.css text/css 4.40KB 68ms
/Styles 4.16KB 61ms
jquery-1.7.1.min.js application/x-javascript 109.91KB 80ms
/Scripts 109.65KB 67ms
jquery.adipoli.min.js application/x-javascript 7.57KB 242ms
/Scripts 7.32KB 163ms

The Squish effect:

Two requests in total. Check out the file size and content being loaded. 

Name/Path Type Size Content Time Latency
squishstyle6788C36F832FE70161B88F2D08193F3E.css text/css 2.95KB 80ms
/Styles 2.71KB 72ms
squishjs0F44BB5917C6332E4D49DFCDA5F3556D.js application/x-javascript 98.29KB 91ms
/Scripts 98.03KB 76ms

The same can be done in MVC with this NuGet package.

Currently rated 5.0 by 1 person