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 5 Hosting :: Introducing ASP.Net SignalR in MVC 5

clock December 17, 2013 05:29 by author Patrick

In this article I am using the ASP.NET SignalR library in the latest MVC 5 project template. Now, what is this real-time functionality? It is used to access the server code and push the content to the connected clients instantly instead of the server waiting for the client's request.

Prerequisites

Using Visual Studio 2013. There are some prerequisites to develop the application:

  • Visual Studio 2010 SP1 or Visual Studio 2012.
  • ASP.NET and Web Tools 2012.2

Let's create an application for SignalR development using the following sections:

  • MVC 5 Application
  • Code Execution

MVC 5 Application

Step 1: Open Visual Studio 2013 and create a New Project.

Step 2: Select MVC project template.

Step 3: Open the Package Manager Console.

And write the following command:

install-package Microsoft.AspNet.SignalR

Step 4: You can see in your Solution Explorer that the SignalR was successfully added to your application.

Step 5: Add a new folder named Hubs in your application and add a class in it.

Give the name of your class ChatHub as shown below:

Step 6: Add the following code in the class:

using Microsoft.AspNet.SignalR;
namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public void  LetsChat(string Cl_Name, string Cl_Message)
        {
            Clients.All.NewMessage(Cl_Name, Cl_Message);
        }
    }
}
Step 7: Open the Global.asax file and modify the Applicatio_Start() method as shown below:
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        RouteTable.Routes.MapHubs();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

Step 8:
Open your HomeController.cs file and modify it as shown below:
public ActionResult Contact()
{
    ViewBag.Message = "Your contact page."
    return View();
}
public ActionResult Chat()
{
    ViewBag.Message = "Your chat page";
    return View();
}

Step 9: Generate the view for the Chat method as shown in the following parts:

Select Home folder and right-click to add Scaffold

(m8)

Select MVC 5 View in the Add Scaffold wizard

Do as directed in the following image:

Step 10: Add the following code in the Chat.cshtml file:
@{
    ViewBag.Title = "Chat";
}
<hgroup>
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
</hgroup>
<div class="container">
    <input type="text" id="TxtMessage" />
    <input type="button" id="BtnSend" value="Send" />
    <input type="hidden" id="UserName" />
    <ul id="Chats"></ul>
</div>
@section scripts {
    <script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
    <script src="~/signalr/Hubs"></script>
    <script
        $(function () {
            var chat = $.connection.chatHub;
            chat.client.NewMessage=function(Cl_Name, Cl_Message) {
                $('#Chats').append('<li><strong>' + htmlEncode(Cl_Name)
                    + '</strong>: ' + htmlEncode(Cl_Message) + '</li>');
            };
            $('#UserName').val(prompt('Please Enter Your Name:', ''));
            $('#TxtMessage').focus();
            $.connection.hub.start().done(function () {
                $('#BtnSend').click(function () {
                    chat.server.LetsChat($('#UserName').val(), $('#TxtMessage').val())
                    $('#TxtMessage').val('').focus()
                });
            });
        });
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

Code Execution

Save all your application and debug the application. Use the following procedure.

Step 1: Debug your application. Open /Home/Chat in your browser like: http://localhost:12345/Home/Chat
Step 2: Enter your name in the prompt
Step 3: Enter message and send
Step 4: Copy the browser URL and open more browsers, paste the URL in the address bar and do the same thing as above.



European ASP.NET MVC 5 Hosting :: Getting Started With Areas in MVC 5

clock December 12, 2013 09:51 by author Patrick

MVC (Model, View, Controller) is a design pattern to separate the data logic from the business and presentation logic. We can also design the structure physically, where we can keap the logic in the controllers and views to exemplify the relationships.

It is also possible that we can have large projects that use MVC, then we need to split the application into smaller units called areas that isolate the larger MVC application into smaller functional groupings. A MVC application could contain several MVC structures (areas).  

How to creating a simple application for defining the area in MVC 5. MVC 5 is the latest version of MVC used in Visual Studio 2013?

You need to have the following to complete this article:

  • MVC 5
  • Visual Studio 2013

In that context, we'll follow the sections given below:MVC 5 application:

  • Adding Controller for Area
  • Adding Views for Area
  • Area Registration
  • Application Execution
  • MVC 5 Application

Use the following procedure to create a Web application based on a MVC 5 template.

Step 1: Open Visual Studio 2013.
Step 2: Create an ASP.NET Web Application with MVC 5 project template.

Step 3: In Solution Explorer, right-click on the project and click "Add" to add an area as shown below:

Step 4: Enter the name for the area, such as "News".

Step 5: Similarly add an another area named "Article".

Now from the steps above you have added two areas for your application named News and Article.

Adding Controller for Area

We have successfully added an area, now we'll add controllers for each of our areas using the following procedure.

Step 1: Right-click on the Controller in your Article area to add a controller.

Step 2: Select "MVC 5 Empty Controller".

Step 3: Enter the name as "ArticleController" .

Step 4: Similarly add the controller for "News".

Now your Area folder should be as in the following screenshot:

Adding Views for Area

We have successfully added a controller for our area, now to add a view for the area using the following procedure.

Step 1: Right-click on the "News" folder in the View to add a View for the News Area.

Step 2: Enter the view name as defined in the NewsController.

Step 3: Generate some content in the View of News as in the following screenshot:

Step 4: You can also add a view as shown in the following screenshot:

Step 5: Generate some content for the Article view.

Area Registration

Step 1: Open the "Global.asax" file.

Step 2: Add the following code in your Application_Start() method:

AreaRegistration.RegisterAllAreas();

Application Execution

Step 1: Open the project view Layout file.

Step 2: Modify the <ul> in the layout file as shown in the following code:

<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("Article", "Index", "Article", new {area= "Article" }, null)</li>
<li>@Html.ActionLink("News", "Index", "News", new { area = "News" }, null)</li>
</ul>

Step 3: Debug the application, and finish!



European ASP.NET MVC 4 Hosting :: Single Page Application in ASP.NET MVC 4

clock December 5, 2013 11:20 by author Scott

Single Page Applications (SPA)?

Normally a web application is a collection of web pages, each doing a specific task. For example, consider a web application that does CRUD operations (Create, Read, Update and Delete) on data. A common practice is to create different web pages for operations such as showing a list of existing records, adding a new record, updating an existing record and deleting a record. A trend becoming increasingly popular is to have a single web page perform all of these operations. Such an application is called Single Page Application or SPA. So, in this example instead of developing four separate web pages you develop just one web page. At runtime, depending on the operation selected by a user, the web page renders an appropriate user interface. Such an application heavily relies on client side JavaScript libraries.

It should be noted that SPA is a general concept and ASP.NET MVC 4 has decided to offer some basic infrastructure to the developers to put this concept into practice. ASP.NET MVC 4 provides a project template that creates a basic yet functional SPA application. You can then customize the application to add more functionality. In the discussion that follows you will learn SPA with respect to ASP.NET MVC 4.

Parts of SPA

A Single Page Application consists of several pieces that fit together to provide the overall functionality of the application. A typical SPA consists of the following pieces:

  • Data Model : This is a server side piece that represents your data (often mapping database tables as .NET objects).
  • Data Service : Data service provides operations for database access (typically CRUD operations). This is also a service side piece and uses Entity Framework Code First approach.
  • ViewModel : View Model refers to your data and UI level operations that you wish to perform on the data. You can think of View Model as a wrapper over your model data that adds UI level operations to it.
  • Views : Views display your data to the user and also contain associated JavaScript. The default SPA project template uses Razor views.
  • Database: SPA uses Entity Framework Code First approach for database operations. The default project template creates a database in the local installation of SQL Server Express.

The following sections discuss all these parts from the default SPA project template in detail.

Creating a New Project Based on SPA Template

Installing ASP.NET MVC 4 adds a new project template in Visual Studio 2010. To create a new SPA you should create an ASP.NET MVC4 Web Application project based on this template.

The default project created using the SPA project template contains data models, views and client script files for performing CRUD operations of a sample "To Do" application. SPA extensively uses two JavaScript libraries, namely Knockout and Upshot. The following figure shows these libraries added in the Solution Explorer.

Data Model

The sample application created by the default SPA project template deals with "To Do" items, i.e. tasks. A task is represented by a data model class - TodoItem. The TodoItem class resides in the Models folder and looks like this:

public class TodoItem
{
    public int TodoItemId { get; set; }
    [Required]
    public string Title { get; set; }
    public bool IsDone { get; set; }
}

As you can see the TodoItem is a simple class with three properties, viz. TodoItemId, Title and IsDone. The Title property is a required property as indicated by Data Annotation Attribute [Required].

To deal with the application data you need to create a DbContext and a DbDataController. This is done for you when you add a new controller to the project specifying the SPA controller template. Right click on the Controllers folder and select Add > Controller. In the Add Controller dialog specify details as shown below:

Specify the controller name as TodoController. Select scaffolding template of "Single Page Application with read/write actions and views, using Entity Framework". In the Model class drop-down select TodoItem class. In the Data context class drop-down click "New data context" and specify a name for the DbContext class. Once you click on the Add button the following files will be created for you:

  1. TodoController.cs (Controllers folder)
  2. SPADefaultDemoController.cs (Controllers folder)
  3. SPADefaultDemoController.TodoItem.cs (Controllers folder)
  4. SPADefaultDemoContext.cs (Models folder)
  5. Index.cshtml and associated partial views (Views folder)

Out of these classes the DbContext class (SPADefaultDemoContext) looks like this:

public class SPADefaultDemoContext : DbContext
{
    public DbSet<TodoItem> TodoItems { get; set; }
}

As you can see the SPADefaultDemoContext class inherits from DbContext base class and contains a DbSet of TodoItem.

Data Service

The job of performing CRUD operations is handled by the SPADefaultDemoController (the data service) class. This class is shown below:

public partial class SPADefaultDemoController :
               DbDataController<SPADefaultDemo.Models.SPADefaultDemoContext>
{
    public IQueryable<SPADefaultDemo.Models.TodoItem> GetTodoItems() {
        return DbContext.TodoItems.OrderBy(t => t.TodoItemId);
    } 

    public void InsertTodoItem(SPADefaultDemo.Models.TodoItem entity) {
        InsertEntity(entity);
    } 

    public void UpdateTodoItem(SPADefaultDemo.Models.TodoItem entity) {
        UpdateEntity(entity);
    } 

    public void DeleteTodoItem(SPADefaultDemo.Models.TodoItem entity) {
        DeleteEntity(entity);
    }
}

As you can see the SPADefaultDemoController class inherits from DbDataController base class and includes methods for selecting, inserting, updating and deleting TodoItem records to the database. The data service is called from the client side JavaScript code as you will see later.

ViewModel

The ViewModel class for the TodoItem data model is created automatically for you and is placed in the Scripts folder.

As you can see TodoItemsViewModel.js file is placed in the Scripts folder. This ViewModel is developed using Knockout and a part of it is shown below:

// TodoItem class
var entityType = "TodoItem:#SPADefaultDemo.Models";
MyApp.TodoItem = function (data) {
    var self = this;
    // Underlying data
    self.TodoItemId = ko.observable(data.TodoItemId);
    self.Title = ko.observable(data.Title);
    self.IsDone = ko.observable(data.IsDone);
    upshot.addEntityProperties(self, entityType);
}
...

As you can see the TodoItem ViewModel class contains the same properties as the server side data model. These properties are observable properties as indicated by ko.observable() syntax. Knockout synchronizes the data between views and ViewModel. The communication between the ViewModel and the server side data happens through Upshot.js.

View

The Index.cshtml file represents the main view of the application. Three partial views are also created viz. _Grid, _Editor and _Paging that provide the user interface for list, insert/update and paging respectively. Depending on the operation selected by the user the appropriate partial view is rendered. The following markup shows a fragment from the Index.cshtml.

@{
    ViewBag.Title = "TodoItems";
    Layout = "~/Views/Shared/_SpaLayout.cshtml";


<div data-bind="visible: editingTodoItem">
    @Html.Partial("_Editor")
</div> 

<div data-bind="visible: !editingTodoItem()">
    @Html.Partial("_Grid")
</div> 

<div class="message-info message-success" data-bind="flash: { text: successMessage, duration: 5000
}"></div>
<div class="message-info message-error" data-bind="flash: { text: errorMessage, duration: 20000 }"></div>

<script type="text/javascript" src="@Url.Content("~/Scripts/TodoItemsViewModel.js")"></script>
<script type="text/javascript">
    $(function () {
        upshot.metadata(@(Html.Metadata<SPADefaultDemo.Controllers.SPADefaultDemoController>())); 

        var viewModel = new MyApp.TodoItemsViewModel({
            serviceUrl: "@Url.Content("~/api/SPADefaultDemo")"
        });
        ko.applyBindings(viewModel);
    });
</script>

Notice that data service URL is specified as ~/api/SPADefaultDemo. The Html.Metadata() method provides the metadata of the types to the Upshot. The binding between View and ViewModel is provided by the applyBindings() method of Knockout.

If you run the application and navigate to http://localhost:1275/todo (change the port no. as per your setup) you will see something similar to the following figure.

You can click on the "Create TodoItem" button to add a few records. You can then modify or delete them. The following figure shows the view in edit mode.

Database

At this stage the sample "To do" application is able to store and retrieve the data but you might be wondering where the actual data is. Since SPA uses Code First approach to database operations, the database is automatically created for you when you run the application for the first time. The subsequent runs use the previously created database. Have a look at the following figure that shows a sample database generated under local installation of SQL Express.

As you can see, by default the database name is the same as the fully qualified name of the DbContext class. Inside there is a TodoItems table that stores the application data.



European ASP.NET MVC 4 Hosting - Amsterdam :: ValidateInput and AllowHtml attribute in MVC4

clock October 28, 2013 09:43 by author Scott

Sometimes, your required to save Html data in the database. By default Asp.Net MVC doesn't allow a user to submit html for avoiding Cross Site Scripting attack to your application. Suppose you have below form and you can submit the Html in description textarea.

If you do this and try to submit it you will get the error below

However, if you want to do this, you can achieve it by using ValidateInput attribute and AllowHtml attribute.

ValidateInput Attribute

This is the simple way to allow the submission of HTML. This attribute can enable or disable input validation at the controller level or at any action method.

ValidateInput at Controller Level

[ValidateInput(false)]
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}

[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{

}
return View();
}
}

Now, the user can submit Html for this Controller successfully.

ValidateInput at Action Method Level

public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}

[ValidateInput(false)]
[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{

}
return View();
}
}

Now, the user can submit Html for this action method successfully.

Limitation of ValidateInput attribute

This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should useAllowHtml attribute.

AllowHtml Attribute

This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc; 

public class BlogModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; } 

[AllowHtml]
[Required]
[Display(Name = "Description")]
public string Description{ get; set; } 

}

Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.



European ASP.NET MVC Hosting - Amsterdam :: Example Routing in ASP.NET MVC

clock October 18, 2013 12:32 by author Scott

Basically, Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event.

How to defining route...

    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // Route Pattern
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for above defined parameters
    );
    }    

    protected void Application_Start()
    {
    RegisterRoutes(RouteTable.Routes);
    //To:DO
    }

When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it returns a 404 HTTP status code.

Note

Always remeber route name should be unique across the entire application. Route name cann't be duplicate.

How it works...

In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default values for controller,action and id parameters. Default values means if you will not provide the values for controller or action or id defined in the pattern then these values will be serve by the routing system.

Suppose your webapplication is running on www.example.com then the url pattren for you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system.

Difference between Routing and URL Rewriting

Many developers compares routing to URL rewritting that is wrong. Since both the approaches are very much different. Moreover, both the approaches can be used to make SEO friendly URLs. Below is the main difference between these two approaches.

  • URL rewriting is focused on mapping one URL (new url) to another URL (old url) while routing is focused on mapping a URL to a resource.
  • Actually, URL rewriting rewrites your old url to new one while routing never rewrite your old url to new one but it map to the original route.


European ASP.NET MVC 3 Hosting - Amsterdam :: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

clock September 18, 2013 09:14 by author Scott

I write this blog post as I saw many people get this error message when deployed their MVC 3 application:

Error 1 It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

You can find the resource error on http://stackoverflow.com/questions/5161511/mvc3-strange-error-after-switching-on-compilation-of-views or forums.asp.net.

Its always a good idea to compile your Razor views. The reason being that errors within a view file are not detected until run time.

To let you detect these errors at compile time, ASP.NET MVC projects now include an MvcBuildViews property, which is disabled by default. To enable this property, open the project file and set the MvcBuildViews property to true, as shown in the following example:

After enabling MvcBuildViews you may find that error above.

Turns out that this problem occurs when there is web project output (templated web.config or temporary publish files) in the obj folder. The ASP.NET compiler used isn't smart enough to ignore stuff in the obj folder, so it throws errors instead.

The fix was a modification to the MVC Project File as shown below:

Under the <Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'"> node, add the following :

<ItemGroup>


  <ExtraWebConfigs Include="$(BaseIntermediateOutputPath)\**\web.config" />

  <ExtraPackageTmp Include="$([System.IO.Directory]::GetDirectories(&quot;$(BaseIntermediateOutputPath)&quot;, &quot;PackageTmp&quot;, System.IO.SearchOption.AllDirectories))" />

</ItemGroup>
<Delete Files="@(ExtraWebConfigs)" />
<RemoveDir Directories="@(ExtraPackageTmp)" />

Hope this helps!



European ASP.NET MVC 4 Hosting - Amsterdam :: Securely Verify and Validate Image Uploads in ASP.NET and ASP.NET MVC

clock September 17, 2013 10:01 by author Ronny

One of the more interesting things had to do as part of building XAPFest was handle bulk image uploads for screenshots for applications and user / app icons. Most of the challenges here are UI-centric ones (which resolved using jQuery File-Upload) but the one security challenge that remains outstanding is ensuring that the content uploaded to your servers is safe for your users to consume.

Fortunately this problem isn't too hard to solve and doesn't require much code in C#.

Flawed Approaches to Verifying Image Uploads

Here's what usually see when developers try to allow only web-friendly image uploads:

  1. File extension validation (i.e. only allow images with .png, .jp[e]g, and .gif to be uploaded) and
  2. MIME type validation.


So what's wrong with these techniques? The issue is that both the file extension and MIME type can be spoofed, so there's no guarantee that a determined hacker might not take a js. file, slap an extra .png extension somewhere in the mix and spoof the MIME type.

Stronger Approach to Verifying Image Uploads: GDI+ Format Checking

Every file format has to follow a particular codec / byte order convention in order to be read and executed by software. This is as true for proprietary formats like .pptx as it is for .png and .gif.

You can use these codecs to your advantage and quickly tell if a file is really what it says it is - you quickly check the contents of the file against the supported formats codecs to see if the content fits into any of those specifications.

Luckily GDI+ (System.Drawing.Imaging), the graphics engine which powers Windows, has some super-simple functions we can use to perform this validation. Here's a bit of source you can use to validate a file against PNG, JPEG, and GIF formats:

using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
namespace XAPFest.Providers.Security
{
    ///
    /// Utility class used to validate the contents of uploaded files  
    ///
    public static class FileUploadValidator  
    {    
     public static bool FileIsWebFriendlyImage(Stream stream)   
     {
            try
            {
                //Read an image from the stream...
                var i = Image.FromStream(stream);
                 //Move the pointer back to the beginning of the stream
                stream.Seek(0, SeekOrigin.Begin);
                 if (ImageFormat.Jpeg.Equals(i.RawFormat))
                    return true;
                return ImageFormat.Png.Equals(i.RawFormat)|| ImageFormat.Gif.Equals(i.RawFormat);
            }
            catch
            {
                return false;
            }
        }
     }
}

All this code does is read the Stream object returned for each posted file into an Image object, and then verifies that the Image supports one of three supported codecs. This source code has not been tested by security experts, so use it at your own risk. If you have any questions about how this code works or want to learn more, please drop me a line in the comments below or on Twitter.

How Do Make Sure Files Are below [X] Filesize

Since had this source code lying around anyway, We thought we would share it: 

Super-simple, like we said, but it gets the job done. Express the maximum allowable size as a long and compare it against the length of the stream

public static bool FileIsWebFriendlyImage(Stream stream, long size)
        {
            return stream.Length <= size && FileIsWebFriendlyImage(stream);
        }
    }
The other important catch to note here is that move the Stream's pointer back to the front of the stream, so it can be read again by the caller which passed the reference to this function.



European ASP.NET MVC 4 Hosting - Amsterdam :: Asynchronous Controllers in ASP.NET MVC 4

clock September 6, 2013 12:01 by author Scott

One of the most important features of ASP.NET MVC 4 is the introduction of the new ASP.NET Web API, which simplifies REST programming with a strongly typed HTTP object model. In addition, ASP.NET MVC 4 takes advantage of the new asynchronous programming model introduced with .NET Framework 4.5 to allow developers to write asynchronous action methods. It is important to understand the advantages and disadvantages of the new asynchronous methods to use them whenever they will provide a benefit.

(ASP.NET MVC 4 also includes many enhancements focused on mobile development, such as jQuery Mobile support and selecting views based on which mobile browser makes requests. If you work with previous ASP.NET MVC versions and you target multiple mobile devices, the new display modes are worth moving to ASP.NET MVC 4. In addition, the bundling and minification framework makes it simpler to reduce HTTP requests for each page without having to use third-party tools.)

Asynchronous controllers ASP.NET MVC 4

Asynchronous execution is the future of Windows development : it has been largely demonstrated during the //Build conference two weeks ago.

In previous versions of ASP.NET MVC it was possible to create asynchronous controllers by inheriting the AsyncController class and using some conventions :

- MyActionAsync : method that returns void and launches an asynchronous process
- MyActionCompleted : method that returns an ActionResult (the result of the MVC action “MyAction”, in this case)

To allow the MVC engine to manage asynchronous operations and pass the result to the view engine, developers had to use the propery AsyncManager of the AsyncController. The “completed” method parameters was passed by the MVC engine through this object.

For example, the controller that is defined bellow allows to get a Json-serialized list of movies – asynchronously – from an OData service :

public class MoviesController : AsyncController
{
    public ActionResult Index()
    {
        return View();
    } 

    public void GetJsonMoviesAsync(int? page)
    {
        const int pageSize = 20;
        int skip = pageSize * ((page ?? 1) - 1);
        string url = string.Format("http://odata.netflix.com/[…]&$skip={0}&$top={1}",
            skip, pageSize); 

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

        var webClient = new WebClient();
        webClient.DownloadStringCompleted += OnWebClientDownloadStringCompleted;
        webClient.DownloadStringAsync(new Uri(url));//the asynchronous process is launched
    } 

    private void OnWebClientDownloadStringCompleted(object sender,
        DownloadStringCompletedEventArgs e)
    {
        //the asynchronous process ends
        //"movies" result is added to the parameters of the AsyncManager
        //NB : it's the name of the parameter that is take by the
        //GetJsonMoviesCompleted method
        List<Movie> movies = null;
        if (AsyncManager.Parameters.ContainsKey("movies"))
        {
            movies = (List<Movie>)AsyncManager.Parameters["movies"];
            movies.Clear();
        }
        else
        {
            movies = new List<Movie>();
            AsyncManager.Parameters["movies"] = movies;
        } 

        movies.AddRange(Movie.FromXml(e.Result)); 

        //the ends of the asynchronous operation (launches the call of "Action"Completed)
        AsyncManager.OutstandingOperations.Decrement();
    } 

    public ActionResult GetJsonMoviesCompleted(List<Movie> movies)
    {
        //on retourne le résultat Json
        return Json(movies, JsonRequestBehavior.AllowGet);
    }
}

It’s not really complicated to create an asynchronous controller but ASP.NET MVC 4 and C# 5 with the new async and await keywords will make it easier !

public class MoviesController : AsyncController
{
    public ActionResult Index()
    {
        return View();
    } 

    public async Task<ActionResult> GetJsonMovies(int? page)
    {
        const int pageSize = 20;
        int skip = pageSize * ((page ?? 1) - 1);
        string.Format("http://odata.netflix.com/[…]&$skip={0}&$top={1}",
                    skip, pageSize); 

        var webClient = new WebClient();
        string xmlResult = await webClient.DownloadStringTaskAsync(url);
        return Json(Movie.FromXml(xmlResult), JsonRequestBehavior.AllowGet);
    }
}

As you can see in the previous code snippet, in ASP.NET MVC 4 you always should inherits from AsyncController but there is no more naming conventions, no more Async/Completed methods, no more AsyncManager and the action returns a Task instead of an ActionResult !

 



Press Release :: European HostForLIFE.eu Proudly Launches ASP.NET MVC 5 Hosting

clock August 28, 2013 11:05 by author Ronny

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the Microsoft ASP.NET Model View Controller (MVC) technology. The MVC web application framework facilitates the development of dynamic, data-driven websites.

The latest update to Microsoft’s popular MVC (Model-View-Controller) technology,  ASP.NET MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more. Here are some new features of ASP.NET MVC 5:

- ASP.NET Identity
- Bootstrap in the MVC template
- Authentication Filters
- Filter overrides

HostForLIFE.eu is Microsoft’s number one Recommended Windows and ASP.NET Spotlight Hosting Partner in Europe for its support of Microsoft technologies that include WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5, and Visual Studio Lightswitch.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression.

In addition to shared web hosting, shared cloud hosting, and cloud server hosting, HostForLIFE.eu offers reseller hosting packages and specialized hosting for Microsoft SharePoint 2010 and 2013. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee.

For more information about this new product, please visit http://www.HostForLIFE.eu

About HostForLIFE.eu:

HostForLIFE.eu is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. HostForLIFE.eu 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 many top European countries.

HostForLIFE.eu number one goal is constant uptime. HostForLIFE.eu data center uses cutting edge technology, processes, and equipment. HostForLIFE.eu has one of the best up time reputations in the industry.

HostForLIFE.eu second goal is providing excellent customer service. HostForLIFE.eu technical management structure is headed by professionals who have been in the industry since it's inception. HostForLIFE.eu has customers from around the globe, spread across every continent. HostForLIFE.eu serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET MVC 4 Hosting - Amsterdam :: Creating MVC 4 Application with Umbraco

clock August 16, 2013 06:38 by author Scott

Hello, how do you do? In this article, I will gonna show you how to integrate ASP.NET MVC 4 using Umbraco. Note that Umbraco does not provide a “pure” MVC application as the Umbraco UI comes with a fair amount of webforms baggage. That said, it plays nicely with an MVC 4 project in Visual Studio and provides a flexible view rendering engine that lets you build genuinely testable page templates.

Setting up the project

Umbraco is shipped as an ASP.NET website which you can use directly, though this is not ideal. It is a better idea to create a full MVC 4 project, manage the dependencies using the Umbraco NuGet package and drop the Umbraco files directly into the site. Use the following steps to set up Umbraco as an MVC 4 project in Visual Studio:

Firstly, start an empty MVC 4 project in Visual Studio – make sure it is an empty project as you will not need any of the baggage that comes with other project templates.

Add the NuGet Umbraco Cms Core Binaries package which will manage the various dependencies and references that Umbraco 6 requires for you.

Copy all the files from the Umbraco installation ZIP archive directly into your project in Visual Studio except the App_Code and Bin folders – you won’t need the binaries as they are managed by NuGet and the App_Code folder is not used in a web application project.

The default mode for Umbraco is to use web forms rendering. You will need to switch this to use MVC by changing the defaultRenderingEngine setting in the Umbraco configuration file UmbracoSettings.config as shown below:

<templates>
  <useAspNetMasterPages>true</useAspNetMasterPages>
  <defaultRenderingEngine>Mvc</defaultRenderingEngine>
</templates>

Now you’re good to go – run the Umbraco site to set up the database and once the admin console comes up you can create a first view.

Note that you may optionally wish to remove the App_Start directory and Global.asax.cs files from your Visual Studio project – they are not used in a default Umbraco application as global.asax inherits directly from the Umbraco.Web.UmbracoApplication class and does not execute this code.

Creating a view

You can create a basic view in the Umbraco UI. In the “Settings” section create a new Document Type – call it “Home” and ensure that “Create matching template” is checked. A new file will be created in your Views folder with the following mark-up:

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{

    Layout = null;
}

If you create and publish a first page based on this content type it will become your site’s home page. This is all you do to start creating pages based on MVC as Umbraco uses a default routing process that delivers the page properties to the view. You can actually build basic content pages without having to worry about the plumbing around controllers and models – this only starts to become important if you want to put more logic in behind the scenes.

Creating a custom controller

The default rendering engine for Umbraco routes requests through RenderMvcController with an IPublishedContent object as the model view. This provides a pretty simple means of  basic pages rigged up with managed content but you can extend this behavior by creating custom controllers. Umbraco refers to this technique of creating custom controllers as hijacking, though really it is just a matter of creating a controller where MVC would normally look.

To create a controller for our Home view we just create a controller called HomeController. To hook it up to Umbraco’s content API you will need to inherit from RenderMvcController and override the Index method as shown below:

public class HomeController : Umbraco.Web.Mvc.RenderMvcController
{
    public override ActionResult Index(RenderModel model)
    {
        //Do some stuff here, then return the base method
        return base.Index(model);
    }
}

Creating controllers to handle forms and actions is a little more involved as you have to create what Umbraco calls a surface controller. This is a controller like any other but one that is derived from the Umbraco SurfaceController class. These controllers can be implemented as a normal part of your MVC project (“locally declared” in Umbraco-speak) or implemented as a plug-in for shipping as part of a package.

If you want to include your own custom MVC routes then you will have to override the OnApplicationStarted method. This can be done by creating your own custom global.asax file that inherits from Umbraco.Web.UmbracoApplication.

Creating a custom model

Once you have wired up a controller it’s pretty straightforward to create in your own model and pass it into the page. You will need to change the view so that it inherits the generic version of UmbracoViewPage with your custom model specified as the generic parameter. The example below shows the view adjusted for a new model called HomeModel.

@inherits Umbraco.Web.Mvc.UmbracoViewPage<UmbracoMvc4.Models.HomeModel>
@{

    Layout = null;
}

The controller will still accept a RenderModel object but you can pass your custom model by using the CurrentTemplate method as shown below:

public override ActionResult Index(RenderModel model)
{
    HomeModel customModel = new HomeModel();
    return CurrentTemplate(customModel);
}

If you want to take advantage of the Umbraco view helpers then you can extend the RenderModel object by creating a constructor that initialises the base class as shown below. This will ensure that your derived model still exposes the page data and current culture properly.

public class HomeModel : RenderModel
{
    public HomeModel(RenderModel model)
        : base(model.Content, model.CurrentCulture)
    { }
}

Beyond the basics

Although it is not a “pure” MVC implementation you can still get Umbraco 6 to sit quite nicely within an MVC 4 web application just so long as you set it up carefully. Beyond the basics of models, views and controllers there is support for features such as partial views and child actions as well as scope for you to use dependency injection and your IoC container of choice. So long as you’re prepared to ignore the messy webforms back-end that lurks in the background Umbraco 6 can really feel like working with an MVC 4 application.



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