ASPHostCentral.com ASP.NET MVC Hosting BLOG

All about ASP.NET MVC 4.0 Hosting, ASP.NET MVC 3.0 Hosting and ASP.NET MVC Hosting articles

.NET MVC 4.0 Hosting :: ASP.NET MVC 4 and working with HTML5 Chart Helper Extension

clock September 10, 2012 15:41 by author Administrator

With the introduction of ASP.NET MVC, the traditional ‘Control’ model of GUI component development went away. Instead it was replaced with the more Web 2.0 style JavaScript and jQuery plugin extensibility model. Nevertheless, adding incremental features to existing HTML components was always required and towards this end Microsoft introduced the HtmlHelper and helper extensions. Helper extensions are .NET extension methods that return a string. Typically, this string is formatted HTML content.

In our sample today we create an extension that renders a bar chart on HTML5 Canvas. It can be bound to a data source from the server side or be assigned data source from the client side.

Building a Html Helper Extension

Html Helper extensions are easy to build. Just follow the steps below to create our helper skeleton.

Step 1: We start with an MVC project and pick the Blank template.

Note we could pick a class library project template too and add package references as follows (via the Nuget package manager as follows)

a. PM> install-package Microsoft.AspNet.Mvc
b. Add reference to System.Web.dll from the ‘Add References’ dialog for the project

Step 2: Add a static class called ChartExtensions. Extension methods, by design, have to be defined in Static classes.

Step 3: Next add a static method Chart whose first parameters is this HtmlHelper and subsequent parameters are values required for rendering the chart.



a. The dataSource is a list of integer arrays. For the example we have assumed a two dimensional array would be provided as a data source. We can make it more sophisticated by making it an array of objects and binding to different properties of the object.
b. xTitle: The text to be displayed on the x-axis.
c. yTitle: The text to be displayed on the y-axis.

Step 4: Next we setup two methods, one to convert the dataSource to JSON and the other to generate the required HTML.



a. The GetDataSourceFromIntArray method uses the System.Web.Helpers’ Json static class to convert the input data source into a Json String. This string is assigned to a variable called arrDataSource and the whole string is returned.
b. The SetupHtml method implements the rendering logic

Step 5: Using TagBuilder to build the Html: ASP.NET provides us with the TagBuilder class that has helper methods to help create HTML elements easily. We use the TagBuilder to create our HTML layout as follows

<div>
<canvas …> … </canvas>
<script …> … </script>
<noscript> … </noscript>
</div>

The actual code is as follows


a. As seen above, the TagBuilder object has an Attributes collection to which we can add the HTML attributes we need. To set text between the opening tag and closing tag, we use the SetInnerText. However unlike an XmlTextWriter, we can’t nest tags. To nest tags we simply assign the string representation of the TagBuilder to the InnerHtml of the parent TagBuilder. So the ‘container’ Tag Builder has the <div> that encapsulates the Canvas and the Script tags.
b. We have created a 400x600 canvas area. The chartName parameter is used for the id of the canvas element.
c. For now we have an empty SetupScript method. This method will eventually build the JavaScript required to render the bar graph.
d. The <noscript> tag holds the message to display when JavaScript is not enabled on the browser.
e. Point to note is the HtmlString object that is returned. The HtmlString is a special object that indicates to the Razor view engine that it should not Html Encode this string any further. If we use string instead of HtmlString, the Razor engine automatically Html Encodes the string and we see the markup as text instead of rendered Html.

Step 6: The SetupScript method: The setup script method has the JavaScript that actually renders the chart on the canvas. The original code is borrowed (with permission) from this project. A demo for it is available here. We have to make the following changes so that it accepts any data source instead of the fixed data source assigned to it in the demo. We have also updated the code to use the strings passed in for x-axis and y-axis labels. Beyond this the animation and rendering code is pretty much the same.

a. The variable initialization change

Earlier we had a hard-coded array of strings that was rendered on the canvas. Now we have the Json string that is created from the data source that was passed to the helper.
b. Changes to the barChart() method to set data source on the client side.

In the barChart method we earlier had no parameters and the elementId was hard-coded, now we use the value that’s passed into the helper.
We also pass a data parameter that is assigned to the data source of the graph.
c. Changes in drawMarkers() method to use the values passed into the helper for the x-axis and y-axis label

d. Changes to handle two-dimensional array of points instead of one-dimensional array of comma separated strings.


In the original code, the data source is an array of strings. Each element in the array has two comma separated values, represent the year (at index-0) and number of hits (at index-1). We have updated our data source to be a two-dimensional array and hence we don’t need to do a string split to get the value. We directly access the value using appropriate indexes. This change is at three places in the code. One of them is shown above.

With these changes in place our Chart, HtmlHelper is ready to be tested in an ASP.NET Web Application

Integrating the Custom Helper in a MVC Web Application

With our Helper all set, we add an MVC Web Application to our solution and call it DotNetCurry.HtmlHelpers.WebHarness. We use the Internet template that gives us a default Index.cshtml to put our Helper in. The following steps guide us through the integration effort

Step 1: Add Reference to the HtmlHelper project.

Step 2: Add a Model class in the Models folder.


This is our view model that will hold the data to be rendered in the Graph.

Step 3: Update the HomeController to create and pass sample data model.



As seen above, we create an instance of our ViewModel class and add some test data into it. We pass this data on to the Index view, where the HtmlHelper will use it.

Step 4: Update the Index.cshtml markup to use the helper


The changes in Index.cshtml highlighted above, from top to bottom are as follows

a. Declare the model to be used in the page.
b. Add using to include the custom HtmlHelper
c. Added the HtmlForm inside which we use our Chart Helper extension. We give it an id=’sampleChart’, pass it the Model.Data and provide the labels for the x and y axes.
d. Finally in the jQuery document ready function, we initialize the chart by calling the barChart() method.
e. Our final effort looks as follows.



To change the graph change the data set coming from the controller.

That brings us to the end of this tutorial. We round off with some of the improvements possible.

Possible Improvements

1. Update the script to be able to bind to any Json object.
2. Use jQuery plugin syntax so that more than one helper can be created per page.
3. Allow more flexibility like passing parameters for bar colors, size of chart etc.
4. Allow multiple data sources to show comparison side by side.
5. Add more chart types like Pie etc.

Conclusion

Though they sound esoteric HtmlHelper extensions is a rather simple mechanism to inject rich functionality in a componentized way in ASP.NET MVC applications. We converted an existing HTML5 chart, originally created using plain HTML5 and JavaScript into a Chart HtmlHelper with very little code. For large projects, HtmlHelpers are a neat way to encapsulate small pieces of re-usable UI functionality.

Currently rated 1.9 by 18 people

  • Currently 1.944445/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


.NET MVC 4 Hosting :: New Things to Learn in ASP.NET MVC 4

clock March 27, 2012 15:59 by author Administrator

Introduction

MVC4 is really trying to break new ground in helping developers get to market more quickly and with a product that adheres to the emerging standards of today. A tough thing to ask of any technology, to be sure, but it's making some decent strides in the right direction.

Already the tutorials and blogs posts are popping up quicker than mushrooms on the midden heap. We highlight a few here that you definitely shouldn't miss which deal with key upcoming features...

ASP.NET MVC  4 Hosting

If you are looking for a QUALITY, AFFORDABLE host that supports
ASP.NET MVC 4 Hosting, you can take a look at ASPHostCentral.com



ASP.NET MVC 4 Overview - Part 2

Jon Galloway goes into some significant detail here about some of the changes coming our way in the new version. He talks about the new default templates that come out of the box and the reasoning behind them.

He also talks about the new adaptive rendering taking advantage of CSS media queries and the usage of the viewport meta tag to help improve the mobile user experience. Overall a solid post that will stand the test of time. Check it out...


ASP.NET MVC 4 Bundling and Minification

Bundling and Minification of assets have to be two of the most tedious things to setup on a new web project. In this excellent post, David Hayden goes through exactly what you need to do to make the process as seamless as possible in MVC4.

Don't make the mistake of leaving this to the end of the project. You'll have deployment nightmares you didn't dream of and you'll be kicking yourself for not smoothing out the wrinkles. Do it early, and you'll thank yourself everyday for that small mercy...


Micro ORM Data Mapping with PetaPoco and ASP.NET MVC 4

Getting tired of working with the verbosity of Entity Framework classes and mapping? Well, you're not the only one, and in this quality post, Greg Arroyo takes us for a lap around the track using PetaPoco as your Micro ORM in MVC4.

Micro ORMs really are here to stay, and in some ways, more broadly applicable to web applications of today where everyone is trying to keep things more simple. If you haven't tried one yet, take this opportunity to get clued up on these fantastic tools.


ASP.NET MVC 4 Web API Routes and ApiController

Once again David Hayden masterfully takes us through a key piece of architecture that is going to be very important to anyone who will be working with MVC4. He details what seems to be a very slick piece of integration work between the new Web API framework and MVC4, and he throws in some OData queries for good measure.

It's short and sweet, and just enough to get you going, and whet your appetite for how to architect your solutions around your own APIs, allowing for more decoupled designs with less possible points of failure.


Getting started on your first Single Page Application

As with the introduction of any new method now encompassed in a technology, it's best to start with what comes straight from the horse's mouth. This Walkthrough put together by Brad Severtson gives you a great introduction, and leaves the mind boggling as to the possibilities.

If you've ever wanted to build your own Gmail and specifically wanted to do it with MVC, then go ahead, knock yourself out! (no pun intended)..

Currently rated 1.6 by 106 people

  • Currently 1.556604/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4 Hosting :: Entity Frameworks Database Migration and ASP.NET MVC 4

clock March 21, 2012 16:30 by author Administrator

ASP.NET MVC 4 was released in beta by the Microsoft ASP.NET MVC Developer Team and it comes with a number of really cool features: Bundling and Minification Support of CSS and JavaScript, Database Migrations using Entity Framework 4.3, Web APIs, Mobile Web with support for jQuery Mobile, Real Time Communication via SignalR, and Asynchronous Support. The Database Migrations using Entity Framework Code-First is really cool and is very much like Rails where you can change your code and then via Package Manager add migrations and update your database as your code evolves. Because the EF Migration Files and Configuration get added to your Visual Studio Solution, all the database migration changes get added to source code.

If you are looking for a quality ASP.NET MVC 4 Hosting provider, please have a look at ASPHostCentral.com


   

ASP.NET MVC 4 and Entity Framework Code-First

ASP.NET MVC support for EF Code-First has been there since ASP.NET MVC 3. To jump start playing with Database Migrations start an empty ASP.NET MVC 4 Project and use Package Manager to install or update Entity Framework to the latest version that includes Database Migrations.

Install-Package EntityFramework

Add a simple Product Class that represents a product in your E-Commerce Website. Let's intially make Product simple by just providing an Id and Title to it.

public class Product {
    public int Id { get; set; }
    publis string Title { get; set; }
}


Run the Add Controller Recipe in ASP.NET MVC 4 to add a Products Controller that uses Entity Framework to read/write to the Database of your E-Commerce Website.



Once the Add Controller Recipe is finished you will have a working ASP.NET MVC 4 Website that reads and writes products to the Database using Entity Framework. The ProductsController was created along with all actions and views that display, create, update, and delete products.

Enabled Database Migrations to ASP.NET MVC 4

Now we want to enable database migrations to ASP.NET MVC 4 by using the Package Manager Console.

Enable-Migrations

Enabling database migrations creates a new Migrations Folder in your Visual Studio Solution as well as an InitialCreate Target Migration that has both an Up and Down Migration. The Up Migration creates the Products Table while the Down Migration drops the Products Table.

public partial class InitialCreate : DbMigration {
    public override void Up() {
        CreateTable(
            "Products",
                 c => new
                 {
                      Id = c.Int(nullable: false, identity: true),
                      Title = c.String(),
                  })
                  .PrimaryKey(t => t.Id);
         );
     }

     public override void Down() {
          DropTable("Products");
     }
 }


Add New Database Migration to ASP.NET MVC 4 Website

Now let's say we want to add more properties to the Product Class as well as make Title a Required Property and a length of 255 characters.

public class Product {
    public int Id { get; set; }

    [Required,MaxLength(255)]
    public string Title { get; set; }

    public string Description { get; set; }

    public decimal Price { get; set; }
}

One can now add a data migration as well as update the database via the Package Manager Console.

Add-Migration AddDescriptionPriceToProduct
Update-Database


The Add-Migration command creates another file in the Migrations Folder of our ASP.NET MVC 4 Project and the Update-Database command updates the database with the new Description and Price Columns as well as modifies the Title Column to be only 255 characters and not nullable.



If you look at the ASP.NET MVC 4 Database before and after issuing this Database Migration you will notice the effect.



And, of course, the new Database Migration File has the approprite Up and Down Methods.

public partial class AddDescriptionPriceToProduct : DbMigration {
    public override void Up() {
        AddColumn("Products", "Description", c => c.String());
        AddColumn("Products", "Price",
            c => c.Decimal(nullable: false, precision: 18, scale: 2));
        AlterColumn("Products", "Title",
            c => c.String(nullable: false, maxLength: 255));
    }

    public override void Down() {
        AlterColumn("Products", "Title", c => c.String());
        DropColumn("Products", "Price");
        DropColumn("Products", "Description");
    }
}

Conclusions

If you are a Rails Developer moving to ASP.NET MVC 4, you will find the Database Migrations support in Entity Framework a nice addition to the tooling. And, of course, those ASP.NET MVC 4 Developers that love Code-First Development with Entity Framework will love the new Database Migrations support in EF 4.3. Don't forget to check out other ASP.NET MVC 4 Features such as bundling and minification of CSS and JavaScript, Web API's, Asynchronous Support, and the mobile web templates. ASP.NET MVC 4 is still in beta at this point, but it has a go-live license.

Currently rated 1.8 by 26 people

  • Currently 1.846154/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4.0 Hosting :: Exciting Features of ASP.NET MVC 4.0 Framework

clock March 15, 2012 15:59 by author Administrator
Not only MVC

First of all I want to make clear that most features aren't MVC-specific features. However, MVC does implement most of them out-of-the-box, while Web Forms needs some more installation and configuration work.

Front-end

Minification

There are some really neat features on the front-end part of MVC 4, first of all there's minification. Minification means that all spaces, enters and comments are removed from your CSS / Javascript files (including coffee, SASS and LESS), and that variable names are replaced with shorter variable names (such as a, b, c, etc.). This means that less data needs to be transferred to the visitors of your website, resulting in a faster page loading time, etc. Probably a feature that any front-end developer will love.

Bundling

Another cool feature that is often mentioned in one sentence with minification is bundling. Bundling means that you can have separate CSS files (e.g. one for your content, one reset style sheet, one for your layout) that are 'bundled' into one CSS file. ASP.NET does this by convention (but it's also configurable), for example: the reset.css will be placed in the bundle first, etc. This means that you only have one request instead of multiple requests, again resulting in a faster page load time.

Mobile web

Much has been done to improve the way MVC 4 behaves on mobile devices. There's now a mobile application project type that creates a nice lay-out that uses JQuery mobile to do all kinds of fancy stuff. MVC 4 also tries to render your lay-out in a mobile compatible way. This means that your elements are properly resized to fit inside the screen of mobile devices. But this is not the only feature, nor is it the most exiting feature. The most important mobile web feature (in my opinion) is the fact that you can now create device specific views. This allows you to create specific views for Windows Phone 7 devices, for Android devices, etc.

Project templates

For those who just want to make a quick prototype there are new project templates that look pretty fancy compared to the old project templates. Below is an overview of the new templates, the left template is the default template when you choose the 'internet application' project type, the second is the 'single page application' type and the third, obviously, the mobile type. The new project types also support AJAX login and OAuth.

Back-end

Web APIs

A very exiting new feature of ASP.NET is the introduction of Web APIs. This is another name for the new controller type, namely the ApiController. The ApiController makes creating an API much easier compared to WCF. Just like the default MVC controllers you can mark methods to be HttpPost methods, HttpGet methods, etc., but there are many new features to this.

The ApiController now allows users to perform queries against the API with OData if the ApiController method returns IQueryable<T>, it's possible to return specific HTTP codes to the consumer of the API, there's improved testability and IoC support, and more features that you will love.

Since the ASP.NET team and the WCF team have been merged, the new ASP.NET Web API wil replace some parts of WCF. This is a good things because the Web API is really easy (and flexible) to work with.

If you want to know more about ASP.NET's Web API I recommend Scott Guthrie's blog post about it.

Async

There was Async support in MVC 3. This meant that you need to have two methods: an Async method and a Completed method. MVC 4 removes the need for two methods and simplifies the way tasks are defined. Below are two examples:

The MVC 3 approach:

public void IndexAsync(string city) {
    AsyncManager.OutstandingOperations.Increment(2);
    NewsService newsService = new NewsService();
    newsService.GetHeadlinesCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["headlines"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    newsService.GetHeadlinesAsync();
     SportsService sportsService = new SportsService();
    sportsService.GetScoresCompleted += (sender, e) =>
    {
        AsyncManager.Parameters["scores"] = e.Value;
        AsyncManager.OutstandingOperations.Decrement();
    };
    sportsService.GetScoresAsync();
}

public ActionResult IndexCompleted(string[] headlines, string[] scores, string[] forecast) {
    return View("Common", new PortalViewModel  {
        NewsHeadlines = headlines,
        SportsScores = scores,
    });
}

The MVC 4 approach:

public async Task<ActionResult> Index(string city) {
    var newsService = new NewsService();
    var sportsService = new SportsService();    

    return View("Common",
        new PortalViewModel {
        NewsHeadlines = await newsService.GetHeadlinesAsync(),
        SportsScores = await sportsService.GetScoresAsync()
    });
}

As you can see the MVC 4 approach is much shorter and much easier, probably leading to more people using asynchronous methods. The code is still compiled into the same intermediate language, it's just syntactic sugar.

Real-time communication

There's also support for WebSockets and a new open source framework called SignalR that allows you to set up a real-time multi-user interactive website in a real easy manner. I highly recommend reading Scott Hanselman's blog post about SignalR and the official SignalR Github project.

Database migrations

The last feature that I wanted to mention is probably the coolest new feature. However, it's rather an Entity Framework feature than an ASP.NET feature. I'm talking about Entity Framework 4.3's new Database Migrations.

What it means is that Entity Framework can generate classes with Execute/Unexecute (actually they are called Up and Down, but I don't think those names really describe what they do), performing any database modifications that you've made. For example: let's say we have an entity called Person. If I wanted to add a property called 'Age' to Person entity, Entity Framework would generate a class for me with two methods: the Up method that adds the Age property to the Person table in the database (or whatever we've mapped the Person entity to) and the Down method that removes the Age property from the Person table. This allows us to rollback any changes, or easily perform updates on the database.

Entity Framework also allows us to generate SQL so we don't have to write change scripts manually any more. Automating the generation of change scripts can significantly reduce the time it takes to deploy your application, allowing the developers to focus on developing new features.

Currently rated 1.9 by 16 people

  • Currently 1.875/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4.0 BETA Hosting FREE Account is now available at ASPHostCentral.com

clock March 14, 2012 16:33 by author Administrator

ASPHostCentral.com, the leader in ASP.NET and Windows Hosting Provider, proudly announces that we have supported the latest ASP.NET MVC 4.0 BETA Hosting.   

To support Microsoft ASP.NET MVC 4.0 BETA Framework, we gladly inform you that we provide this beta account FREE of charge for a limited time (* terms and conditions apply). 



New Features in ASP.NET MVC 4


This section describes features that have been introduced in the ASP.NET MVC 4: 
- Enhancements to Default Project Templates
- Better Support for Mobile Project Template
- Enhancement in Display Modes
- Mobile Project Template support for VB.NET
- Dependency Injection Improvements    

Terms and Conditions in Using this ASP.NET MVC 4.0 BETA Account
 

The followings are the features you will get under this FREE ASP.NET MVC 4.0 BETA Account: 
- ASP.NET MVC 4.0 Beta Framework
- 1 Website/Domain
- 100 MB disk space
- 100 MB bandwidth
- 50 MB SQL 2008 space
- 24/7 FTP access
- Windows Server 2008 Platform

If you want to participate in this BETA program, there are several rules you need to understand: 

- As this is a beta version, not all the features are available. They may be some issues on this beta framework, which will be fixed upon the full release of ASP.NET MVC 4.0 Framework

- ASPHostCentral.com does not guarantee the uptime of the sandbox solution. Additionally, we do not keep/store any backup of your files/accounts

- ASPHostCentral.com does not guarantee rapid response to any inquiries raised by a user

- This free account is only meant for testing. Users should not use it to store a production, personal, e-commerce or any blog-related site

- This free account is used to host any ASP.NET MVC 4.0 beta website only. Any questions that are not related to ASP.NET MVC 4.0 BETA will not be responded. A user shall not host any non-ASP.NET MVC 4.0 site on this free account either

- ASPHostCentral.com reserves full rights to terminate this beta program at any time. We will provide a notification on our Help Desk System prior to the termination of this program

- ASPHostCentral.com reserves full rights to terminate a user account, in which we suspect that there is an abuse to our system

- Once this beta program is terminated, your account will be completely wiped/remove from our system.

- This offer expires on 31st May 2012

If you wish to participate in this FREE ASP.NET MVC 4.0 BETA Program, you must register via https://secure.asphostcentral.com/BetaOrder.aspx

 

Currently rated 2.2 by 10 people

  • Currently 2.200001/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4 Hosting :: ASP.NET MVC 4.0 Mobile Template

clock November 16, 2011 15:22 by author darwin

Introduction

The five years back, we all are knew that  we able to developed ASP.NET mobile application usign Visual Studio, but microsoft  has been take off those templates from the visual studio in the following versions. But again there is a good news for all that Microsoft has released the much awaited ASP.NET MVC 4.0 developer preview and there are lots of features bundle with it. One of the greatest features is a mobile website. Yes, Now with ASP.NET MVC 4.0 you can create mobile site also. So let’s create a simple application and let’s see how it works.

To create mobile site first you need to click File->New Project->ASP.NET MVC 4.0 Web application. Like following.




Now once you click OK it will open a new another dialog like following where we have to choose the Mobile site.



As you can see in above post I have selected Razor view Once you click it will create a new application like following. As you can see similar structure as normal MVC Application application below.



This view are based on the standard jQuery Mobile. So this can be viewed in any tablet or mobile device. So if you have IPad and IPhone both then it will work on both. You need not to different application for both. see the browser first I have selected standard IPad size of browser.



Now lets see how it look in mobile. So I have made my browser same site as mobile. As you can see its working in both.



If you see the code of view you can see the razor syntax over there. Nothing change in razor syntax. But as you can see in below code you need to use Jquery mobile attributes like data-Role and other stuff which will convert standard HTML into mobile or device compatible website.

<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>


That's it. It’s very easy you can create mobile compatible site in few hours. Hope you like it.

Currently rated 2.2 by 46 people

  • Currently 2.23913/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 4 Hosting :: ASP.NET MVC 4 Display Modes and WURFL.NET

clock October 30, 2011 17:52 by author darwin

The usage of mobile phones to access the web is increasing day by day. So, this is now become very important for every public web application to add the support of mobile browsers. ASP.NET MVC 4 makes it very easy for you to make the mobile phone user’s browsing experience as smooth as possible. For example, with Display Modes feature, you can select views depending on the browser(mobile or desktop) capabilities. But, ASP.NET MVC 4 does not include all the information about the capabilities of different mobile or desktop devices that are currently available on the market. For example, it does not tell you about the screen resolution of various mobile or desktop devices. WURFL(Wireless Universal Resource FiLe), is an up-to-date XML configuration file which contains the information about device capabilities. It contains over 7000 unique devices and thousands of firmware variations. WURFL.NET API(the one which is created by ScientiaMobile), currently, is the only .NET standard API for accessing WURLF data. WURFL.NET API contains information about devices in a list of over 500 capabilities. In this article, I will show you how you can use ASP.NET MVC 4  Display Modes feature with WURFL.NET API.

Description:

Firstly, create a new ASP.NET MVC 4 application. Next, open the Package Manager Console and type “Install-Package WURFL_Official_API”. This will add the WURFL.NET API in the application. You can also install the package using “Add Library Package Reference” dialog. Doing this will automatically add a reference to the WURFL.dll in the application. It will also add web_browsers_patch.xml and wurfl-latest.zip data files in App_Data folder. This step will make the WURFL.NET API available to the application.  


Now you need to tell WURFL.NET API about the location of web_browsers_patch.xml and wurfl-latest.zip data files. There are three ways to do this. First way: specify these data files in the web.config file,

        <wurfl>
            <mainFile path=”C:\….\WURFL.NETAndDisplayModes\App_Data\wurfl-latest.zip” />
            <patches>
              <patch path=”C:\….\WURFL.NETAndDisplayModes\App_Data\web_browsers_patch.xml” />
            </patches>
        </wurfl>

Note, you need to specify the complete path of data files. Currently, WURFL.NET API does not support any shortcuts(like, DataDirectory or ~). Next, you need add the following code inside the global.asax.cs file,


        public const String WurflManagerCacheKey = “__WurflManager”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context.Cache);
        }
        public static void LoadWurflData(System.Web.Caching.Cache cache)
        {
            var configurer = new ApplicationConfigurer();
            var manager = WURFLManagerBuilder.Build(configurer);
            cache[WurflManagerCacheKey] = manager;
        }

Second way: instead of using web.config file, you can put all your code inside the global.asax.cs file,

        public const String WurflManagerCacheKey = “__WurflManager”;
        public const String WurflDataFilePath = “~/App_Data/wurfl-latest.zip”;
        public const String WurflPatchFilePath = “~/App_Data/web_browsers_patch.xml”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context);
        }

        public static void LoadWurflData(HttpContext context)
        {
            var server = context.Server;
            var wurflDataFile = server.MapPath(WurflDataFilePath);
            var wurflPatchFile = server.MapPath(WurflPatchFilePath);
            var configurer = new InMemoryConfigurer()
                    .MainFile(wurflDataFile)
                    .PatchFile(wurflPatchFile);
            var manager = WURFLManagerBuilder.Build(configurer);
            context.Cache[WurflManagerCacheKey] = manager;
        }

Third way is the combination of first and second way. First, you need to add these app settings in web.config file,

        <add key=”WurflDataFilePath” value=”~/App_Data/wurfl-latest.zip” />
        <add key=”WurflPatchFilePath” value=”~/App_Data/web_browsers_patch.xml” />

Next, add the following code inside the global.asax.cs file,

        public const String WurflManagerCacheKey = “__WurflManager”;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            LoadWurflData(Context);
        }
        public static void LoadWurflData(HttpContext context)
        {
            var server = context.Server;
            var appSettings = WebConfigurationManager.AppSettings;
            var wurflDataFile = server.MapPath(appSettings["WurflDataFilePath"]);
            var wurflPatchFile = server.MapPath(appSettings["WurflPatchFilePath"]);
            var configurer = new InMemoryConfigurer()
                    .MainFile(wurflDataFile)
                    .PatchFile(wurflPatchFile);
            var manager = WURFLManagerBuilder.Build(configurer);
            context.Cache[WurflManagerCacheKey] = manager;
        }

Now, WURFL.NET API is initialized. Let’s say you need to show a particular view depending on the device screen resolution. You can do this by adding the following code in Application_Start method, 

        DisplayModes.Modes.Insert(0, new DefaultDisplayMode(“Resolution320By480″)
        {
            ContextCondition = (context =>
            {
                var manager = (context.Cache[WurflManagerCacheKey] as IWURFLManager);
                var cabablities = manager.GetDeviceForRequest(context.Request.UserAgent);
                return cabablities.GetCapability(“resolution_width”) == “320″
                    && cabablities.GetCapability(“resolution_height”) == “480″;
            }
            )
        });


Now, if you make a request which returns the Index view, then ASP.NET MVC framework will look for Index.Resolution320By480.cshtml file for devices with 320X480 resolution and Index.cshtml file for others. Similarly, you can add different display modes in your application depending upon the various capabilities of device. WURFL.NET consists information in a list of over 500 capabilities.

Summary:

Using ASP.NET MVC 4 Display Modes feature, you can select views depending on the browser capabilities. WURFL.NET API provides you a list of over 500 capabilities. Combining both of these features will help you to build an application which support vast amount of devices. In this article, I showed you how you can add WURFL.NET API in your application. I also showed you how you can use WURFL.NET API to find the device capabilities and then use these capabilities in ASP.NET MVC 4 application. Hopefully you will enjoy this article too.

Currently rated 2.2 by 33 people

  • Currently 2.181818/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!


Sign in