About Me

My photo

Senior Technical Talent Advisor and Community Development - A.I, Machine Learning and Data Science.

Director & Co-Founder @ www.Abso-Fashion-Lutely.co.uk
Director & Founder of Data Science & Big Data Analytics IT Job Board http://datasciencebigdataanalytics.jobboard.io/

Roles:

Data Scientist, Statistician, Insight Analyst, Chief Data Scientists, Data Architect, Data Engineer, Data Analyst, Statistics Consultant, Research Engineer, Quantitative Analyst, Developer, Engineer, Pre-Sales / Post Sales engineer, Sales Engineer, Software Engineer, Systems Engineer, Technical Evangelist, Client Services Engineer, Architects (Cloud, Solutions & Enterprise), Cloud & Big data Analytics, Microsoft Azure and consulting roles.

The above is not an exclusive list and I work on a diverse range of roles and technologies. Contact me:  0044 788 135 1363

I am currently studying with Udacity to further my career in Data Science, Big Data Analytics, Programming, Algorithms, Artificial Intelligence, Computer Science, Statistics, Physics, Psychology & Visualizing Algebra.

I specialise in the following:

• Talent Manager and also responsible for expanding our internal team; vetting, meeting & technically testing candidates
• Providing advice around legal, accounting and general recruitment to the community
• Utilising the latest social media strategies for recruitment Twitter,Github Etc ..
• Setting up interviews, negotiating extensions, offers & contracts
• Developing new relationships and bringing in new business
• Client & account management
• Attending and arranging technical conferences to better my understanding of the technologies and markets I specialise in

I own & run the following groups on LinkedIn:
• ASP.Net MVC 3, MVC 4 & MVC5 Ninjas
• Cloud & Big data
• Microsoft Azure Ninjas
• Data Scientist & Analytics UK
• HTML5 Ninjas
• Java Blackbelt
• Hadoop Experts UK & EMEA
You'll need Skype CreditFree via Skype

Friday, 27 July 2012

eSynergy Solutions celebrate the Olympics coming to town

eSynergy Solutions got into the swing of things on Tuesday with an Olympic themed Summer party in Hyde Park. A sports day style course was set up to host a variety of fun events such as; The Limbo, relay and sack race. Teams were themed as countries and each member wore a hat to represent the given nation.

Nicki Treffers, The events organiser said "The day was fantastic, we are all very excited about the Olympic games and thought that there would be no better way to get involved than to create our own version of events . The guys in the office have worked tremendously hard over the last few months and deserved a day in the sunshine to relax and kick back’’ Japan proved to be the triumphant team, with Nigeria coming a close second! Medals and cups were awarded for the efforts.

http://www.apsco.org/Article/Detail.aspx?ArticleUid=48ed6170-30ee-416d-b6a9-f81e0011710f&utm_source=twitterfeed&utm_medium=twitter

Given by the pictures it definitely looked to be a great day!

Image

Monday, 23 July 2012

eSynergy Solutions Summer Party- Tuesday 24th July 2012- The Plan

 

THE SUN IS HEAR AND WE ARE NOW GOING TO GET THE SUMMER PARTY STARTED – COME ON eSYNERGY SOLUTIONS

The Team:

Russia – Nigel (captain), Sarah, Gus, Seren, Martin, Ahilan, Cat

Denmark- Birty (Captain), James, Lucinda, Nicki, Tim, Jack

Nigeria- Pat C (Captain), Neil Matt, Jordan, Rahwa, Claire, Tom Young,

Japan- Kelly (Captain), Antony, Matt Dixie, Tejal, Neil P, Matt

Australia- Naushine (Captain), Karen, Tom Loftus, Adam R, Pat W, Josh

UK- Nicola (Captain), Luke, Nicola A, Gavin, Laura, Chris

The Games:

Each team will select a member to participate in each game.

1. Sack Race

2. Three Legged Race

3. The relay race

4. Space Hopper race

5. Egg and spoon race

6. Skipping race

7. Rounders match

8. Limbo Tournament

9. Football Match

10. Stick of Doom

Each winning team will be awarded a medal. Points will be allocated from 1-6, 6 for the winner 1 for the loser and for those in between. The overall winning team of the day will be award a team Cup and

Allowed to finish work an hour early (to be arranged accordingly). The losers will face a forfeit.

Tuesday, 17 July 2012

Upgrading an ASP.NET MVC 3 Project to ASP.NET MVC 4

ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 3 application to ASP.NET MVC 4.

The simplest way to upgrade is to create a new ASP.NET MVC 4 project and copy all the views, controllers, code, and content files from the existing MVC 3 project to the new project and then to update the assembly references in the new project to match the old project. If you have made changes to the Web.config file in the MVC 3 project, you must also merge those changes into the Web.config file in the MVC 4 project.

To manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:

  1. In all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):
    System.Web.Mvc, Version=3.0.0.0
    System.Web.WebPages, Version=1.0.0.0
    System.Web.Helpers, Version=1.0.0.0
    System.Web.WebPages.Razor, Version=1.0.0.0

    with the following corresponding text:

    System.Web.Mvc, Version=4.0.0.0
    System.Web.WebPages, Version=2.0.0.0
    System.Web.Helpers, Version=2.0.0.0,
    System.Web.WebPages.Razor, Version=2.0.0.0,

  2. In the root Web.config file, update the webPages:Version element to "2.0.0.0" and add a new PreserveLoginUrl key that has the value "true":
    <appSettings>
      <add key="webpages:Version" value="2.0.0.0" />
      <add key="PreserveLoginUrl" value="true" />
    </appSettings>

  3. In Solution Explorer, right-click on the References and select Manage NuGet Packages. Search for Microsoft.AspNet.Mvc and install the Microsoft ASP.NET MVC 4 (RC) package. Click OK.
  4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.
  5. Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.
  6. Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.
  7. If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:
    <configuration>
      <!--... elements deleted for clarity ...-->
     
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers"
                 publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc"
                 publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages"
                 publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
    </configuration>

ASP.NET MVC 4 Mobile Features

his tutorial will teach you the basics of how to work with mobile features in an ASP.NET MVC 4 developer preview Web application. For this tutorial, you can use Microsoft Visual Web Developer 2010 Express Service Pack 1 ("Visual Web Developer"), which is a free version of Microsoft Visual Studio. Or you can use Visual Studio 2010 SP1 if you already have that.

Before you start, make sure you've installed the prerequisites listed below.

You will also need a mobile browser emulator. Any of the following will work:

This tutorial shows code in C#. However, the starter project and completed project will be available in Visual Basic. Visual Studio projects with Visual Basic and C# source code are available to accompany this topic:

What You'll Build

For this tutorial, you'll add mobile features to the simple conference-listing application that's provided in the starter project. The following screenshot shows the tags page of the completed application as seen in the Windows 7 Phone Emulator.

p1_Tags_CompletedProj

Skills You'll Learn

Here's what you'll learn:

  • How the ASP.NET MVC 4 templates use the HTML5 viewport attribute and adaptive rendering to improve display on mobile devices.
  • How to create mobile-specific views.
  • How to create a view switcher that lets users toggle between a mobile view and a desktop view of the application.
Getting Started

Download the conference-listing application for the starter project using the following link: Download. Then in Windows Explorer, right-click the MvcMobile.zip file and choose Properties. In the MvcMobile.zip Properties dialog box, choose the Unblock button. (Unblocking prevents a security warning that occurs when you try to use a .zip file that you've downloaded from the web.)

p1_unBlock

Right-click the MvcMobile.zip file and select Extract All to unzip the file. In Visual Web Developer or Visual Studio 2010, open the MvcMobile.sln file.

Press CTRL+F5 to run the application, which will display it in your desktop browser. Start your mobile browser emulator, copy the URL for the conference application into the emulator, and then click the Browse by tag link. If you are using the Windows Phone Emulator, click in the URL bar and press the Pause key to get keyboard access. The image below shows the AllTags view (from choosing Browse by tag).

p1_browseTag

The display is very readable on a mobile device. Choose the ASP.NET link.

p1_tagged_ASPNET

The ASP.NET tag view is very cluttered. For example, the Date column is very difficult to read. Later in the tutorial you'll create a version of the AllTags view that's specifically for mobile browsers and that will make the display readable.

CSS Media Queries

CSS media queries are an extension to CSS for media types. They allow you to create rules that override the default CSS rules for specific browsers (user agents). A common rule for CSS that targets mobile browsers is defining the maximum screen size. The Content\Site.css file that's created when you create a new ASP.NET MVC 4 Internet project contains the following media query:

@media only screen and (max-width: 850px) {

If the browser window is 850 pixels wide or less, it will use the CSS rules inside this media block. You can use CSS media queries like this to provide a better display of HTML content on small browsers (like mobile browsers) than the default CSS rules that are designed for the wider displays of desktop browsers.

The Viewport Meta Tag


Most mobile browsers define a virtual browser window width (the viewport) that's much larger than the actual width of the mobile device. This allows mobile browsers to fit the entire web page inside the virtual display. Users can then zoom in on interesting content. However, if you set the viewport width to the actual device width, no zooming is required, because the content fits in the mobile browser.

The viewport <meta> tag in the ASP.NET MVC 4 layout file sets the viewport to the device width. The following line shows the viewport <meta> tag in the ASP.NET MVC 4 layout file.

 <meta name="viewport" content="width=device-width">

Examining the Effect of CSS Media Queries and the Viewport Meta Tag


Open the MvcMobile\Views\Shared\_Layout.cshtml file in the editor and comment out the viewport <meta> tag. The following markup shows the commented-out line.

@*<meta name="viewport" content="width=device-width">*@

Open the MvcMobile\Content\Site.css file in the editor and change the maximum width in the media query to zero pixels. This will prevent the CSS rules from being used in mobile browsers. The following line shows the modified media query:

@media only screen and (max-width: 0px) { ...

Save your changes and browse to the Conference application in a mobile browser emulator. The tiny text in the following image is the result of removing the viewport <meta> tag. With no viewport <meta> tag, the browser is zooming out to the default viewport width (850 pixels or wider for most mobile browsers.)

p1_noViewPort

Undo your changes — uncomment the viewport <meta> tag in the layout file and restore the media query to 850 pixels in the Site.css file. Save your changes and refresh the mobile browser to verify that the mobile-friendly display has been restored.

The viewport <meta> tag and the CSS media query are not specific to ASP.NET MVC 4, and you can take advantage of these features in any web application. But they are now built into the files that are generated when you create a new ASP.NET MVC 4 project.

For more information about the viewport <meta> tag, see A tale of two viewports — part two.

In the next section you'll see how to provide mobile-browser specific views.

Overriding Views, Layouts, and Partial Views


A significant new feature in ASP.NET MVC 4 is a simple mechanism that lets you override any view (including layouts and partial views) for mobile browsers in general, for an individual mobile browser, or for any specific browser. To provide a mobile-specific view, you can copy a view file and add .Mobile to the file name. For example, to create a mobile Index view, copy Views\Home\Index.cshtml to Views\Home\Index.Mobile.cshtml.

In this section, you'll create a mobile-specific layout file.

To start, copy Views\Shared\_Layout.cshtml to Views\Shared\_Layout.Mobile.cshtml. Open _Layout.Mobile.cshtml and change the title from MVC4 Conference to Conference (Mobile).

In each Html.ActionLink call, remove "Browse by" in each link ActionLink. The following code shows the completed body section of the mobile layout file.

<body>
    <div class="page">
        <div id="header">
            <div id="logindisplay"></div>
            <div id="title">
                <h1> Conference (Mobile)</h1>
            </div>
            <div id="menucontainer">
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Date", "AllDates", "Home")</li>
                    <li>@Html.ActionLink("Speaker", "AllSpeakers", "Home")</li>
                    <li>@Html.ActionLink("Tag", "AllTags", "Home")</li>
                </ul>
            </div>
        </div>
        <div id="main">
            @RenderBody()
        </div>
        <div id="footer">
        </div>
    </div>
</body>

Copy the Views\Home\AllTags.cshtml file to Views\Home\AllTags.Mobile.cshtml. Open the new file and change the <h2> element from "Tags" to "Tags (M)":

<h2>Tags (M)</h2>

Browse to the tags page using a desktop browser and using mobile browser emulator. The mobile browser emulator shows the two changes you made.

p2m_layoutTags.mobile

In contrast, the desktop display has not changed.

p2_layoutTagsDesktop

Browser-Specific Views


In addition to mobile-specific and desktop-specific views, you can create views for an individual browser. For example, you can create views that are specifically for the iPhone browser. In this section, you'll create a layout for the iPhone browser and an iPhone version of the AllTags view.

Open the Global.asax file and add the following code to the Application_Start method.

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone")
{
    ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf
        ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});

Here's the complete Application_Start method:

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone")
    {
        ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf
            ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
    });
}

This code defines a new display mode named "iPhone" that will be matched against each incoming request. If the incoming request matches the condition you defined (that is, if the user agent contains the string "iPhone"), ASP.NET MVC will look for views whose name contains the "iPhone" suffix.

In the code, right-click DefaultDisplayMode, choose Resolve, and then choose using System.Web.WebPages;. This adds a reference to the System.Web.WebPages namespace, which is where the DisplayModes and DefaultDisplayMode types are defined.

p2_resolve

Alternatively, you can just manually add the following line to the using section of the file.

using System.Web.WebPages;

Save the changes. Copy the MvcMobile\Views\Shared\_Layout.Mobile.cshtml file to MvcMobile\Views\Shared\_Layout.iPhone.cshtml. Open the new file and then change the h1 heading from Conference (Mobile) to Conference (iPhone).

Copy the MvcMobile\Views\Home\AllTags.Mobile.cshtml file to MvcMobile\Views\Home\AllTags.iPhone.cshtml. In the new file, change the <h2> element from "Tags (M)" to "Tags (iPhone)".

Run the application. Run a mobile browser emulator, make sure its user agent is set to "iPhone", and browse to the AllTags view. The following screenshot shows the AllTags view rendered in the Safari browser.

p2_iphoneView

(For instructions on how to set the user agent string in an Safari browser to emulate an iPhone, see How to let Safari pretend it's IE in David Alison's blog.)

In this section we've seen how to create mobile layouts and views and how to create layouts and views for specific devices such as the iPhone. In the next section you'll see how to leverage jQuery Mobile for more compelling mobile views.

Using jQuery Mobile


The jQuery Mobile library provides a user interface framework that works on all the major mobile browsers. jQuery Mobile applies progressive enhancement to mobile browsers that support CSS and JavaScript. Progressive enhancement allows all browsers to display the basic content of a web page, while allowing more powerful browsers and devices to have a richer display. The JavaScript and CSS files that are included with jQuery Mobile style many elements to fit mobile browsers without making any markup changes.

In this section you'll install the jQuery.Mobile.MVC NuGet package, which installs jQuery Mobile and a view-switcher widget.

To start, delete the Shared\_Layout.Mobile.cshtml and Shared\_Layout.iPhone.cshtml files that you created earlier.

Rename Views\Home\AllTags.Mobile.cshtml to Views\Home\AllTags.iPhone.cshtml.hide. Because the files no longer have a .cshtml extension, they won't be used by the ASP.NET MVC runtime to render the AllTags view.

Install the jQuery.Mobile.MVC NuGet package by doing this:



  1. From the Tools menu, select Package Manager Console, and then select Library Package Manager.

    p3_packageMgr



  2. In the Package Manager Console, enter Install-Package jQuery.Mobile.MVC

    p3_packageMgrConsole


Note If you get the following error:
The file C:\my_script.ps1 cannot be loaded. The execution of scripts is disabled on this system. Please see "Get-Help about_signing" for more details

See Scott Hanselman’s blog Signing PowerShell Scripts. You can run the following in a power shell script to allow signed scripts to run:

Set-ExecutionPolicy AllSigned
This command requires administrator privileges. Changes to the execution policy are recognized immediately.

The jQuery.Mobile.MVC NuGet package installs the following:


  • jQuery Mobile (jquery.mobile-1.0b3.js and the minified version jquery.mobile-1.0b3.min.js).
  • A jQuery Mobile-styled layout file (Views\Shared\_Layout.Mobile.cshtml).
  • A jQuery Mobile CSS file (jquery.mobile-1.0b3.css and the minified version jquery.mobile-1.0b3.min.css)
  • Several .png image files in the Content\images folder.
  • A view-switcher partial view (MvcMobile\Views\Shared\_ViewSwitcher.cshtml) that provides a link at the top of each page to switch from desktop view to mobile view and vice versa.
  • A ViewSwitcher controller widget (Controllers\ViewSwitcherController.cs).
  • jQuery.Mobile.MVC.dll, a DLL that provides view context extensions used to determine if view overrides exist.

The installation process also upgrades jQuery from version 1.62 to 1.63. The starter application uses jQuery 1.63. If you create a new ASP.NET MVC project, you'll have to manually change the script references from jQuery version 1.62 to 1.63 in the layout file.

Note Verify that the jQuery and jQuery Mobile version numbers in the layout file match the version numbers in your project. If the NuGet package updates a new ASP.NET MVC 4 project you create, you will have to change MvcMobile\Views\Shared\_Layout.Mobile.cshtml to reference 1.6.3 instead of 1.6.2.

Open the MvcMobile\Views\Shared\_Layout.Mobile.cshtml file and add the following markup directly after the Html.Partial call:

<div data-role="header" align="center">
    @Html.ActionLink("Home", "Index", "Home")
    @Html.ActionLink("Date", "AllDates")
    @Html.ActionLink("Speaker", "AllSpeakers")
    @Html.ActionLink("Tag", "AllTags")
</div>

The complete body section looks like this:

<body>
    <div data-role="page" data-theme="a">
        @Html.Partial("_ViewSwitcher")
        <div data-role="header" align="center">
            @Html.ActionLink("Home", "Index", "Home")
            @Html.ActionLink("Date", "AllDates")
            @Html.ActionLink("Speaker", "AllSpeakers")
            @Html.ActionLink("Tag", "AllTags")
        </div>
        <div data-role="header">
            <h1>@ViewBag.Title</h1>
        </div>
        <div data-role="content">
            @RenderSection("featured", false)
            @RenderBody()
        </div>
    </div>
</body>

Build the application, and in your mobile browser emulator browse to the AllTags view. You see the following:

p3_afterNuGet

Note If your mobile browser doesn't display the Home, Speaker, Tag, and Date links as buttons, the reference to the jQuery Mobile script file is probably not correct. Verify that the jQuery Mobile file version referenced in the mobile layout file matches the version in the Scripts folder.

In addition to the style changes, you see Displaying mobile view and a link that lets you switch from mobile view to desktop view. Choose the Desktop view link, and the desktop view is displayed.

p3_desktopView

The desktop view doesn't provide a way to directly navigate back to the mobile view. You'll fix that now. Open the Views\Shared\_Layout.cshtml file. Just under the page div element, add the following code, which renders the view-switcher widget:

@Html.Partial("_ViewSwitcher")

Here's the completed code:

<body>
    <div class="page">
        @Html.Partial("_ViewSwitcher")
        <div id="header">
          
        @*Items removed for clarity.*@
        </div>
    </div>
</body>

Refresh the AllTags view is the mobile browser. You can now navigate between desktop and mobile views.

p3_desktopViewWithMobileLink

Browse to the AllTags page in a desktop browser. The view-switcher widget is not displayed in a desktop browser because it's added only to the mobile layout page. Later in the tutorial you'll see how you can add the view-switcher widget to the desktop view.

p3_desktopBrowser

Improving the Speakers List


In the mobile browser, select the Speakers link. Because there's no mobile view(AllSpeakers.Mobile.cshtml), the default speakers display (AllSpeakers.cshtml) is rendered using the mobile layout view (_Layout.Mobile.cshtml).

p3_speakersDeskTop

You can globally disable a default (non-mobile) view from rendering inside a mobile layout by setting RequireConsistentDisplayMode to true in the Views\_ViewStart.cshtml file, like this:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    DisplayModes.RequireConsistentDisplayMode = true;
}

When RequireConsistentDisplayMode is set to true, the mobile layout (_Layout.Mobile.cshtml) is used only for mobile views. (That is, the view file is of the form ViewName.Mobile.cshtml.) You might want to set RequireConsistentDisplayMode to true if your mobile layout doesn't work well with your non-mobile views. The screenshot below shows how the Speakers page renders when RequireConsistentDisplayMode is set to true.

p3_speakersConsistent

You can disable consistent display mode in a view by setting RequireConsistentDisplayMode to false in the view file. The following markup in the Views\Home\AllSpeakers.cshtml file sets RequireConsistentDisplayMode to false:

@model IEnumerable<string>

@{
    ViewBag.Title = "All speakers";
    DisplayModes.RequireConsistentDisplayMode = false;
}

Creating a Mobile Speakers View


As you just saw, the Speakers view is readable, but the links are small and are difficult to tap on a mobile device. In this section, you'll create a mobile-specific Speakers view that looks like a modern mobile application — it displays large, easy-to-tap links and contains a search box to quickly find speakers.

Copy AllSpeakers.cshtml to AllSpeakers.Mobile.cshtml. Open the AllSpeakers.Mobile.cshtml file and remove the <h2> heading element.

In the <ul> tag, add the data-role attribute and set its value to listview. Like other data-* attributes, data-role="listview" makes the large list items easier to tap. This is what the completed markup looks like:

@model IEnumerable<string>

@{
    ViewBag.Title = "All speakers";
}
<ul data-role="listview">
    @foreach(var speaker in Model) {
        <li>@Html.ActionLink(speaker, "SessionsBySpeaker", new { speaker })</li>
    }
</ul>

Refresh the mobile browser. The updated view looks like this:

p3_updatedSpeakerView1

Although the mobile view has improved, it's difficult to navigate the long list of speakers. To fix this, in the <ul> tag, add the data-filter attribute and set it to true. The code below shows the ul markup.

<ul data-role="listview" data-filter="true">

The following image shows the search filter box at the top of the page that results from the data-filter attribute.

ps_Data_Filter

As you type each letter in the search box, jQuery Mobile filters the displayed list as shown in the image below.

ps_data_filter_SC

Improving the Tags List


Like the default Speakers view, the Tags view is readable, but the links are small and difficult to tap on a mobile device. In this section, you'll fix the Tags view the same way you fixed the Speakers view.

Rename the Views\Home\AllTags.Mobile.cshtml.hide file to the Views\Home\AllTags.Mobile.cshtml. Open the renamed file and remove the <h2> element.

Add the data-role and data-filter attributes to the <ul> tag, as shown here:

<ul data-role="listview" data-filter="true">

The image below shows the tags page filtering on the letter J.

p3_tags_J

Improving the Dates List


You can improve the Dates view like you improved the Speakers and Tags views, so that it's easier to use on a mobile device.

Copy the Views\Home\AllDates.Mobile.cshtml file to Views\Home\AllDates.Mobile.cshtml. Open the new file and remove the <h2> element.

Add data-role="listview" to the <ul> tag, like this:

<ul data-role="listview">

The image below shows what the Date page looks like with the data-role attribute in place.

p3_dates1

Replace the contents of the Views\Home\AllDates.Mobile.cshtml file with the following code:

@model IEnumerable<DateTime>
@{
    ViewBag.Title = "All dates";
    DateTime lastDay = default(DateTime);
}
<ul data-role="listview">
    @foreach(var date in Model) {
        if (date.Date != lastDay) {
            lastDay = date.Date;
            <li data-role="list-divider">@date.Date.ToString("ddd, MMM dd")</li>
        }
        <li>@Html.ActionLink(date.ToString("h:mm tt"), "SessionsByDate", new { date })</li>
    }
</ul>

This code groups all sessions by days. It creates a list divider for each new day, and it lists all the sessions for each day under a divider. Here's what it looks like when this code runs:

p3_dates2

Improving the SessionsTable View


In this section, you'll create a mobile-specific view of sessions. The changes we make will be more extensive than in other views we have created.

In the mobile browser, tap the Speaker button, then enter Sc in the search box.

ps_data_filter_SC

Tap the Scott Hanselman link.

p3_scottHa

As you can see, the display is difficult to read on a mobile browser. The date column is hard to read and the tags column is out of the view. To fix this, copy Views\Home\SessionsTable.cshtml to Views\Home\SessionsTable.Mobile.cshtml, and then replace the contents of the file with the following code:

@using MvcMobile.Models
@model IEnumerable<Session>

<ul data-role="listview">
    @foreach(var session in Model) {
        <li>
            <a href="@Url.Action("SessionByCode", new { session.Code })">
                <h3>@session.Title</h3>
                <p><strong>@string.Join(", ", session.Speakers)</strong></p>
                <p>@session.DateText</p>
            </a>
        </li>                                          
    }   
</ul>

The code removes the room and tags columns, and formats the title, speaker, and date vertically, so that all this information is readable on a mobile browser. The image below reflects the code changes.

ps_SessionsByScottHa

Improving the SessionByCode View


Finally, you'll create a mobile-specific view of the SessionByCode view. In the mobile browser, tap the Speaker button, then enter Sc in the search box.

ps_data_filter_SC

Tap the Scott Hanselman link. Scott Hanselman's sessions are displayed.

ps_SessionsByScottHa

Choose the An Overview of the MS Web Stack of Love link.

ps_love

The default desktop view is fine, but you can improve it.

Copy the Views\Home\SessionByCode.cshtml to Views\Home\SessionByCode.Mobile.cshtml and replace the contents of the Views\Home\SessionByCode.Mobile.cshtml file with the following markup:

@model MvcMobile.Models.Session

@{
    ViewBag.Title = "Session details";
}
<h2>@Model.Title</h2>
<p>
    <strong>@Model.DateText</strong> in <strong>@Model.Room</strong>
</p>

<ul data-role="listview" data-inset="true">
    <li data-role="list-divider">Speakers</li>
    @foreach (var speaker in Model.Speakers) {
        <li>@Html.ActionLink(speaker, "SessionsBySpeaker", new { speaker })</li>
    }
</ul>

<p>@Model.Description</p>
<h4>Code: @Model.Code</h4>

<ul data-role="listview" data-inset="true">
    <li data-role="list-divider">Tags</li>
    @foreach (var tag in Model.Tags) {
        <li>@Html.ActionLink(tag, "SessionsByTag", new { tag })</li>
    }
</ul>

The new markup uses the data-role attribute to improve the layout of the view.

Refresh the mobile browser. The following image reflects the code changes that you just made:

p3_love2

Wrapup and Review


This tutorial has introduced the new mobile features of ASP.NET MVC 4 Developer Preview. The mobile features include:


  • The ability to override layout, views, and partial views, both globally and for an individual view.
  • Control over layout and partial override enforcement using the RequireConsistentDisplayMode property.
  • A view-switcher widget for mobile views than can also be displayed in desktop views.
  • Support for supporting specific browsers, such as the iPhone browser.

ASP.NET MVC 4 Release Notes

Installation Notes

ASP.NET MVC 4 Release Candidate for Visual Studio 2010 can be installed from the ASP.NET MVC 4 home page using the Web Platform Installer.

We recommend uninstalling any previously installed previews of ASP.NET MVC 4 prior to installing ASP.NET MVC 4 Release Candidate. You can upgrade the ASP.NET MVC 4 Developer Preview and Beta to ASP.NET MVC 4 Release Candidate without uninstalling.

This release is not compatible with the .NET Framework 4.5 Developer Preview or Beta. You must separately upgrade the .NET 4.5 Developer Preview and the .NET 4.5 Beta to .NET 4.5 Release Candidate when installing the ASP.NET MVC 4 Release Candidate. The .NET Framework 4.5 RC can be downloaded at http://go.microsoft.com/fwlink/?LinkId=251397

ASP.NET MVC 4 can be installed and run side-by-side with ASP.NET MVC 3.

Documentation

Documentation for ASP.NET MVC is available on the MSDN website at the following URL:

http://go.microsoft.com/fwlink/?LinkID=243043

Tutorials and other information about ASP.NET MVC are available on the MVC 4 page of the ASP.NET website (http://www.asp.net/mvc/mvc4).

Support

This is a preview release and is not officially supported. If you have questions about working with this release, post them to the ASP.NET MVC forum (http://forums.asp.net/1146.aspx), where members of the ASP.NET community are frequently able to provide informal support.

Software Requirements

The ASP.NET MVC 4 components for Visual Studio require PowerShell 2.0 and either Visual Studio 2010 with Service Pack 1 or Visual Web Developer Express 2010 with Service Pack 1.

New Features in ASP.NET MVC 4 Release Candidate

This section describes features that have been introduced in the ASP.NET MVC 4 Release Candidate release.

ASP.NET Web API

ASP.NET MVC 4 includes ASP.NET Web API, a new framework for creating HTTP services that can reach a broad range of clients including browsers and mobile devices. ASP.NET Web API is also an ideal platform for building RESTful services.

ASP.NET Web API includes support for the following features:

  • Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a new, strongly typed HTTP object model. The same programming model and HTTP pipeline is symmetrically available on the client through the new HttpClient type.
  • Full support for routes: ASP.NET Web API supports the full set of route capabilities of ASP.NET Routing, including route parameters and constraints. Additionally, use simple conventions to map actions to HTTP methods.
  • Content negotiation: The client and server can work together to determine the right format for data being returned from a web API. ASP.NET Web API provides default support for XML, JSON, and Form URL-encoded formats and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy.
  • Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by the Web API actions. Validation is also performed on action parameters based on data annotations.
  • Filters: ASP.NET Web API supports filters including well-known filters such as the [Authorize] attribute. You can author and plug in your own filters for actions, authorization and exception handling.
  • Query composition: Use the [Queryable] filter attribute on an action that returns IQueryable to enable support for querying your web API via the OData query conventions.
  • Improved testability: Rather than setting HTTP details in static context objects, web API actions work with instances of HttpRequestMessage and HttpResponseMessage. Create a unit test project along with your Web API project to get started quickly writing unit tests for your Web API functionality.
  • Code-based configuration: ASP.NET Web API configuration is accomplished solely through code, leaving your config files clean. Use the provide service locator pattern to configure extensibility points.
  • Improved support for Inversion of Control (IoC) containers: ASP.NET Web API provides great support for IoC containers through an improved dependency resolver abstraction
  • Self-host: Web APIs can be hosted in your own process in addition to IIS while still using the full power of routes and other features of Web API.
  • Create custom help and test pages: You now can easily build custom help and test pages for your web APIs by using the new IApiExplorer service to get a complete runtime description of your web APIs.
  • Monitoring and diagnostics: ASP.NET Web API now provides light weight tracing infrastructure that makes it easy to integrate with existing logging solutions such as System.Diagnostics, ETW and third party logging frameworks. You can enable tracing by providing an ITraceWriter implementation and adding it to your web API configuration.
  • Link generation: Use the ASP.NET Web API UrlHelper to generate links to related resources in the same application.
  • Web API project template: Select the new Web API project form the New MVC 4 Project wizard to quickly get up and running with ASP.NET Web API.
  • Scaffolding: Use the Add Controller dialog to quickly scaffold a web API controller based on an Entity Framework based model type.

For more details on ASP.NET Web API please visit http://www.asp.net/web-api.

Enhancements to Default Project Templates

The template that is used to create new ASP.NET MVC 4 projects has been updated to create a more modern-looking website:

In addition to cosmetic improvements, there’s improved functionality in the new template. The template employs a technique called adaptive rendering to look good in both desktop browsers and mobile browsers without any customization.

To see adaptive rendering in action, you can use a mobile emulator or just try resizing the desktop browser window to be smaller. When the browser window gets small enough, the layout of the page will change.

Mobile Project Template

If you’re starting a new project and want to create a site specifically for mobile and tablet browsers, you can use the new Mobile Application project template. This is based on jQuery Mobile, an open-source library for building touch-optimized UI:

This template contains the same application structure as the Internet Application template (and the controller code is virtually identical), but it's styled using jQuery Mobile to look good and behave well on touch-based mobile devices. To learn more about how to structure and style mobile UI, see the jQuery Mobile project website.

If you already have a desktop-oriented site that you want to add mobile-optimized views to, or if you want to create a single site that serves differently styled views to desktop and mobile browsers, you can use the new Display Modes feature. (See the next section.)

Display Modes

The new Display Modes feature lets an application select views depending on the browser that's making the request. For example, if a desktop browser requests the Home page, the application might use the Views\Home\Index.cshtml template. If a mobile browser requests the Home page, the application might return the Views\Home\Index.mobile.cshtml template.

Layouts and partials can also be overridden for particular browser types. For example:

  • If your Views\Shared folder contains both the _Layout.cshtml and _Layout.mobile.cshtml templates, by default the application will use _Layout.mobile.cshtml during requests from mobile browsers and _Layout.cshtml during other requests.
  • If a folder contains both _MyPartial.cshtml and _MyPartial.mobile.cshtml, the instruction @Html.Partial("_MyPartial") will render _MyPartial.mobile.cshtml during requests from mobile browsers, and _MyPartial.cshtml during other requests.

If you want to create more specific views, layouts, or partial views for other devices, you can register a new DefaultDisplayMode instance to specify which name to search for when a request satisfies particular conditions. For example, you could add the following code to the Application_Start method in the Global.asax file to register the string "iPhone" as a display mode that applies when the Apple iPhone browser makes a request:

DisplayModeProvider.Instance.Modes.Insert(0, new
DefaultDisplayMode("iPhone")
{
    ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf
        ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});

After this code runs, when an Apple iPhone browser makes a request, your application will use the Views\Shared\_Layout.iPhone.cshtml layout (if it exists).

jQuery Mobile, the View Switcher, and Browser Overriding


jQuery Mobile is an open source library for building touch-optimized web UI. If you want to use jQuery Mobile with an ASP.NET MVC 4 application, you can download and install a NuGet package that helps you get started. To install it from the Visual Studio Package Manager Console, type the following command:

Install-Package jQuery.Mobile.MVC -Pre

This installs jQuery Mobile and some helper files, including the following:

  • Views/Shared/_Layout.Mobile.cshtml, which is a jQuery Mobile-based layout.
  • A view-switcher component, which consists of the Views/Shared/_ViewSwitcher.cshtml partial view and the ViewSwitcherController.cs controller.

    After you install the package, run your application using a mobile browser (or equivalent, like the Firefox User Agent Switcher add-on). You'll see that your pages look quite different, because jQuery Mobile handles layout and styling. To take advantage of this, you can do the following:


  • Create mobile-specific view overrides as described under Display Modes earlier (for example, create Views\Home\Index.mobile.cshtml to override Views\Home\Index.cshtml for mobile browsers).
  • Read the jQuery Mobile documentation to learn more about how to add touch-optimized UI elements in mobile views.

    A convention for mobile-optimized web pages is to add a link whose text is something like Desktop view or Full site mode that lets users switch to a desktop version of the page. The jQuery.Mobile.MVC package includes a sample view-switcher component for this purpose. It's used in the default Views\Shared\_Layout.Mobile.cshtml view, and it looks like this when the page is rendered:


    If visitors click the link, they’re switched to the desktop version of the same page.

    Because your desktop layout will not include a view switcher by default, visitors won't have a way to get to mobile mode. To enable this, add the following reference to _ViewSwitcher to your desktop layout, just inside the <body> element:

    <body>
        @Html.Partial("_ViewSwitcher")
        ...

    The view switcher uses a new feature called Browser Overriding. This feature lets your application treat requests as if they were coming from a different browser (user agent) than the one they're actually from. The following table lists the methods that Browser Overriding provides.

    HttpContext.SetOverriddenBrowser(userAgentString)

    Overrides the request's actual user agent value using the specified user agent.

    HttpContext.GetOverriddenUserAgent()

    Returns the request's user agent override value, or the actual user agent string if no override has been specified.

    HttpContext.GetOverriddenBrowser()

    Returns an HttpBrowserCapabilitiesBase instance that corresponds to the user agent currently set for the request (actual or overridden). You can use this value to get properties such as IsMobileDevice.

    HttpContext.ClearOverriddenBrowser()

    Removes any overridden user agent for the current request.

    Browser Overriding is a core feature of ASP.NET MVC 4 and is available even if you don't install the jQuery.Mobile.MVC package. However, it affects only view, layout, and partial-view selection — it does not affect any other ASP.NET feature that depends on the Request.Browser object.

    By default, the user-agent override is stored using a cookie. If you want to store the override elsewhere (for example, in a database), you can replace the default provider (BrowserOverrideStores.Current). Documentation for this provider will be available to accompany a later release of ASP.NET MVC.

    Task Support for Asynchronous Controllers


    You can now write asynchronous action methods as single methods that return an object of type Task or Task<ActionResult>.

    For example, if you're using Visual C# 5 (or using the Async CTP), you can create an asynchronous action method that looks like the following:

    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()
        });
    }

    In the previous action method, the calls to newsService.GetHeadlinesAsync and sportsService.GetScoresAsync are called asynchronously and do not block a thread from the thread pool.

    Asynchronous action methods that return Task instances can also support timeouts. To make your action method cancellable, add a parameter of type CancellationToken to the action method signature. The following example shows an asynchronous action method that has a timeout of 2500 milliseconds and that displays a TimedOut view to the client if a timeout occurs.

    [AsyncTimeout(2500)]
    [HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]
    public async Task<ActionResult> Index(string city,
        CancellationToken cancellationToken) {
        var newsService = new NewsService();
        var sportsService = new SportsService();
      
        return View("Common",
            new PortalViewModel {
            NewsHeadlines = await newsService.GetHeadlinesAsync(cancellationToken),
            SportsScores = await sportsService.GetScoresAsync(cancellationToken)
        });
    }

    Azure SDK


    ASP.NET MVC 4 Release Candidate supports the 1.6 release of the Windows Azure SDK.

    Database Migrations


    ASP.NET MVC 4 projects now include Entity Framework 5.0 RC. One of the great features in Entity Framework 5.0 is support for database migrations. This feature enables you to easily evolve your database schema using a code-focused migration while preserving the data in the database.

    Empty Project Template


    The MVC Empty project template is now truly empty so that you can start from a completely clean slate. The earlier version of the Empty project template has been renamed to Basic.

    Add Controller to any project folder


    You can now right click and select Add Controller from any folder in your MVC project. This gives you more flexibility to organize your controllers however you want, including keeping your MVC and Web API controllers in separate folders.

    Bundling and Minification


    The bundling and minification framework enables you to reduce the number of HTTP requests that a Web page needs to make by combining individual files into a single, bundled file for scripts and CSS. It can then reduce the overall size of those requests by minifying the contents of the bundle. Minifying can include activities like eliminating whitespace to shortening variable names to even collapsing CSS selectors based on their semantics. Bundles are declared and configured in code and are easily referenced in views via helper methods which can generate either a single link to the bundle or, when debugging, multiple links to the individual contents of the bundle.

    Upgrading an ASP.NET MVC 3 Project to ASP.NET MVC 4


    ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 3 application to ASP.NET MVC 4.

    The simplest way to upgrade is to create a new ASP.NET MVC 4 project and copy all the views, controllers, code, and content files from the existing MVC 3 project to the new project and then to update the assembly references in the new project to match the old project. If you have made changes to the Web.config file in the MVC 3 project, you must also merge those changes into the Web.config file in the MVC 4 project.

    To manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:


    1. In all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):
      System.Web.Mvc, Version=3.0.0.0
      System.Web.WebPages, Version=1.0.0.0
      System.Web.Helpers, Version=1.0.0.0
      System.Web.WebPages.Razor, Version=1.0.0.0

      with the following corresponding text:

      System.Web.Mvc, Version=4.0.0.0
      System.Web.WebPages, Version=2.0.0.0
      System.Web.Helpers, Version=2.0.0.0,
      System.Web.WebPages.Razor, Version=2.0.0.0,

    2. In the root Web.config file, update the webPages:Version element to "2.0.0.0" and add a new PreserveLoginUrl key that has the value "true":
      <appSettings>
        <add key="webpages:Version" value="2.0.0.0" />
        <add key="PreserveLoginUrl" value="true" />
      </appSettings>

    3. In Solution Explorer, right-click on the References and select Manage NuGet Packages. Search for Microsoft.AspNet.Mvc and install the Microsoft ASP.NET MVC 4 (RC) package. Click OK.
    4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.
    5. Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.
    6. Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.
    7. If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:
      <configuration>
        <!--... elements deleted for clarity ...-->
       
        <runtime>
          <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
              <assemblyIdentity name="System.Web.Helpers"
                   publicKeyToken="31bf3856ad364e35" />
              <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
              <assemblyIdentity name="System.Web.Mvc"
                   publicKeyToken="31bf3856ad364e35" />
              <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
              <assemblyIdentity name="System.Web.WebPages"
                   publicKeyToken="31bf3856ad364e35" />
              <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
            </dependentAssembly>
          </assemblyBinding>
        </runtime>
      </configuration>

    Changes from ASP.NET MVC 4 Beta


    The release notes for ASP.NET MVC 4 Beta can be found here: http://go.microsoft.com/fwlink/?LinkID=238227

    The major changes from ASP.NET MVC 4 Beta in this release are summarized below:


    • Removed ASP.NET Single Page Application: ASP.NET Single Page Application (SPA) shipped with ASP.NET MVC 4 Beta as an early preview of the experience for building applications that include significant client-side interactions using JavaScript. SPA won’t ship with the final MVC 4 release, but will continue to evolve outside of the MVC 4 release. Check out the ASP.NET SPA home page for details.
    • ASP.NET Web API now uses Json.NET for JSON formatting: The default JSON formatter in ASP.NET Web API now uses Json.NET for JSON serialization. Json.NET provides the flexibility and performance required for a modern web framework.
    • Formatter improvements: The methods on MediaTypeFormatter are now public to enable unit testing of custom formatters. A single formatter can now support multiple text encodings. Use BufferedMediaTypeFormatter to implement simple synchronous formatting support. FormatterContext has been removed. To get access to the request from a formatter on the server implement GetPerRequestFormatterInstance.
    • Removed System.Json.dll: Because of the overlap with functionality already in Json.NET the System.Json.dll assembly has been removed.
    • XmlMediaTypeFormatter uses DataContractSerializer by default: The XmlMediaTypeFormatter now uses the DataContractSerializer by default. This means that by default ASP.NET Web API will use the Data Contract programming model for formatting types. You can configure the XmlMediaTypeFormatter to use the XmlSerializer by setting UseXmlSerializer to true.
    • Removed Ajax grid controller template: The Ajax grid controller template was removed to simplify and cleanup the list of available controller templates
    • Formatters now always handle the body content: ASP.NET Web API formatters are now used consistently for handling both the request and response content. We have removed IRequestContentReadPolicy. The FormUrlEncodedMediaTypeFormatter class has been updated to use MVC-style model binding, so you can still use model binding infrastructure for handling form data in the request body.
    • HTTP content negotiation decoupled from ObjectContent: Previously in ASP.NET Web API all HTTP content negotiation logic was encapsulated in ObjectContent, which made it difficult to predict when HTTP content negotiation would occur. We have decoupled HTTP content negotiation from ObjectContent and encapsulated it as an IContentNegotiator implementation. ObjectContent now takes a single formatter. You can run HTTP content negotiation whenever you want using the DefaultContentNegotiator implementation to select an appropriate formatter. IFormatterSelector has been removed
    • Removed HttpRequestMessage<T> and HttpResponseMessage<T>: Previously there were two ways to specify a request or response with an ObjectContent instance: you could provide an ObjectContent instance directly, or you could use HttpRequestMessage<T> or HttpResponseMessage<T>. Having two ways of doing the same thing complicated request and response handling, so HttpRequestMessage<T> and HttpResponseMessage<T> have been removed. To create content negotiated responses that contain an ObjectContent use the CreateResponse<T> extension methods on the request message. To send a request that contains an ObjectContent use the PostAsync<T> extension methods on HttpClient. Or, use the PostAsJsonAsync<T> and PostAsXmlAsync<T> extension methods to specify a request that will be specifically formatted with as JSON or XML respectively.
    • Simplified action parameter binding: You can now predictably determine whether an action parameter will be bound to the request body. This ensures that the request stream is not unnecessarily consumed. Parameters with simple types by default come from the URL. Parameters with complex types by default come from the body. There can be only one body parameter. You can explicitly specify if a parameter comes from the URL or from the body using the [FromUri] and [FromBody] attributes.
    • Query composition is now implemented as a reusable filter: Previously support for query composition was hard coded into the runtime. Query composition is now implemented as a reusable filter that can be applied as an attribute ([Queryable]) to any action that returns an IQueryable instance. This attribute is now required to enable query composition.
    • Cookies: The HttpRequestMessage and HttpResponseMessage classes expose the HTTP Cookie and Set-Cookie headers as raw strings and not structured classes. This made it cumbersome and error prone to work with cookies in ASP.NET Web API. To fix this we introduced two new CookieHeaderValue and CookieState that follow RFC 6265 HTTP State Management Mechanism. You can use the AddCookies extension method to add a Set-Cookie header to a response message. Use the GetCookies extension method to get all of the CookieHeaderValues from a request.
    • HttpMessageInvoker: The HttpMessageInvoker provides a light weight mechanism to invoke an HttpMessageHandler without the overhead of using HttpClient. Use HttpMessageInvoker for unit testing message handlers and also for invoking message handlers on the server.
    • Response buffering improvements: When web-hosting a web API the response content length is now set intelligently so that responses are not always chunked. Buffering also enables reasonable error messages to be returned when exceptions occur in formatters.
    • Independently control IHttpController selection and activation: Implement the IHttpControllerSelector to control IHttpController selection. Implement IHttpControllerActivator to control IHttpController activation. The IHttpControllerFactory abstraction has been removed.
    • Clearer integration with IoC containers that support scopes: The dependency resolver for ASP.NET Web API now supports creating dependency scopes that can be independently disposed. A dependency scope is created for each request and is used for controller activation. Configuring dependency resolution (i.e. HttpConfiguration.DependencyResolver) is optional and is now configured separately from the default services used by ASP.NET Web API (HttpConfiguration.Services). However, the service locator consults the dependency resolver first for required services and then falls back to explicitly configured services.
    • Improved link generation: The ASP.NET Web API UrlHelper how has convenience methods for generating links based on the configured routes and the request URI.
    • Register resource for disposal at the end of the request life-time: Use the RegisterForDispose extension method on the request to register an IDisposable instance that should be disposed when the request is disposed.
    • Monitoring and diagnostics: You can enable tracing by providing an ITraceWriter implementation and configuring it as a service using the dependency resolver. The ILogger interface has been removed.
    • Create custom help and test pages: You now can easily build custom help and test pages for your web APIs by using the new IApiExplorer service to get a complete runtime description of your web APIs.
    • Entity Framework based scaffolding for web APIs: Use the Add Controller dialog to quickly scaffold a web API controller based on an Entity Framework based model type.
    • Create unit test projects for Web API projects: You can now easily create a unit test project for a Web API project using the New ASP.NET MVC 4 Project dialog box.
    • Unauthorized requests handled by ASP.NET Web API return 401 Unauthroized: Unauthorized requests handled by ASP.NET Web API now return a standard 401 Unauthorized response instead of redirecting the user agent to a login form so that the response can be handled by an Ajax client.
    • Configuration logic for MVC applications moved under the App_Start directory: The configuration logic For MVC applications has been moved from Global.asax.cs to a set of static classes in the App_Start directory. Routes are registered in RouteConfig.cs. Global MVC filters are registered in FilterConfig.cs. Bundling and minification configuration now lives in BundleConfig.cs.
    • Support different debug and release modes for bundling and minification: Use the Styles.Render and Scripts.Render helpers from within a Razor view so that resources will not be bundled while developing and debugging, but will be bundled and minified when the application is deployed into production.
    • Explicit configuration of default bundles: All of the default bundles are now explicitly configured in BundleConfig.cs to provide greater visibility into what bundles are available and to enable more flexibility in modifying the configuration. Separate bundles are configured for different components (jQuery, jQuery UI, etc.) to enable finer grained control over which bundles are included on a page.
    • Simplified bundle configuration: Strongly typed bundle classes (ex. StyleBundler, ScriptsBundle) automatically wire up the appropriate default bundle transform class (i.e. minifier). Use method chaining to avoid the three-step process of creating, configuring and adding to a bundle. Streamline configuration code by including multiple values for bundle files and bundle transforms via a params array.
    • Entity Framework 5.0 RC: ASP.NET MVC 4 projects now include Entity Framework 5.0 RC.
    • Empty Project Template: The MVC Empty project template is now truly empty so that you can start from a completely clean slate. The earlier version of the Empty project template has been renamed to Basic.
    • Add Controller to any project folder: You can now right click and select Add Controller from any folder in your MVC project. This gives you more flexibility to organize your controllers however you want, including keeping your MVC and Web API controllers in separate folders.
    • Invoke and test HttpMessageHandlers using the new HttpMessageInvoker: HttpMessageInvokerprovides a simple and light-weight way to invoke and test any HttpMessageHandler including HttpServer instances. The public SubmitRequestAsync method on HttpServer has been removed and HttpMessageInvoker should be used instead.

    Known Issues and Breaking Changes



    • Breaking changes in the Razor View Engine. As part of a rewrite of the Razor parser, the following types were removed from System.Web.Mvc.Razor:

      • ModelSpan
      • MvcVBRazorCodeGenerator
      • MvcCSharpRazorCodeGenerator
      • MvcVBRazorCodeParser
      The following methods were also removed:

      • MvcCSharpRazorCodeParser.ParseInheritsStatement(System.Web.Razor.Parser.CodeBlockInfo)
      • MvcWebPageRazorHost.DecorateCodeGenerator(System.Web.Razor.Generator.RazorCodeGenerator)
      • MvcVBRazorCodeParser.ParseInheritsStatement(System.Web.Razor.Parser.CodeBlockInfo)

    • When WebMatrix.WebData.dll is included in in the /bin directory of an ASP.NET MVC 4 apps, it takes over the URL for forms authentication. Adding the WebMatrix.WebData.dll assembly to your application (for example, by selecting "ASP.NET Web Pages with Razor Syntax" when using the Add Deployable Dependencies dialog) will override the authentication login redirect to /account/logon rather than /account/login as expected by the default ASP.NET MVC Account Controller. To prevent this behavior and use the URL specified already in the authentication section of web.config, you can add an appSetting called PreserveLoginUrl and set it to true:
      <appSettings>
          <add key="PreserveLoginUrl" value="true"/>
      </appSettings>

    • The NuGet package manager fails to install when attempting to install ASP.NET MVC 4 for side by side installations of Visual Studio 2010 and Visual Web Developer 2010. To run Visual Studio 2010 and Visual Web Developer 2010 side by side with ASP.NET MVC 4 you must install ASP.NET MVC 4 after both versions of Visual Studio have already been installed.
    • Uninstalling ASP.NET MVC 4 fails if prerequisites have already been uninstalled. To cleanly uninstall ASP.NET MVC 4 you must uninstall ASP.NET MVC 4 prior to uninstalling Visual Studio.
    • Installing ASP.NET MVC 4 Release Candidate breaks ASP.NET MVC 3 RTM applications. ASP.NET MVC 3 applications that were created with the RTM release (not with the ASP.NET MVC 3 Tools Update release) require the following changes in order to work side-by-side with ASP.NET MVC 4 Release Candidate. Building the project without making these updates results in compilation errors.

      Required updates


      1. In the root Web.config file, add a new <appSettings> entry with the key webPages:Version and the value 1.0.0.0.
        <appSettings>
            <add key="webpages:Version" value="1.0.0.0"/>
            <add key="ClientValidationEnabled" value="true"/>
            <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
        </appSettings>

      2. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.
      3. Locate the following assembly references:
        <Reference Include="System.Web.WebPages"/> 
        <Reference Include="System.Web.Helpers" />

        Replace them with the following:

        <Reference Include="System.Web.WebPages, Version=1.0.0.0,
        Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL "/>
        <Reference Include="System.Web.Helpers, Version=1.0.0.0,
        Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />

      4. Save the changes, close the project (.csproj) file you were editing, and then right-click the project and select Reload.

    • Changing an ASP.NET MVC 4 project to target 4.0 from 4.5 does not update the EntityFramework assembly reference: If you change an ASP.NET MVC 4 project to target 4.0 after targetting 4.5 the reference to the EntityFramwork assembly will still point to the 4.5 version. To fix this issue reinstall the EntityFramework NuGet package.
    • 403 Forbidden when running an ASP.NET MVC 4 application on Azure after changing to target 4.0 from 4.5: If you change an ASP.NET MVC 4 project to target 4.0 after targetting 4.5 and then deploy to Azure you may see a 403 Forbidden error at runtime. To workaround this issue add the following to your web.config: <modules runAllManagedModulesForAllRequests="true" />
    • Visual Studio crashes when editing a .cshtml file after renaming the file. Visual Studio may crash if you rename a .cshtml file while the file is open in the editor. To work around this issue, close and reopen the .cshtml file after renaming it.
  • Wednesday, 11 July 2012

    HTC confirms another tablet coming to the UK

    HTC has kept pretty quiet on the tablet front, aside from some Windows brou-ha-ha. But according to PC Advisor, the company has plans to launch another tablet on British shores. The Flyer remains the last tablet to arrive -- due to a lack of 4G networks, the Jetstream didn't make the trip across the Atlantic. It remains a very vague tease, with no promise of a launch even within the year and not even a nod to whether the OS will be Android or something else altogether. HTC's apparently holding back until it has something unique to offer, a strategy that other companies seem to be following in a bid to avoid the pile of tablet also-rans.

    Wednesday, 4 July 2012

    Microsoft Azure Slide shares from 22nd June

    After a very successful event we had on the 22nd June. I would like to thank Scott Guthrie and the Microsoft team, Elastacloud and eSynergy Solutions for some brilliant presentations.
    I would also like to thank all those that attended the conference. It was a great success apart from the internet connection
    I have put some links below for you to review some of the slide shows from the event.
    If you need any more info please contact me on adam@esynergy-solutions.co.uk