European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Amsterdam :: Building a Northwind Single Page Application using ASP.NET MVC 4 Beta - Part 1

clock May 30, 2012 06:42 by author 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.

 

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Display Mode in ASP.NET MVC 4

clock April 6, 2012 05:09 by author 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.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: What’s New in ASP.NET MVC 4

clock April 5, 2012 09:59 by author Scott

Microsoft is ramping up the release cycles of some of its products, and the phenomenal rate at which the ASP.NET MVC framework is being updated is testament to that.

The latest version, MVC 4 Developer Preview, has some cool new additions to its armory. Over the next few weeks, I’ll be taking a look at some of the features new to the framework, and how you might use these in your website.


The more noticeable features added to the framework include:


- Mobile project templates

- Display modes
- Recipes
- Task support for Asynchronous controllers
- Azure SDK
- Bug fixes

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

Task Support for Asynchronous Controllers


The feature I’m going to be focusing on today is task support for asynchronous controllers.

Nobody likes to wait, so why should your users wait for a long-running asynchronous task? It doesn’t make sense!

Developing asynchronous controllers has been available since MVC 3, but for this to work you had to write a bunch of extra code – what I like to refer to as code noise – to get it to work.

Take the example of integrating Twitter into a webpage. In MVC 3, the code needed to follow specific rules. Instead of there being one action method, there had to be two action methods. Both were named the same, but for the method beginning the asynchronous request, you needed to append Async to the action name. For the method handling the ending of the asynchronous request, you needed to append Completed to the action name.

It’s much easier to follow if you see some code. The sample code below requests data from Twitter asynchronously.

public void SearchTwitterAsync()
{
        const string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";

        // the asynchronous operation is declared
        AsyncManager.OutstandingOperations.Increment();

        var webClient = new WebClient();
        webClient.DownloadStringCompleted += (sender, e) =>
        {
              AsyncManager.Parameters["results"] = e.Result;
              AsyncManager.OutstandingOperations.Decrement();
        };
        webClient.DownloadStringAsync(new Uri(url)); //the asynchronous process is launched
}

public ActionResult SearchTwitterCompleted(string results)
{
        // Now return the twitter results to the client
        return Json(ReadTwitterResults(results), JsonRequestBehavior.AllowGet);
}

The code above is going off to Twitter, searching for data and returning the results asynchronously. There’s a lot of code noise in there and to me, it’s violating – for want of a better word – the Don’t Repeat Yourself (DRY) principle.

Well, in MVC 4, these tasks have been rolled into one. You can now write asynchronous action methods as single methods that return an object of type Task or Task<ActionResult>.

These features are only available in MVC 4 or C# 5. Here’s the simplified code below.

public async Task<ActionResult> Search()
{
        string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
        var webClient = new WebClient();
        string xmlResult = await webClient.DownloadStringTaskAsync(url);
        return Json(ReadTwitterResults(xmlResult), JsonRequestBehavior.AllowGet);
}

The results are the same, but now you can reduce the amount of code you need to accomplish the same outcome.

Asynchronous action methods that return Task instances can also support timeouts. To set a time limit for your action method, you can use the AsyncTimeout attribute. The following example shows an asynchronous action method that has a timeout of 2500 milliseconds. Once it has timed out, the view “TimedOut” will be displayed to the user.

[AsyncTimeout(2500)]
[HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]
public async Task<ActionResult> Search()
{
        string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
        var webClient = new WebClient();
        string xmlResult = await webClient.DownloadStringTaskAsync(url);
        return Json(ReadTwitterResults(xmlResult), JsonRequestBehavior.AllowGet);
}

Nothing else has changed with asynchronous actions.

The controller still needs to derive from AsyncController, and you still access the action in the same way but you have to write less code.

Asynchronous controllers are perfect for pieces of code that run to great length. Most of the time you’ll be working with a database, so being able to make calls to the database asynchronously is a big plus for the end user.

Why should they wait?

Test drive for
NEW ASP.NET MVC 4 for FREE, please visit our site at http://www.hostforlife.eu/ASPNET-45-Beta-European-Hosting.aspx.

 



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.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in