Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.






September 2011 - Posts

ASP.NET MVC 4: Display modes

One new features of ASP.NET MVC 4 is support for display modes. This means that you can conditionally show different output to different user agents like desktop and mobile browsers. Of course, you can define your own custom rules too. In this posting I will show you how display modes work and explain how to use them in your ASP.NET MVC applications.

User Agent Switcher for Firefox

If you don’t have access to your computer from mobile device you can use User Agent Switcher add-on for Firefox. This add-on allows you to change user-agent string so your Firefox identifies itself as a browser you say for web servers.

Firefox: User Agent Switcher
User Agent Switcher is set to identify Firefox as iPhone 3.0. You can change settings
and add more user-agent strings if you like. The add-on is free to use.

Now let’s get to real business.

Creating mobile view

Create new ASP.NET MVC 4 internet application and leave it as it is created by Visual Studio. We will create now one special view for all mobile devices to show how ASP.NET MVC 4 uses display modes.

Now create new view and name it as Take the code here using copy and paste to get it to your new mobile view.

@{     ViewBag.Title = "Home Page Mobile"; } <h2>@ViewBag.Message</h2> <p>     To learn more about ASP.NET MVC visit <a href= 
title="ASP.NET MVC Website"></a>.
<ul data-role="listview" data-inset="true">     <li data-role="list-divider">Navigation</li>     <li>@Html.ActionLink("About", "About", "Home")</li>     <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul>

Now run your project from Visual Studio and take a look at the page as it is shown in your default web browser. Run Firefox, make it identify itself as iPhone and open same URL in it. You should see the following page.

ASP.NET MVC 4: Displaying mobile page using display modes

What happened? ASP.NET detected Firefox as iPhone. Based on settings in browser capabilities file ASP.NET takes iPhone as mobile device. Now ASP.NET MVC 4 uses this information to detect the correct view. If there is view that has string “.mobile” before file extension ASP.NET MVC 4 uses this view. If such view is not found then default view is used instead.

Creating custom display mode rules

When you are targeting wider range of mobile devices or other user agents then you usually face incompatibility problems that different user agents of same type may have. By example, not all mobile web browsers support CSS fully and for older and poorer mobile web browsers you should create special primitive views. Of course, there are also devices like smart phone browsers that are very powerful and you may want to use some UI parts to use some specific features of these browsers.

You can define your own display mode rules in Application_Start method of Global.asax. Here is one simple example taken from release notes.

protected void Application_Start()







    DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")


        ContextCondition = (context => context.Request.UserAgent.IndexOf

            ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)



Of course, now we need also additional view for iPhone. Add new view for Home controller to your project and name it as Home.iPhone.cshtml. My test view has the following contents.

@{     ViewBag.Title = "Home Page iPhone";

<h2>Welcome to iPhone page</h2>

<ul data-role="listview" data-inset="true">
    <li data-role="list-divider">Navigation</li>
    <li>@Html.ActionLink("About", "About", "Home")</li>
    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>

After running your project and opening it in Firefox you should see something like this.

ASP.NET MVC 4: Displaying iPhone page using display modes

Now we have also separate view for iPhone. We inserted new rule as first one to the display mode rules so before ASP.NET applies mobile devices rule to requests made from iPhone our rule will be detected and applied.


Display modes support in ASP.NET MVC 4 provides us with powerful feature to support different user agents and keeping our project clean at same time. If you create views for different user agents and these views support same type of model then you will have less code in your controllers and views that are not messy and full of different rendering logic. What is the best thing – display modes support is flexible and extensible like many other parts of ASP.NET MVC framework.

Posted: Sep 18 2011, 09:06 PM by DigiMortal | with 4 comment(s)
Filed under: , ,
ASP.NET MVC 4: New mobile web application template

ASP.NET MVC 4 Developer Preview introduces also new template for mobile web applications. These templates are special because they are using jQuery Mobile – special jQuery library for building mobile user interfaces. In this posting I will show you how new mobile web application template looks like.

Two forms below show you home and contact page of mobile web application. These forms are built using jQuery Mobile. jQuery Mobile uses simple HTML mark-up and media queries to make forms look nice. Older browsers and browsers with less features are still able to render these forms in acceptable manner but these forms may seem more basic and not so cool.

ASP.NET MVC 4: Home page of mobile web application ASP.NET MVC 4: Contact page of mobile web application

jQuery Mobile supports more features than showing nice lists. By example there are toolbars and navigation bars, dialogs, buttons, lists etc you can use when building your mobile web application. Also take a look at the very important document that describes jQuery Mobile support levels for different mobile web browsers before you give any promises to your customers.

ASP.NET MVC 4: New template for web applications

I’m playing with ASP.NET MVC 4 Developer Preview. There is new default application template available for ASP.NET MVC 4 web applications. New template is modern, has better look than current one and has better support for different screen sizes. In this posting I will show you how new template looks like.

When you create new internet application and open it in your web browser then you will see this nice and simple page.

ASP.NET MVC 4: Main page of new default web application.
Click on image to see it in original size.

The registration paged is shown in two different modes. When you click Register link then registration form is shown in dialog. You can also type in URL to registration view and then it it shown as usual page.


New template provides different page layout for content pages. There’s no big header and you can also see menu on right.

ASP.NET MVC 4: Sample content page.
Click on image to see it in original size.

New template supports also adaptive rendering and looks nice also on devices with small screen. You can try it also with your browser by making browser window smaller.


New templates look better than old ones but I think there’s still room enough for improvements like hierarchical menus and more professional look. Although I can always find something to take on I still think that new template looks nice and you can use it at least in your in-house applications.

Posted: Sep 16 2011, 12:09 PM by DigiMortal | with 5 comment(s)
Filed under: ,
Using Lucene.NET search engine library in .NET applications

Adding search capabilities to applications is something that users often ask. Sometimes it is not enough to have just filters on lists. Instead of going with mainstream and write complex SQL queries we can be smarter and use specialized indexing and search solutions that perform way better than custom large SQL queries that I consider as anti-pattern for searching something. In this posting I will introduce you Lucene.NET indexing and search engine and show you how to use it in your applications.

NB! I just started playing with Lucene.NET and this is just my quick introduction about how to get it work and start discovering it. Code examples here maybe not perfect ones but they help you to get started and I am sure that later I am able to write more effective code for Lucene.NET.

What is Lucene.NET?

Lucene.NET is indexing and search server ported from famous Lucene that is developed for Java platform. From Lucene.NET project page we can read that Lucene.NET has the following goals:

  1. Maintain the existing line-by-line port from Java to C#, fully automating and commoditizing the process such that the project can easily synchronize with the Java Lucene release schedule.
  2. Maintaining the high-performance requirements excepted of a first class C# search engine library.
  3. Maximize usability and power when used within the .NET runtime. To that end, it will present a highly idiomatic, carefully tailored API that takes advantage of many of the special features of the .NET runtime.

To add search capabilities to your application you can take Lucene.NET because it performs way better than all those awful custom mega-big-and-smart search queries that sooner or later will kill your server.

Adding documents to Lucene.NET index

By its nature Lucene.NET let’s you define loose and structured documents. Documents have properties that you can freely define. These properties may have values and Lucene.NET is able to index them. These properties and their values are used when user searches Lucene.NET index.

Before we can search something we need to have at least one document in Lucene.NET index. Here’s how to add document to index.

private static void WriteDocument()


    Directory directory = FSDirectory.Open(
                             new DirectoryInfo("LuceneIndex")

    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);           

    var writer = new IndexWriter(directory, analyzer,


    var doc = new Document();

    doc.Add(new Field("id", "1", Field.Store.YES, Field.Index.NO));

    doc.Add(new Field("postBody", "Lorem ipsum", Field.Store.YES,







After calling this method we have new document in Lucene.NET index. This document has ID with value 1 and property postBody with value “Lorem ipsum”. As we can see the ID property is not indexed and we don’t expect somebody to search documents by ID.

Searching documents

Now we can write method that searches documents by given phrase in document body.

private static void SearchSomething()


    Directory directory = FSDirectory.Open(
new DirectoryInfo("LuceneIndex")

    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);        


    var parser = new QueryParser(Version.LUCENE_29, "postBody", analyzer);

    Query query = parser.Parse("lorem*");


    var searcher = new IndexSearcher(directory, true);


    TopDocs topDocs = searcher.Search(query, 10);


    int results = topDocs.scoreDocs.Length;

    Console.WriteLine("Found {0} results", results);


    for (int i = 0; i < results; i++)


        ScoreDoc scoreDoc = topDocs.scoreDocs[i];

        float score = scoreDoc.score;

        int docId = scoreDoc.doc; 

        Document doc = searcher.Doc(docId);


        Console.WriteLine("Result num {0}, score {1}", i + 1, score);

        Console.WriteLine("ID: {0}", doc.Get("id"));

        Console.WriteLine("Text found: {0}\r\n", doc.Get("postBody"));






In this method we will search for search term lorem*. Asterisk means that we want to get all documents that start with search term lorem. Search results are retrieved as TopDocs object that contains scoreDocs collection. Each scoreDoc contains information about specific document returned by search. To get actual document we need to ask it from searcher by document ID.

More resources

Here you can find more information about Lucene.NET:


Lucene.NET is good solution for applications that need wide and powerful search capabilities. Lucene.NET is small library by size and it is very easy to use. Lucene.NET API enables you to fully manage the search index and perform queries on it. Although Lucene.NET is in Apache incubator right now it is promising project and I think it is worth to try out.

Posted: Sep 02 2011, 12:25 PM by DigiMortal | with 5 comment(s) |
Filed under: ,
More Posts