QueryString in Routing and Model Binding in ASP.NET MVC

Filed Under (Development) by Emad Alashi on 13-01-2012

Tagged Under : , , , , ,

In a nutshell, a query string will not be part of the RouteData dictionary in the routing process, yet it will affect the route matching. On the other hand when Model Binding takes place, query string will be used to bind to the parameters of the action method, unless there is an item in route data with the same key.
Now the details, let’s consider this ASP.NET MVC application, we have an action method:
public ViewResult Archive(DateTime? dateFrom, int? page){...
And we have defined the following routes:
routes.MapRoute(

          "Archive",

          "Archive/{dateFrom}",

          new { controller = "Episode", action = "Archive", dateFrom = UrlParameter.Optional}

          );

Let’s check the URL “~/Archive/1-2-2012?page=2”:
The RouteData dictionary will be as the following:
Key Value
controller Episode
action Archive
dateFrom 1-2-2012?page=2

Yet the action method above will work, and be invoked with the parameters:

Parameter Value
dateFrom 1-2-2012
page 2

So let’s notice the following:

  1. The query string “page” key is NOT part of the RouteData dictionary
  2. In the routing process “?page=2” is considered to be part of the value of the “dateFrom” item in the RouteData dictionary (watch out your route unit tests!)
  3. Even though “dateFrom” route item has the value “1-2-2012?page=2”, Model Binding figures that it can ignore the “?page=2” part because it’s a query string, and the dateFrom parameter is bound correctly to the “1-2-2012”
  4. Even though there is NO “page” item in the RouteData dictionary, the query string it is still used in the Model Binding to bind to the “page” parameter

Having this explained and the above notes taken in mind, what if we have defined an item “page” in the route itself at the end like the following:

routes.MapRoute(

    "Archive",

    "Archive/{dateFrom}",

     new { controller = "Episode", action = "Archive", dateFrom = UrlParameter.Optional, page = 1}

     );

Then this item “page” will show in the RouteData but it should NOT be mistaken by the query string “page”, the Model Binding will always ignore the query string and use the route data item to bind to the action parameter “page”.

And this is why I am writing this post:

  1. I have mistaken the route item “page” with the query string “page” and this confused me a lot
  2. My routing unit tests failed because the query string was still concatenated and present in the value of the route data item, I should have ignored them

I hope this helps you better understand how query strings affects Routing and Model Binding, and helps you avoid what I have went through. Watch out for routing unit tests, and good luck.

Interviews with Jordanian Microsoft Guests

Filed Under (Development, software management) by Emad Alashi on 31-12-2011

Tagged Under : , , , , ,

During the last quarter of 2011 we have hosted two amazing Jordanian Microsoft guests, Yousef Al Khalidi (Distinguished Engineer), and Ayman Dahleh (Development Manager for the Global Experience Platform group), who happened to be having their vacation here, they generously accepted our invitation to deliver sessions here in Jordan despite their busy times.

The community recorded these two inspiring interviews with our guests through which I can see how close achievements can be.

A big thank-you to Mr. Yousef and Mr. Ayman for their availability, and thanks to our DPE at the time Mohammad Arrabi for giving us this opportunity to meet such great people, and thanks to our community member Mosab for making these videos.

Hide Subfolder in Multiple Domains Under One Site

Filed Under (Development, DotNetArabi) by Emad Alashi on 26-12-2011

Tagged Under : , ,

After I have moved to WinHost, I was surprised they don’t support multiple domains under one site out of the box; you have to rely on IIS URL Rewrite magic to achieve that.

So as expected, I looked for a solution in their KB and the internet (you don’t reinvent the wheel, remember?) and found couple of posts here, here, here, and here that helped a lot in achieving this.
So I managed to have www.emadashi.com and www.dotnetarabi.com working fine together residing in the folders “emadashi-blog” and “dotnetarabi-root” respectively under the root; they both have same IP address, but upon request a redirection is made to the proper application folder.

Until one day my very good friend Omar Qadan generously shared a link to an episode he found interesting; and the link was as the following:

“www.dotnetarabi.com/dotnetarabi-root/episode.aspx?..etc”

Ops! that’s not right isn’t it! The URL should not include the folder name “dotnetarabi-root”! So I read more about Regular Expressions, read the above mentioned article more thoroughly, and came to the conclusion that for each domain we have we are going to write two rules:

1) Correct and Redirect undesired URL’s:
If IIS receives a request that contains the folder name (e.g “www.dotnetarabi.com/dotnetarabi-root/episode.aspx”), then:

  1. Omit the folder name from the URL, in our case the URL becomes “www.dotnetarabi.com/episode.aspx” 
  2. Redirect the request again to IIS using the new URL, by sending 301 status prompting the browser to initiate a new request with the new URL

The step above can be achieved by the following:

Figure 1:

    1. <rule name="UnWantedDirectAccessToSubFolder-DotNetArabi-root" patternSyntax="ECMAScript" stopProcessing="true">
    2. <match url=".*" />
    3. <action type="Redirect" url="{C:1}" appendQueryString="true" logRewrittenUrl="false" />
    4. <conditions>
    5. <add input="{HTTP_HOST}" pattern="^(www.)?dotnetarabi.com" />
    6. <add input="{PATH_INFO}" pattern="^[/\\]dotnetarabi_root[/\\](.*)" />
    7. </conditions>
    8. </rule>

Then we do the second rule:

2) Guide and Redirect desired URL’s to the right folder:
If IIS receives a request by the URL format we desire, which doesn’t contain the folder name (e.g. “www.dotnetarabi.com/episode.aspx”) then:

  1. Insert the folder name to the URL to be come “www.dotnetarabi.com/dotnetarabi-root/episode.aspx” in our case
  2. Rewrite the URL again within IIS using the new URL

Which can be achieved by the following:

Figure 2:

    1. <rule name="DirectToDotNetArabiRoot" patternSyntax="ECMAScript" stopProcessing="true">
    2. <match url=".*" />
    3. <action type="Rewrite" url="dotnetarabi_root/{R:0}" appendQueryString="true" logRewrittenUrl="false" />
    4. <conditions>
    5. <add input="{HTTP_HOST}" pattern="^(www.)?dotnetarabi.com" />
    6. <add input="{PATH_INFO}" pattern="^[/\\]emadalashi_blog[/\\]" negate="true" />
    7. <add input="{PATH_INFO}" pattern="^[/\\]dotnetarabi_root[/\\]" negate="true" />
    8. </conditions>
    9. </rule>

The best way to describe what happens is through this diagram I put together (the start block is the “Browser”):

clip_image001

And that was it, now notice the following:

  1. The rules should maintain the mentioned order
  2. Rule 1 uses action type “Redirect”, and Rule 2 uses action type “Rewrite
  3. We configure the rules to stop processing any rule after it is executed
  4. Your key to successful and easy manipulation of the URL is to understand the Back-references in the URL Rewriting, notice the {C:1} and {R:0} usage above, notice as well the brackets () in the URL’s; they are used to capture the back-references, check the “Using back-references in rewrite rules” in the above mentioned article
  5. To test your rules use Fiddler, IE Developers Tools (Network tab), or Firebug (Net tab), and the great tool IIS provides to test rules which can be accessed by: open IIS –> select site-> URL Rewrite –> Double click rule –> double click condition –> Test pattern:
    clip_image002

I hope you found this useful.

Let me do thanks here to  www.gliffy.com as well for providing such great service for drawing diagrams online

“AmmanTT: Developer Edition” presentation and slides

Filed Under (Development, Misc, software management) by Emad Alashi on 09-12-2011

Tagged Under : ,

It was a very interesting event “AmmanTT: Developer Edition” which took place last Tuesday; the team did a very good job putting it together, it is really great seeing this great effort put into such fruitful events; moving the community steps forward, so thank you AmmanTT team, you rock.

Hereby I post the slides I presented in my talk:

Speaking at AmmanTT: Developer Edition

Filed Under (Development, software management) by Emad Alashi on 04-12-2011

Tagged Under : , ,

AmmanTTI will be speaking at “AmmanTT: Developer Edition” next Tuesday 6th of December 2011. Never heard about AmmanTT? quoting from their About page:

Coming to you on the first Tuesday of every month is a 2-hour event that brings industry experts, local technologists/engineers, entrepreneurs, idea-generators and just about any enthusiast together in a casual setting to meet and learn from each other

I will be talking about the real-life side of the software development life cycle, and about the overlapping between Process and Humans in the cycle. So mark your calendars, I will be very happy to meet you there.

HTML5 and IE presentation on Microsoft Open Door

Filed Under (Development, Misc) by Emad Alashi on 04-11-2011

Tagged Under : , , ,

And it’s over, the Microsoft Open Door event is behind us now, and so was my presentation about HTML5 and IE; all praise to god, the feedback was great and I am humbled by the nice compliments.
If you were among the audience and you have any comment, question, or critique, you are most welcome to contact me anytime.

Below is the presentation slides as I promised:

Speaking at Microsoft Open Door

Filed Under (Development, Personal) by Emad Alashi on 27-10-2011

Tagged Under : , ,

I will be speaking at this year’s Microsoft event Open Door; the session will be about HTML5 & IE, including highlights on the main new specifications for HTML5, and how Microsoft is approaching it through IE and some of the dev tools.
It will be on Day 2, Track 3, at 3:00 PM.

Check the event details and agenda here, catch you there hopefully.

My MVP Award Dedication

Filed Under (Development, Personal) by Emad Alashi on 05-10-2011

Tagged Under :

Couple of days ago I received the wonderful email from Microsoft telling me that I was awarded the MVP; it really feels nice when you achieve results. But the best part of all this is my friends’ reactions, the congrats, and the big smiles on the faces (not mentioning a generous gift from my colleagues Winking smile), to all these true friends I say big thank you!

Continuous Integration Book Review

Filed Under (Development, Personal) by Emad Alashi on 21-05-2011

Tagged Under : ,

ContinuousIntegration-coverTo be frank I hesitated a bit to review a “a Martin Fowlers signature book”, but I have to share this review with others; to set expectations.

The book “Continuous Integration” is ok, but it’s too general, that’s it! 
I have read several articles about Continuous Integration and posts here and there until I thought to myself “that’s it, it’s time to get the book, it’s time to delve deep into this”, to my surprise the content of the book was too general and it didn’t add much to the articles I read.

The book itself is nice, but if you have been reading about CI in the past and want to delve deeper, this is NOT the book you want to get.

Reflections on Jordev Web Camp

Filed Under (Development, Personal) by Emad Alashi on 17-05-2011

Tagged Under : , , , , , , ,

webcampsLast Saturday 14th of May 2011 we had the first web camp in Jordan among Jordev’s activities, and it was great!
check my presentation slides at the end of this post.

The event was like the following:

  1. 8:30 AM – 9:00 AM: Registration
  2. 9:00 AM – 1:00 PM: Four 50 minutes sessions with 10 minutes between each for breaks, there was a few attendees at the beginning so we delayed the first session for couple of minutes (yes we have a morning problem here). Sessions were “Entity Framework 4.1”, “ASP.NET MVC One Step Deeper”, “Dynamic Data”, and “jQuery
  3. 1:00 PM – 2:15 PM: lunch break, where people went to the near market and had their lunch there.
  4. 2:15 PM – 4:30 PM: free coding session.

Things went great:

  1. Enough people attended. The attendees were about 25 people spread all over a hall that takes at least 100, this gave us a great freedom in moving around and hocking cables freely on available slots.
  2. The attendees were great. It’s awesome that the attendees were really serious about the event; everyone brought his/her laptop charged and ready, every one was kind enough to pay the right attention, and everyone stayed to the last minute; it’s this passion and dedication that makes a successful event a successful event.
  3. Very good speakers. We were lucky enough to host one of the smartest and most active community members in Jordan: Omar Qadan, Mahmoud Manasrah, and Omar Muwahed did a great job and delivered such a rich value, I was humbled to be among such intelligent speakers and share the stage with them.
  4. Topics were diverse. It’s true all web, but we covered four important parts that summed the basics of a web app: Entity Framework, ASP.NET MVC, Dynamic Data, and jQuery.
  5. There was no lunch arrangement hassle. Interestingly enough, we decided to skip the arrangement for lunch; we still had a lunch break and we provided fast coffee, but we revolted on the pattern of supplying sponsored food and snacks on the lunch break, this gave us the opportunity to concentrate more on delivering technical value, and less managerial things. Of course the near market made our decision a lot easier, in addition to our good luck of having such sufficient number of attendees.
  6. Two and half hours of Free coding. Actually this was pretty good; the free nature of the session allowed the attendees to contribute, and to ask their questions freely.
    We first gave the attendees the opportunity to try things on their own, then we suggested to have walkthroughs; started playing with some of the latest technologies NuGet and Glimpse, then a walkthrough on ASP.NET MVC, then finally a brief general talk about OData.

    Though I see a big space for improvement here; the down side is that there was a dominant stream because the presenter used the main desk and the presentation screen to talk to the majority in the walkthroughs, which was a distraction to the individuals who wanted to try things on their own, anyway I didn’t hear any complaints.
    We had an option to distribute people among groups depending on the technology they want to learn, but it appeared that it was little bit hard to organize, and the attendees in majority agreed to the way we concluded.

  7. The DVD accumulated for the event. We accumulated a DVD that contains Visual Studio 2010 Express, SQL 2008 Express, VS2010 SP1, NerdDinner sample, and MVCMusicStore sample. This helped others to boot up fast with the event, and a nice thing for the attendees to go home with.

Things went wrong:

  1. Marketing the event. We thought that we should limit the number of the attendees to 80 so we don’t end up in crowded auditorium, so we did, and 80 people registered on EventBrite in less than 48 hours of declaring the event on Facebook and Twitter. To our sad happy surprise only 25 people showed up! I know that not all event registrars attend the events they register for online, but the percent is strikingly high! 75% not attending?! what was wrong?
    I think we didn’t do enough reminders, apparently people are lazy about keeping their calendars
  2. SQL Express installation file was 64 bit. 32 bit OS is still the most common OS here, so we missed that up.

Things we did for preparations:

  1. Distributed tasks among us (four people) so everyone had a clear task, this way we made sure we don’t miss anything due to ambiguity in responsibilities
  2. One of us made sure the hall was booked (more tedious than you think!)
  3. Created an event on EventBrite and shared the link over a mailing list, Facebook, and Twitter
  4. Brought enough 3-in-1 packs of Nescafe, one electronic kettle for hot water, and many small bottles of water
  5. Burned out DVD’s with free content (check above)
  6. Brought 3 multi-slot plugs to support the many laptops with electricity
  7. Rehearsed enough for the presentations Smile

That was about it, I hope this reading benefits you and good luck with YOUR web camps.

Jordev-Webcamp-Speakers

My presentation slides embedded: