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

ASP.NET MVC 4 Hosting - HostForLIFE.eu :: How to Create ASP.NET MVC 4 Web Registration?

clock April 13, 2016 21:39 by author Anthony

In this tutorial, I will explain how to develop web applications using C# ASP.NET MVC 4.  You’ll create an ASP.NET MVC 4 web application that allows the user to register their details.

Index View

  •     Page 1 will ask the user to enter their name. The page will have a “Next” button that shows page 2.
  •     Page 2 will ask the user for their details: username, password and email address.
  •     Page 3 will confirm the user’s details. The page will have a hyperlink to return to page 1.

Creating First Page


Create an empty ASP.NET MVC 4 web application named Registration using C#. Implement the first page, make sure to choose Empty Project and use the ASPX engine.

An MVC4 Applcation

  • Add a controller class named HomeController to the Controllers folder. To do this right-click and select Add>Controller from the context menu. Add a standard action method named Index() that returns the default view to this controller.In an MVC application all of the browser’s HTTP requests are handled first by a Controller class. This class contains action methods that the requests are directed to. The specific controller and method that is invoked will depend on the request’s URL.
  • Add an ASPX view for the Index() action method. To do this right-click in the Index() method and select Add View from the context menu, make sure to deselect “use a layout or masterpage” and use the ASPX Engine. This will cause a web page named Index.aspx to be added in the Views/Home folder.In an MVC application a view holds only the visual content of the web page.
  • Open Index.aspx in the Views\Home folder.
  • Add a tag, to start a form in Index.aspx.
  • Within the form, include the Html.TextBox() HTML helper function to display a text box named username. HTML helper functions make it easier to add HTML tags to a view by employing intellisense.
  • Add a submit button inside the form. Use plain old HTML to do this. The submit button will post back the form back to the same action and the same controller.
  • Use a %}%> tag to mark the end of the form.
    <body>
    <h3>Welcome to the website registration</h3>
    <%using(Html.BeginForm())
    {%>
    <%: Html.Label("Please enter your name") %>
    <%: Html.TextBox("name")%>
    <p> <input type="submit" value="Next" /> </p>
    <%}%>
    </body>
  • View code file.
  • Now run the application. When the page is shown, just enter your name and click the button. This submits the form back to the server, and causes MVC to call your Index() action method. Unfortunately Index() only redisplays page without your name. To solve this problem, you now need to handle the HTTP POST request so the user is redirected to the next page.
  • Edit the Index() method in the Controller so that it only handles the initial page request. To do this adds this annotation just above the method declaration. [HttpGet]
    [HttpGet]//Run action method on first request
    public ActionResult Index() {
    return View();
    }
  • Add a second action method also called Index(), to handle form submissions from the first page. To do this, add this annotation just above the method declaration.[HttpPost]
  • This method also requires a string parameter called username, which MVC automatically populates from the textbox on the page.
  • Now edit your new Index() method by including this statement.
    return RedirectToAction(“Details”, “Home”, new {name = name});
    This attempts to redirect the next page and it also passes the name parameter to that page.
    [HttpPost]//Run action method on form submission
    public ActionResult Index(string name)
    {
    return RedirectToAction("Details", "Home", new { name = name });
    }
  • View code file.
  • Run the application. Even though you will get a 404 Page Not Found error, this is not a problem at this stage. The error will disappear when you create the Details() action method and the Details.aspx view on the next lab.

Creating User Details Page

Add a model class to hold the user details. Add a view to allow the user to enter their details.

  • In the Models folder, create a class named UserDetails. To do this right-click and select Add>Class from the context menu.In an MVC application a Model class contains all the business, validation and data access code. Since the Model classes are clearly separate from the application’s Controllers and Views, they can be implemented, tested & maintained independently.
  • Add properties of type string for name, username, password and email address.
    public class UserDetails
    {
    public string Name { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string EmailAddress { get; set; }
    }
  • View code file.
  • In the controller class, add an action method named Details(). This handles HTTP GET requests to display the Details view.
  • Include a string parameter to hold the name in the Details() method. The parameter will be passed in from the first page.
  • Inside the method, create a new UserDetails object and set its Name property to the incoming name parameter.
  • Add this statement to return the default view: return View(user);
    [HttpGet]//Run action method on first request
    public ActionResult Details(string name)
    {
    UserDetails user = new UserDetails();
    user.Name = name;
    return View(user);
    }
  • View code file.
  • This passes an UserDetails object as the model parameter to the view.
  • Add an ASPX view for the Details() action method. Make the view a strongly-typed view, based on the UserDetails class. This will add a Web page named Details.aspx to the Views/Home folder.
  • Implement Details.aspx to display the name entered on the first page in a heading.
  • In Details.aspx also display a form containing text boxes. These allow the user to enter their details. Use Html.TextBoxFor() for each text box.
  • At the bottom of Details.aspx add a submit button.
    <body>
    <h3>Hi <%: Model.Name %></h3>
    Please enter your registration details
    <div>
    <% Html.EnableClientValidation(); %>
    <% using(Html.BeginForm())
    {%>
    <p>
    <%: Html.LabelFor(m => m.UserName, "User Name:")%>
    <%: Html.TextBoxFor(m => m.UserName)%>
    </p>
    <p>
    <%: Html.LabelFor(m => m.Password, "Password:")%>
    <%: Html.TextBoxFor(m => m.Password)%>
    </p>
    <p>
    <%: Html.LabelFor(m => m.EmailAddress, "Email Address:")%>
    <%: Html.TextBoxFor(m => m.EmailAddress)%>
    </p>
    <p> <input type="submit" value="Next" /> </p>
    <%}%>
    </div>
    </body>
  • View code file.
  • Back in the controller class, implement another action method named Details() to handle HTTP POST requests.
  • The method takes a UserDetails parameter. MVC will populate this object automatically with the data entered in each text box.
  • Return a view specifying “Confirmation” as the view name. Pass the UserDetails object as the model parameter to the view. The view does not yet exist.
    [HttpPost]//Run action method on form submission
    public ActionResult Details(UserDetails user)
    {
    return View("Confirmation", user);
    }
  • Run the application. In the first page, enter your name and click the submit button. Verify that the “user details” page now appears, displaying your name and a series of text boxes. Enter some details and then click the submit button. At this stage you will receive an ASP.NET error indicating the “Confirmation” view cannot be found. You will create this in the next lab.

Creating The Confirmation Page

Add a view to confirm the user has entered their details.

  • For the HTTP-POST version of the Details() action method, then add an ASPX view named Confirmation that is strongly bound to the UserDetails class. Make the view a strongly-typed view, based on the UserDetails class.
  • Implement Confirmation.aspx so that it shows the user information.
  • Add a hyperlink at the bottom of the page to return the user to the first page. Use the Html.ActionLink() helper function.
    <body>
    <div>
    <% using(Html.BeginForm())
    {%>
    <p>You have now been registered as:</p>
    <ul>
    <li> User Name: <%: Model.UserName %> </li>
    <li> Password: <%: Model.Password%> </li>
    <li> Email Address: <%: Model.EmailAddress %> </li>
    </ul>
    <p> <%: Html.ActionLink("Return to welcome page", "Index")%>
    </p>
    <%}%>
    </div>
    </body>
  • View code file.
  • Run the application. Is it now working fully?

Add Validation

Add validation checks when user details are entered.

  • Include validation in the model class. Add attributes to the properties that define the checks. Use attributes in the System.ComponentModel.DataAnnotations namespace, such as [Required], [StringLength], and [Range].
    [Required(ErrorMessage = "Name required")]
    public string Name { get; set; }
  • In the Details page, do not proceed if there are any validation errors.
    [HttpPost]//Run action method on form submission public
    ActionResult Details(UserDetails user)
    {
    if (ModelState.IsValid)
    return View("Confirmation", user);
    else
    return View(user);
    }
  • View code file.
  • Enable client-side validation In the Details page.

HostForLIFE.eu ASP.NET MVC 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 4 Hosting - HostForLIFE.eu :: How to Use KnockoutJS in ASP.NET MVC 4?

clock April 8, 2016 20:00 by author Anthony

In this post I’ll show how you can use KnockoutJS and SignalR together. KnockoutJS is a MVVM implementation for JavaScript written by Steve Sanderson, in my opinion the author of the best ASP.NET MVC textbooks available. Simply put it lets you bind a JavaScript object model to your HTML UI using a simple binding format, and when the underlying model is updated the UI is automatically updated to reflect the change.

SignalR is a library from Microsoft utilising HTML5’s WebSockets allowing server side code to call JavaScript functions on the client to create real-time functionality.

To me these two libraries seem like a match made in heaven. SignalR calling a JavaScript function to alter data, and Knockout automatically updating the UI.

To create real-time web application with little effort. I’m going to create a very basic example of a web page showing a list of exchange rates hooked up using KnockoutJS. I’ll then create a server side page to update the data and use SignalR to call a JavaScript function to update the JavaScript model.

Source code

The layout page looks like this.

<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
 
    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.css">
 
    <script src="~/Scripts/jquery-1.6.4.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery.signalR-1.0.0-rc2.js" type="text/javascript"></script>
    <script src="~/Scripts/knockout-2.2.1.debug.js" type="text/javascript"></script>
    <script src="~/Scripts/knockout.mapping-latest.debug.js" type="text/javascript"></script>
    <script src="/signalr/hubs" type="text/javascript"></script>
 
</head>
<body>
    <div class="container">
        @RenderBody()
    </div>
 
    @RenderSection("scripts", false)
</body>
</html>

You can see I’ve included references for SignalR, jQuery, Knockout and Knockout Mapping (I’ll explain what this is and how to use it later). You’ll also see a reference to signalr/hubs. This gets generated on the fly by SignalR to manage the client connection, but you still need to create a reference to it.

Now I want to create a view to display my currencies with Knockout. I have created a HomeController with an Index view that looks like this:

<h2>Current Exchange Rates</h2>
 
<table class="table table-bordered">
    <thead>
        <tr>
            <th></th>
            <th>USD</th>
            <th>EUR</th>
            <th>GBP</th>
            <th>INR</th>
            <th>AUD</th>
            <th>CAD</th>
            <th>ZAR</th>
            <th>NZD</th>
            <th>JPY</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>USD</th>
            <!-- ko foreach: currencies -->
            <td data-bind="text: price"></td>
            <!-- /ko -->
        </tr>
    </tbody>
</table>

It’s just a basic table with some bindings for Knockout. Knockout supports several types of bindings and other functions; if you haven’t already run through the live examples it’s worth doing. Above I’m using the for foreach binding to iterate though a collection on the model called currencies. Bindings can be applied to a HTML element, for example to the tbody element to make each item create a table row. In my example I only want one row and I’m manually adding the text USD to the first column, so I’m using the containerless syntax using comment tags. For each item in my collection it will render a TD tag and bind the price property of the object as the text.

That’s my template all set up and ready to go. Now for adding the JavaScript to bind my model to my UI.

var currentCurrencies = [
                { code: "USD", price: ko.observable(1.00000) },
                { code: "EUR", price: ko.observable(0.75103) },
                { code: "GBP", price: ko.observable(0.63163) },
                { code: "INR", price: ko.observable(53.8253) },
                { code: "AUD", price: ko.observable(0.95095) },
                { code: "CAD", price: ko.observable(1.00020) },
                { code: "ZAR", price: ko.observable(9.04965) },
                { code: "NZD", price: ko.observable(1.18616) },
                { code: "JPY", price: ko.observable(89.3339) }
            ];
 
            var currencyModel = function (currencies) {
                this.currencies = currencies;
            };
 
            ko.applyBindings(currencyModel(currentCurrencies));

First I have created an array of currency objects. For each price I have used the ko.observable function which is required for knockout to track the property and automatically update the UI. I have created a simple model with a property called currencies, and then used ko.applyBinding passing the model which binds to the template. I get a basic table that looks like this:

Knockout

At this point if I were to use JavaScript to update the price of one of the objects in the currencies collection the UI would automatically update to reflect that change. I’m now going to do that, but using SignalR to call the JavaScript function.

I’m going to create a page that allows me to update the currencies server side, so I have created a C# model called CurrencyViewModel which looks like this:

public class CurrencyViewModel
{
    public class Currency
    {
        [JsonProperty(PropertyName = "code")]
        public string Code { get; set; }
        [JsonProperty(PropertyName = "price")]
        public decimal Price { get; set; }
    }
 
    public List Currencies { get; set; }
}

You’ll notice the JsonProperty attribute for each property in the Currency object. Later when I call the JavaScript function the Currency object will be serialised as Json and passed into the method, so I added the attribute to make the property names lowercase to fit with JavaScript coding standards.

Next I’ve created an AdminController with an Index method to manage the currencies:
[HttpGet]
public ActionResult Index()
{
    var viewModel = new CurrencyViewModel()
    {
        Currencies = CurrencyService.GetCurrencies()
    };
 
    return View(viewModel);
}

CurrencyService is just an object returning a static list of currency objects. This could be coming from a database or file etc. Later I’ll show how you can also use SignalR to call server side code, and I’ll call this GetCurrencies method to populate the initial exchange rates instead of using the JavaScript array. The CurrencyService object looks like this.

public class CurrencyService
{
    public static List GetCurrencies()
    {
        return new List()
                    {
                        new CurrencyViewModel.Currency() {Code = "USD", Price = 1.00000M},
                        new CurrencyViewModel.Currency() {Code = "EUR", Price = 0.75103M},
                        new CurrencyViewModel.Currency() {Code = "GBP", Price = 0.63163M},
                        new CurrencyViewModel.Currency() {Code = "INR", Price = 53.8253M},
                        new CurrencyViewModel.Currency() {Code = "AUD", Price = 0.95095M},
                        new CurrencyViewModel.Currency() {Code = "CAD", Price = 1.00020M},
                        new CurrencyViewModel.Currency() {Code = "ZAR", Price = 9.04965M},
                        new CurrencyViewModel.Currency() {Code = "NZD", Price = 1.18616M},
                        new CurrencyViewModel.Currency() {Code = "JPY", Price = 89.3339M}
                    };
    }
}

Now I have created a couple of EditorTemplate to allow me to update the currencies. I’ll omit the markup from this post but you can see them in the provided source code. This gives me a form to edit my rates:

Knockout

Okay, so now it’s time to use SignalR. The first step is to register the necessary routes in the Global.asax Application_Start method:

RouteTable.Routes.MapHubs();

Next I need to create a hub. A hub is a C# class containing methods that the client can call. When you run the application, SignalR will create the hubs JavaScript file I mentioned earlier based on the C# hubs in your application. This is essentially a proxy allowing the client to connect to the hub and for messages to flow from server to client and vice versa.

All hubs must inherit from the abstract Hub class. I have a CurrencyHub which looks like this:

public class CurrencyHub : Hub
{
    public void GetCurrencies()
    {
        Clients.Caller.setCurrencies(CurrencyService.GetCurrencies());
    }
}

Methods in the hub are available to the client. As I mentioned earlier I will later get the currencies for the initial load from the currency service, so that is what this GetCurrencies method is for. You do not need to add methods to your hub to call functions on the client.

I’m now going to implement the post action for the Index method on my AdminController. This is where I will call the client side JavaScript to update the exchange rates directly to the UI:

[HttpPost]
public ActionResult Index(CurrencyViewModel viewModel)
{
    var context = GlobalHost.ConnectionManager.GetHubContext<CurrencyHub>();
    viewModel.Currencies.ForEach(c => context.Clients.All.updateCurrency(c.Code, c.Price));
    return View(viewModel);
}

Once I have this I can use Clients.All to call a JavaScript function on all clients connected to the hub. All is dynamic so you simply add a method matching that of the JavaScript function with the same signature. Here that function is called updateCurrency and code and price are passed as arguments.

My action method is looping through each currency object in the model’s collection and calling updateCurrency for each. Not the most efficient way to do it in the real world, but I’m trying to keep this example simple.

Now for the JavaScript to hook it all up. Knockout isn’t dependent on any other library, but SignalR uses jQuery so I’ve now wrapped everything in a ready function. First off I’ve added an updateCurrency method to my model which finds the given currency and updates the price. This is using Knockout’s arrayFirst utilitymethod. The remaining changes set up SignalR. First I create a reference to my currency hub then start the connection to the hub. Next I set up the updateCurrency function on hub.client which is the function that will be called from the server. From this function I’m just calling the function on my model to update the correct price.

$(function () {
    var currentCurrencies = [
        { code: "USD", price: ko.observable(1.00000) },
        { code: "EUR", price: ko.observable(0.75103) },
        { code: "GBP", price: ko.observable(0.63163) },
        { code: "INR", price: ko.observable(53.8253) },
        { code: "AUD", price: ko.observable(0.95095) },
        { code: "CAD", price: ko.observable(1.00020) },
        { code: "ZAR", price: ko.observable(9.04965) },
        { code: "NZD", price: ko.observable(1.18616) },
        { code: "JPY", price: ko.observable(89.3339) }
    ];
 
    var currencyModel = function (currencies) {
        this.currencies = currencies;
 
        this.updateCurrency = function (code, price) {
            var currency = ko.utils.arrayFirst(this.currencies, function (currency) {
                return currency.code == code;
            });
 
            currency.price(price);
        };
    };
 
    ko.applyBindings(currencyModel(currentCurrencies));
 
    var hub = $.connection.currencyHub;
 
    $.connection.hub.start();
 
    hub.client.updateCurrency = function (code, price) {
        updateCurrency(code, price);
    };
});

And that’s all there is to it. My server side code calls hub.client.updateCurrency which calls the method of the same name in the model. That method finds the correct currency and updates the price. As price is observable Knockout then automatically updates the UI.

The final thing I’m going to do is load the currencies from the server when opening the page. This could be done using an ajax request, but you can also do it with SignalR. I’ll be calling the method in my CurrencyHub which I briefly mentioned earlier in the post. Here it as again:

public void GetCurrencies()
{
    Clients.Caller.setCurrencies(CurrencyService.GetCurrencies());
}

The method doesn’t accept any arguments, and when called, it calls a JavaScript function on the client that made the call to the server. This is through Clients.Caller, rather than Clients.All which I used earlier. The JavaScript can now be amended as below to first load the data from the server using SignalR.

$(function () {
    var currencyModel = function (currencies) {
        this.currencies = ko.mapping.fromJS(currencies);
 
        this.updateCurrency = function (code, price) {
            var currency = ko.utils.arrayFirst(this.currencies(), function (currency) {
                return currency.code() == code;
            });
 
            currency.price(price);
        };
    };
 
    var hub = $.connection.currencyHub;
 
    $.connection.hub.start().done(function () {
        hub.server.getCurrencies();
    });
 
    hub.client.updateCurrency = function (code, price) {
        updateCurrency(code, price);
    };
 
    hub.client.setCurrencies = function (currentCurrencies) {
        ko.applyBindings(currencyModel(currentCurrencies));
    };
});

The first obvious change is that I’m using the done function on hub.start so that once the connection has started it calls the getCurrencies function on the server. The function on the server was in pascal case, but when calling via JavaScript you need to use camel case.

The next change is that I’ve moved the ko.applyBindings call inside the setCurrencies function. This is the function called by the server which passes the collection of Currency objects. These objects are serialised as Json, so currentCurrencies here is an array of JavaScript objects that represent the currencies. This is that passed into my model when doing the binding.

As this is just an array of plain objects, none of the properties are observable, so the UI won’t be updated if they change. You could easily manually parse the array and re-create the objects as observable, but here I’m using the Knockout Mapping plugin. The plugin takes a JavaScript object and returns an object with observable properties. It has overrides that allow you to take control of some of the mapping, but here I’m just using the default implementation with ko.mapping.fromJS. As I’m passing in an array, it will return an observable array, where each property of each object in the array is also observable.

Due to this there are a couple of other changes required. One line 6 this.currencies becomes this.currencies(). Any observable object requires parenthesis to access as it’s converted to a method. Similarly on line 7 this.code becomes this.code() for the same reason. Previously I didn’t make code observable, so I didn’t need parenthesis, but as this time I used the mapping plugin it’s now observable.

 

 

HostForLIFE.eu ASP.NET MVC 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 4 Hosting - HostForLIFE.eu :: How to Make ASP.NET MVC 4 Web Application?

clock April 7, 2016 23:39 by author Anthony

In this tutorial I will show you how to make ASP.NET MVC 4 Web Application for beginners. But before we start, we need an application which enables user to create/update/read/delete (CRUD) the data connected with cars. Let’s create a new project.

  • Open Visual Studio 2012
  • File/New/Project -> select Web/ASP.NET MVC 4 Web Application.
  • When new window appears, please select a template as Internet Application and the vie engine as Razor. For this example, please do not select Create a unit test project.
  • Confirm


Your project structure should look like this:

1

We will start from creating a new model class. To do this, please right click on folder Models, select Add->New Item and choose Class. Name it as Car.cs – it is our first POCO in a project. The next thing is to add primitive properties inside of a class as below:

2

This class represents a Car. Car is an object which will be stored in a Cars table in a database. It means, that one car = one row in a db.

If you have already created this class, please create another one for model, named CarContext.cs -> here we will include DbSet for our Car objects and information about the name of the future database. To add it, please follow steps from Car.cs. The structure of CarContext is shown below:

9

The next thing is to add a Controller for our Model. It will store Create, Read, Update, Delete methods. To add this please right click at Controller, then select Add->Controller:

4

Click Add.  As you can see, VS 2012 has automatically added CarController with implemented CRUD methods and also new views:

5

The last thing to do is to add a connection string into web.config file. To do this, please open web.config and add this connection string:

6

Name of connection string should be the same in CarContext class ( : base(“Cars”) ).

Please hit F5 to Debug. When new tab appears please insert http://localhost:yourport/car/ and enter. This will open the view folder named Car, where all razor files for CRUD methods are stored. After that you should see your web application.

The next step is to click Create New. The new View will appear (Create.cshtml). Just add a new car with its brand and model name. After that you will see the list of all cars that have been already added. You can edit this, delete or show the details.

 

HostForLIFE.eu ASP.NET MVC 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



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 !

 



European ASP.NET MVC 4 Hosting - Amsterdam :: What is PRG and Using PRG on MVC 4

clock June 18, 2013 06:55 by author Scott

Hellooo….. Today post I will talk about what is PRG in ASP.NET MVC 4 and how to use it. Before we start, the question is what is PRG?

What is the PRG Pattern ?

  • PRG stands for "Post/Redirect/Get"
  • Instead of returning an HTML page directly,
  • The POST operation returns a redirection command (using the HTTP 303 response code (sometimes 302)
  • together with the HTTP "Location" response header),
  • Instructing the browser to load a different page using an HTTP GET request
  • The result page can then safely be bookmarked or reloaded without unexpected side effects

How to Explain this by using an Example ?

  • Here I'm going to use User Registration function as an example
  • If the Registration attempt is Successful, the user should be redirected to his Home page
  • Otherwise they should be redirected back to the Registration page

Image 1 : Shows Action Methods Interaction When do Registration

AccountController.cs        

Code for the Register Action Method (Get) for Displaying Register View is as below

        /// <summary>
        /// for displaying Register View
        /// </summary>
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
              }

Image 2 : Register View

Code for the Register Action Method (Post) for Processing the Registration and Shows Register Page again is as below

        /// <summary>
        /// for Registering the User
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
          if (ModelState.IsValid)
          {
            // Attempt to register the user
            try
             {
               WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
               WebSecurity.Login(model.UserName, model.Password);
               ViewBag.Message = "Successfully Registered!";
               return View(model);//PRG has not been Maintained
             }
              catch (MembershipCreateUserException e)
             {
                 ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
             }
          }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

Image 3 : New user has been Created



- At this point If you try to Refresh (F5) or Reload the Page,You'll see below mentioned kind of Security Alert Message Box

Image 4 : Register form with "Confirm Form Resubmission" Message Box



- After that If you try to press "Continue" Button, You'll see below mentioned Run time exception
- But for another situation this may be Data Duplication issue etc.

Image 5 : Run time Exception

How to Get Rid Of this Issue ?

  • You have to maintain PRG Pattern with your Return type, After finishing the Successful Registration
  • To properly perform PRG you must return a redirecting ViewResult from your Action
  • Such as RedirectToAction, otherwise you'll get the dialog box pictured above (i.e. Image 4)

Code for the Properly Perform PRG Pattern is Maintaining Register Action Method is as below

    /// <summary>
    /// for Registering the User
    /// </summary>
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
     {
      if (ModelState.IsValid)
      {
       // Attempt to register the user
       try
       {
         WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
         WebSecurity.Login(model.UserName, model.Password);
         ViewBag.Message = "Successfully Registered!";
         return RedirectToAction("Index""Home");//PRG has been Maintained
        }
        catch (MembershipCreateUserException e)
        {
          ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
      }
       // If we got this far, something failed, redisplay form
       return View(model);
     }

Image 6 : Home page

DONE!!



European ASP.NET MVC 4 Hosting - Amsterdam :: Revisiting IBundleTransform ASP.NET 4.5 and MVC 4

clock May 13, 2013 10:26 by author Scott

Web optimization frameworks include two defaults transform type JsMinify and CssMinify which is used by ScriptBundle and StyleBundle respectively. However we can create our own custom transform type to processe references as per our need. To create custom transform type, we need to create class which implements IBundleTransform interface.

IBundleTransform interface define a method named Process which process bundle response. In developer preview version, Process method had only one parameter of type BundleResponse, however onwards RC release, Process method introduced one more parameter of type BundleContext. In this post, we will see how we can utilize this additional parameter while creating our custom transform type.

BundleContext

As name suggest, with BundleContext, we can get information about bundles which could include existing bundle information, bundle url, HTTP context for bundle, etc. Following is the list of all property of BundleContext.

- BundleContext.BundleCollection : We can get collection of all bundles including default and custom bundle in application through this property.

- BundleContext.BundleVirtualPath : This property expose virtual bundle url i.e. ~/bundles/MyBundle.

- BundleContext.HttpContext : This property is type of HttpContextBase, and we can have access of HTTP context through this property. This is very much useful property when we are creating transform type which generate dynamic response. For e.g. we can access query string parameter passed to bundle url (~/bundles/MyBundle?id=123) through this property (context.HttpContext.Request.QueryString["id"]) and we can use it to create dynamic bundle response.

- BundleContext.UseServerCache : Default value of this property is true. It means only first request to bundle url will be intercepted by transform types and once response is generated it will be stored in server cache and further request to bundle url will be served from server cache without processing it. This will help to reduce bundle processing time and to increase performance. If we set BundleContext.UseServerCache to false then all request will be processed by transform type this is only necessary when bundle url are generating dynamic response. See detailed walkthrough later in this post showing how to use this property in accordance with BundleResponse.Cacheability.

- BundleContext.EnableInstrumentation : Default value of this property is false. This is used for tracing and analysis purpose. We can check value of this property and can write tracing code accordingly. We can also set true to this property to enable instrumentation for further lifecycle of Web optimization frameworks for current bundle request.

BundleResponse

BundleResponse is used to retrieve list of files included in bundle so we can process it and generate response for bundle. As BundleResponse is used to generate response of bundles, it needs to take care of two primary properties of generated response. One is response content type and another one is HTTP Cache-Control header. So BundleResponse also expose properties for the same. Following is the list of all properties in BundleResponse class.

- BundleResponse.Files : This is IEnumerable collection of files which is included in bundle. We can iterate through this collection and process file content to generate bundle response.

- BundleResponse.ContentType : Through this property, we can set content type for bundle so that browser can render it appropriately. Default content type "text/html".

- BundleResponse.Cacheability : We can use this property to set Cache-Control HTTP header of bundled response. Default value of this property is Public.

- BundleResponse.Content : Anything which we set as a value of this property, that content will be sent back to browser as a response of bundle.

Following is the complete code which shows how to create custom transform type and how we can use it with bundling.

public class CustomTransformType : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        string strBundleResponse = string.Empty;
        foreach (FileInfo file in response.Files)
        {
            // PROCESS FILE CONTENT
        }
        response.Content = strBundleResponse;
    }


Bundle myBundle = new Bundle("~/bundles/MyBundle", new CustomTransformType());
myBundle.Include("~/path/to/file");
bundles.Add(myBundle);

Bundle and truly dynamic response

As we noted earlier, we can set BundleContext.UseServerCache to false in order to process all bundle request and generate dynamic response. Let try to simulate this by small walkthrough and see it works or we need to take care any additional parameter.

public void Process(BundleContext context, BundleResponse response)

{
    context.UseServerCache = false;
    response.Content = DateTime.Now.ToString();
}


We are returning current date time with UseServerCache set to false. Now try to hit bundle url multiple times by pressing F5. Oops… it seems it has processed bundle response only first time. Let dig more into this, open another browser and hit same url… ahmm it seems it has processed bundle response one more time… again press F5 multiple times…bad luck

As we can see, it seems (read again it seems) it is processing bundle response only first time for separate client (is it really? nop). Nop this is not the case. In fact this is how client deals with it due to HTTP cache control header. Confused? See response header of bundle url to get more information.

As we noted earlier default value of BundleResponse.Cacheability is Public. So even if we have set BundleContext.UseServerCache to false then also due to Expires response header and Public Cache-Control header client is not sending request back to server. So in this case we need to also set BundleResponse.Cacheability to NoCache. We can also set it to Private but in some client we need to press Ctrl + F5 to refresh bundle response.

public void Process(BundleContext context, BundleResponse response)
{
    context.UseServerCache = false;
    response.Cacheability = HttpCacheability.NoCache;
    response.Content = DateTime.Now.ToString();
}

After setting BundleResponse.Cacheability to NoCache try to refresh bundle url again now it is re generating bundle response on each request.



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