
October 1, 2012 08:05 by
Scott
Microsoft has just officially released the highly anticipated Windows Server 2012. The newly released server operating system offers a number of features that can be utilized to benefit developers, resellers and businesses. As a premier European Windows and ASP.NET hosting provider that follow the developments of Microsoft products, HostForLIFE.eu proudly announces the support of Windows Server 2012 Hosting Platform in the world-class Amsterdam (The Netherlands) data center.
“We know that our customers are always looking for new technologies and the latest Microsoft product. With the launch of Windows Server 2012, we believe that anyone can take advantage of all the improvements available in this platform”, said Manager of HostForLIFE.eu, Kevin Joseph. “The focus on high availability, scalability, and virtualization has made this one of the most important releases of Windows Server to date. We have been working closely with Microsoft throughout the pre-release development cycle of the platform to both drive the direction of the product and ensure our team is ready to support Server 2012 solutions. We couldn’t be more excited and confident in the solutions now available to our clients with Windows Server 2012.”
With our Windows Server 2012 Hosting Platform, customers have an access directly to all the newest technologies and frameworks, such as ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, Silverlight 5 Hosting, WebMatrix Hosting, Visual Studio Lightswitch Hosting and SQL 2012 Hosting. All these technologies/frameworks are integrated properly on our world-class Control Panel. The package is offered from just €2.45/month and we believe that this is the most affordable, features-rich Windows and ASP.NET Hosting package in European market.
HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.
For more information about our service, please visit http://www.hostforlife.eu.
About HostForLIFE.eu:
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.
Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.
Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

September 11, 2012 07:31 by
Scott
In this blog post I will show how to implement a custom XmlMediaTypeFormatter that extends the default ASP.NET Web API XmlMediaTypeFormatter in a way that it ignores XML namespaces when parsing xml messages.
By default the ASP.NET Web API XmlMediaTypeFormatter is not able to parse XML requests that contain any XML namespace declarations. If you would like to support clients, that (for any reason) send messages containing XML namespaces you can use the IgnoreNamespacesXmlMediaTypeFormatter that is defined as follows:
public class IgnoreNamespacesXmlMediaTypeFormatter : XmlMediaTypeFormatter
{
// See http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl
private const string NamespaceRemover =
@"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output method='xml' indent='no'/>
<xsl:template match='/|comment()|processing-instruction()'>
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match='*'>
<xsl:element name='{local-name()}'>
<xsl:apply-templates select='@*|node()'/>
</xsl:element>
</xsl:template>
<xsl:template match='@*'>
<xsl:attribute name='{local-name()}'>
<xsl:value-of select='.'/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>";
private readonly XslCompiledTransform _xlstTransformer;
public IgnoreNamespacesXmlMediaTypeFormatter()
{
var xslt = XDocument.Parse(NamespaceRemover, LoadOptions.PreserveWhitespace);
_xlstTransformer = new XslCompiledTransform();
_xlstTransformer.Load(xslt.CreateReader(), new XsltSettings(), new XmlUrlResolver());
}
public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
{
try
{
// Read XML
var xmlDocument = XDocument.Load(new XmlTextReader(stream));
// Transform XML
var resultStream = new MemoryStream();
_xlstTransformer.Transform(xmlDocument.CreateReader(), XmlWriter.Create(resultStream, new XmlWriterSettings() { OmitXmlDeclaration = true }));
resultStream.Position = 0;
// Process request with XmlMediaTypeFormatter default functionality
return base.ReadFromStreamAsync(type, resultStream, contentHeaders, formatterLogger);
}
catch (XmlException)
{
return base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger);
}
}
}
In detail the IgnoreNamespacesXmlMediaTypeFormatter removes the XML namespace declarations from the XML message and passes the modified XML to the base class to use the default XmlMediaTypeFormatter functionality. Removing the XML namespaces is done with a XSLT transformation (see http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl).
To activate the IgnoreNamespacesXmlMediaTypeFormatter add the following lines in the file Global.asax.cs:
protected void Application_Start()
{
[...]
// Remove default XmlFormatter and add (customized) IgnoreNamespacesXmlMediaTypeFormatter
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
var ignoreNamespacesXmlMediaTypeFormatter = new IgnoreNamespacesXmlMediaTypeFormatter{ UseXmlSerializer = true };
GlobalConfiguration.Configuration.Formatters.Add(ignoreNamespacesXmlMediaTypeFormatter);
[...]
}

August 24, 2012 07:51 by
Scott
If you use an Editor Template for DateTime and use the DataTypeAttribute with either or DataType.Date and DataType.DateTime in ASP.NET MVC 2 or 3 and happen to upgrade to ASP.NET MVC 4 be aware!
ASP.NET MVC 4 introduces two new internal editor templates for properties marked as DataType.Date and DataType.DateTime to render HTML5 input types (date and datetime accordingly).
The unexpected side-effect of this is that if you were previously capturing all DateTime type editing through a DateTime editor template now if your property is marked as DataType.Date ASP.NET MVC 4 will use the new internal Date editor template instead of your DateTime editor template.
The solution is to provide a Date.cshtml editor template along your DateTime.cshtml editor template.

August 6, 2012 07:14 by
Scott
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.
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.
Enable Database Migrations to ASP.NET MVC 4 Website
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");
}
}
Conclusion
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.

June 19, 2012 07:11 by
Scott
ASP.NET MVC 4.0 has two great features: One is Display Mode allows you to create mobile-specific and desktop-specific views and Second is Web API platform for building RESTful applications. Sometimes, You might need to return different data or perform different operations for desktop and mobile request. This article explains how to implement separate actions for mobile request keeping same URL format in Web API.
1. In Visual Studio, Select File > New Project > ASP.NET MVC 4 Web Application > Enter name > OK
2. Select ‘Web API‘ > View Engine: ‘Razor‘ > OK
3. You’ll get default ValuesController. When you access <your app url>/api/Values, the array of string value1, value2 is returned.
To create separate action for mobile request, We are going to create separate controller having ‘Mobile‘ suffix.
Right Click on ‘Controllers‘ folder > Add Controller > Give Name ‘ValuesMobileController‘ > Template: ‘API Controller with empty read/write actions‘ > Add
To differentiate both controllers, replace value1, value2 to mobile-value1, mobile-value2 in get method.
4. Now our object is to call action of Mobile controller when request comes from mobile device.
In Global.asax:
default api route:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Change it to
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
).RouteHandler = new MyRouteHandler();
and add following class:
public class MyRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//Check whether request comes from mobile browser
if (requestContext.HttpContext.Request.Browser.IsMobileDevice)
{
string controller = requestContext.RouteData.Values["controller"].ToString();
requestContext.RouteData.Values["controller"] = controller + "Mobile";
}
return new MyHttpControllerHandler(requestContext.RouteData);
}
}
public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
{
public MyHttpControllerHandler(RouteData routeData)
: base(routeData)
{
}
}
You have to import following namespaces:
using System.Web.Http.WebHost;
using System.Web.SessionState;
In this RouteHandler, Request.Browser.IsMobileDevice checks whether request comes from mobile browser and change controller name with ‘Mobile‘ suffix.
Now run app on browser, For testing, You can change user-agent to iPhone with user agent switcher Firefox add-on and open same URL. you’ll get mobile-value1 and mobile-value2.
Hope it helps

June 4, 2012 08:29 by
Scott
Please see the previous post at here.
Once I removed all the TasksController files and the TodoItem, I chose the Models folder, right click and “Add New Item” and searched for “ADO.NET Entity Model” and added it to the folder.
It allowed me to connect to the Northwind database through “Generate from database” and I selected just three tables “Products”, “Categories” and “Suppliers” table for simplicity. At the end of the wizard, we get a EDMX design file with the 3 tables. On this screen I right clicked and choose “Add Code Generation Item” as below
and then in the dialog that came up, chose the “ADO.NET DbContext Generator” and Added (note, if you don’t see this template, you probably don’t have Entity Framework 4.1 installed)
This step created the Model1.Context (not required for us though) and the Model1.tt template which groups the individual class files for each of the tables above (these are required)
The next thing I did, was to remove the NorthwindEntities connectionstring that got automatically added when we followed the ADO.NET Entity Model wizard. We don’t need this connection string.
Also, I deleted the Model1.Context file and also the Model1.cs files which are not required (we will be generating a new context to suit our database name)
Note that these files are not required only for our SPA approach here and they are required when working with EF CodeFirst normally as they do the DbSet Tracking and whole bunch of things
So, we now have the basic model classes required for wiring up our Controller required to create the SPA Pages. One important thing I learnt in this process was that, I had to edit the Model classes as follows:-
In Supplier.cs added the “private” keyword to the ICollection<Products> property. Same is the case with Category.cs. Otherwise you would run into an error explained here.
After this, I added Controller for Products as per the settings below (Right Click Controller – Add –Controller)
Note several important things. I have chosen the “Single Page Application with read/write actions and views, using Entity Framework” template under Scaffolding options. Also, I have edited the Data context class and made it simply MvcApplication126.Models.Northwind. This would be referenced in the web.config connection string as well so that SPA picks up our existing Northwind database instead of creating a new one.
Once you click “Add” the following files are generated.
Under Controllers
- NorthwindController.cs
- NorthwindController.Product.cs
- ProductsController.cs
Under Scripts
- ProductsviewModel.js
Under Views
- Products folder and the Views and Partial Views required
Repeat the steps for adding Controllers for “Categories” and “Suppliers” and the only change would be the respective Model Classes.
One important thing to do is to add the following connectionstring to the web.config file
<add name="Northwind" connectionString="Data Source=SERVERNAME;Initial Catalog=Northwind;User Id=YOUR USER NAME;Password=YOUR PASSWORD" providerName="System.Data.SqlClient" />
Then, when you run the project, it opens up the default Home Page.
- Navigate to /Products and it should load the list of Products from Northwind database.
- Click on each product and edit and note that everything happens in a single page inline.
- Just notice the URLs change in pattern with hash tags.
- Notice that the Categories and Suppliers are wired up as dropdownlists since these are foreign key references.
- Notice that all the items load asynchronously
I went ahead and edited the Shared –> Layout.cshtml under Views folder to add Menu Items for Products, Categories and Suppliers, as below:-
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Products", "Index", "Products")</li>
<li>@Html.ActionLink("Categories", "Index", "Categories")</li>
<li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
Now, we have our full blown Northwind Traders Application running as a SPA.
You can download the sample from https://skydrive.live.com/redir.aspx?cid=069f94a102eff49a&resid=69F94A102EFF49A!919&parid=root

May 30, 2012 06:42 by
Scott
Single Page Application Frameworks are gaining popularity in the ever evolving web community with lot of libraries such as JavaScriptMVC, Backbonejs and many other libraries. ASP.NET MVC 4 introduces experimental support for building single page application (SPA) through a template. Much of the plumbing work of wiring up the client side scripts, javascript modelviews and the controllers is automated, making it a quick start to develop SPAs relatively easier. Lets examine a scenario where we are building a Northwind Store using SPA.
I installed the ASP.NET MVC 4 Beta for Visual Studio 2010 and the Northwind Sample Database for SQL Server
Post that I did a “File – New Project – ASP.NET MVC 4 Web Application”
In MVC 3 we are used to see a screen with 3 options i.e. Intranet, Internet and Empty templates. In MVC 4 we have additional templates as you can see below and I chose the “Single Page Application” template and created the project template.
In MVC 3 we are used to see a screen with 3 options i.e. Intranet, Internet and Empty templates. In MVC 4 we have additional templates as you can see below and I chose the “Single Page Application” template and created the project template.
Next, the important folder is the Scripts folder and there I found that it creates a <Modelname>ViewModel.js file that holds all the observer pattern script required. In addition, this folder contains a truckload of JavaScript files including jQuery, Knockout, upshot and modernizr.
Finally, inside the “Views” folder, it creates the necessary Partial Views and Index View for Tasks. Once you build and run, you can experience all of this SPA for your TodoItem Model without having written a single line of JavaScript code yet.
So, you learn
1. The ContextName that you select when creating the TasksConroller (inour case it is MVCApplication126Context)is important for you to work with other Databases. By default when you run this solution, Visual Studio would create a SQL Express Database in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA folder with the name MVCApplication126Context.
The way I see the SPA framework identifies is, if you don’t have a connectionstring by the name of the Context, it defaults to creating a database in SQL Express with the ContextName in the above mentioned path.
If you have a connectionstring mentioned with the same contextname, it tries and uses that Database (SQL Express, SQL Server). However, when you are running for the first time, if you create a Database and point it in the connectionstring, it would expect that the Table (mapped to the model i.e. TodoItems) need to exist. Otherwise, it throws an exception. So best, is to either use a Model for which there is a Table that already exists in the Database or provide a new Database name in which case, VS would create the Database with the TodoItems Table as well. There must be someplace to configure all of these, but for the lack of time I didn’t delve deep into these things for now.
So, coming to our Northwind Sample. Northwind has been Developers’ best friend to experiment new things and the saga continues here.
I had to do a couple of things though. First I removed the TodoItem.cs class and also removed the TasksController, Views since we don’t need them. So, for all practical purposes, it is now a plain MVC 4 Application with the default Home & Account Controllers and their respective Views. I also removed the Contextfiles created inside the Controllers Folder.
A bit of analogy on how I built this Northwind App before I explain the actual steps.
The TodoItem is a simple class file and can be hand wired. However, in real world, or for that matter, a simple Northwind database table has a lot of columns and hence properties to be wired up. Also, it requires to map foreign relationships and other things. So, I decided to use the ADO.NET Entity Data Model first to create a model class for the Northwind Database. This would help me in generating DbContext classes using EF CodeFirst Template, which are much simpler than the complex EDMX file that is created by the ADO.NET Entity Model. Thereafter, I can use the class files generated to create the Controller, View and JS ViewModels.

May 25, 2012 06:47 by
Scott
This blog post shows how to validate models containing complex types such as Objects and Lists in ASP.NET MVC 3.
In a first step we modify the properties of the model ( Models/ValidationModel.cs) and add some complex types:
public class ValidUserNameAttribue : ValidationAttribute
{
public override bool IsValid(object value)
{
return (value != null && value.ToString() == "Bob");
}
}
public class User
{
[Required]
[StringLength(8, MinimumLength = 3)]
[ValidUserNameAttribue(ErrorMessage = "User name != 'Bob'")]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(8, MinimumLength = 3)]
[Display(Name = "Display name")]
public string DisplayName { get; set; }
}
public class ValidationModel
{
public User User { get; set; }
public List Users { get; set; }
}
In a second step we modify the form ( Views\Home\Partial\_Form.cshtml) to add input element for the new model properties:
@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel
@DateTime.Now: Partial/_Form.cshtml rendered
< hr/>
@using (Html.BeginForm("Form", "Home"))
{
<h1><em>User</em> object</h1>
<p>
@Html.LabelFor(m => m.User.UserName):
@Html.EditorFor(m => m.User.UserName)
@Html.ValidationMessageFor(m => m.User.UserName)
</p>
<p>
@Html.LabelFor(m => m.User.DisplayName):
@Html.EditorFor(m => m.User.DisplayName)
@Html.ValidationMessageFor(m => m.User.DisplayName)
</p>
<h1>List of <em>User</em> objects</h1>
for (var i = 0; i <= 1; i++)
{
<h2>User @i</h2>
<p>
@Html.LabelFor(m => m.Users[i].UserName):
@Html.EditorFor(m => m.Users[i].UserName)
@Html.ValidationMessageFor(m => m.Users[i].UserName)
</p>
<p>
@Html.LabelFor(m => m.Users[i].DisplayName):
@Html.EditorFor(m => m.Users[i].DisplayName)
@Html.ValidationMessageFor(m => m.Users[i].DisplayName)
</p>
}
<input type="submit" value="Submit" />
}
In a last step we adapt the “success-view” ( Views\Home\Partial\_Success.cshtml) that is shown after the data have been successfully validated on the server side:
@model MVC3_Ajax_Form_jQuery_Validation.Models.ValidationModel
< p><strong>Model is valid :)</strong></p>
< p>
Model.User.Username: '@Model.User.UserName'<br />
Model.User.DisplayName: '@Model.User.DisplayName'<br />
Model.Users[0].Username: '@Model.Users[0].UserName'<br />
Model.Users[0].DisplayName: '@Model.Users[0].DisplayName'<br />
Model.Users[1].Username: '@Model.Users[1].UserName'<br />
Model.Users[1].DisplayName: '@Model.Users[1].DisplayName'
</ p>
As you can see in the source code above, there is no magic; model binding and validation of complex objects and lists work out of the box in ASP.NET MVC 3.

April 23, 2012 07:42 by
Scott
HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. We proudly announces the availability of the SQL 2012 hosting in our entire servers environment. HostForLife customer can choose SQL 2012 when creating a database from inside HostForLife hosting control panel.
The first new option is Windows SQL Server 2012, which is available to customers from today. With the public release just last week of Microsoft’s latest version of their premier database product, HostForLife has been quick to respond with updated their shared server configurations. SQL Server 2012 Web Edition is available for the same low monthly rental price as the previous SQL 2008, as well as Express Edition, which is a basic version of Microsoft’s SQL Database product, available for free.
“We’re proud to be at the cutting edge for new technologies. With these additions, customers have the option to explore these new products in the safe environment of their own shared server. Developers and IT Managers can research the potential impact of next-generation software without risking current infrastructure. With Microsoft’s announcement of the general availability of their new SQL server, we are proud to launch SQL 2012 hosting along with a suite of SQL 2012 management tools." Said John Curtis, VP Marketing and Business Development at HostForLIFE.eu.
John added, “It’s very important to our customers that we support their current deployments; we want to make sure that our customers have their good opportunity to test this new technology."
“HostForLIFE customers can now take advantage of SQL Server 2012’s advanced BI capabilities, We’re excited to see the benefits of this release add value to the energy management and manufacturing arena. Ensuring compatibility with Microsoft’s new SQL Server 2012 demonstrates how HostForLife and Microsoft remain committed together to providing leading edge technology for the benefit of our shared customers." Said CEO of HostForLIFE.eu, Anthony Johnson.
For more information about this new product, please visit http://www.hostforlife.eu/SQL-2012-European-Hosting.aspx.
About us:
We are European Windows Hosting Provider which FOCUS in Windows Platform ONLY. We support Microsoft technology, such as the latest ASP.NET 4, ASP.NET MVC 3, SQL 2008/2008 R2, and much more.
Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.
Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since it's inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

April 6, 2012 05:09 by
Scott
This is the second article focusing on the new additions to ASP.NET MVC 4. Today’s article will focus on using Display Modes. This selects a view depending on the browser making the request, which means you can target specific devices and give the user a truly rich experience.
Before getting started, you should read the first article in this series on ASP.NET MVC 4 Developer Preview.
Installation
Before undertaking any development, you’ll need to install the MVC 4 builds. The simplest way to do this is via the Web Platform Installer. MVC 4 is available for Visual Studio 2010 or Visual Studio 2011 Developer Preview.
All of the MVC articles I’m authoring are developed in Visual Studio 2011 Developer Preview. Below are the links to get started.
- ASP.NET MVC 4 for Visual Studio 2010
- ASP.NET MVC 4 for Visual Studio 2011 Developer Preview
Default Mobile Views in MVC 4
It’s important to understand a new feature in MVC 4. By default, if you add a .mobile.cshtml view to a folder, that view will be rendered by mobile and tablet devices.
This is a nice feature, but if you want to target specific devices, such as the iPhone, iPad or Windows Phone, you can use Display Modes.
To do this, you need to register a new DefaultDisplayMode instance to specify which name to search for when a request meets the condition. You set this in the global.asax file in the Application_Start event. Here’s how to specify a display mode for an iPhone.
protected void Application_Start()
{
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")
{
ContextCondition = (context =>context.Request.UserAgent.IndexOf
("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});
}
To consume views that meet this condition, you create a view but change the extension to .iPhone.cshtml. Likewise if you want to target an iPad, create an iPad instance.
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPad")
{
ContextCondition = (context =>context.Request.UserAgent.IndexOf
("iPad", StringComparison.OrdinalIgnoreCase) >= 0)
});
Basically, Display Modes checks the User Agent. If it finds a matching suffix, it will display any view it finds that matches the suffix. The suffix is the parameter that’s passed to the DefaultDisplayMode method. To see this in action, I’ve created a Home controller and added three views to the Home folder.
The differences between the views is the H1 heading. They’ll display iPhone, iPad or Desktop depending on the device. I’m also displaying the User Agent so you can see it changing. First I’ll debug the website through my desktop browser. You can see the desktop specific page being served.
Now navigate to the website using an iPhone. You’ll see the iPhone specific page being served.
Switching over to an iPad, you’ll see the iPad specific page being served.
This is a simple way to target specific devices, producing a view that suits the device – and thus the user.
Testing with Emulators
To test these new features, you can either use a physical iPhone or iPad, or you can use an emulator. The emulator I was using is from MobiOne. You can download a 15 day free trial here.
The Windows Phone RC emulator is free and can be downloaded here.
Likewise another good option is the User Agent Switcher add-on for Firefox, which changes the user agent that’s sent to the browser. That can be downloaded here.
Do you want to test new ASP.NET MVC 4 hosting for FREE??? Please visit our site at http://www.hostforlife.eu/ASPNET-45-Beta-European-Hosting.aspx.