ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET MVC 3 Hosting - ASPHostPortal :: Dependency Injection with Unity 2.0

clock May 3, 2011 06:03 by author Jervis

This blog posts shows a step-by-step instruction how to integrate the Unity 2.0 dependency injection container in an ASP.NET MVC 3 web application.

Create MVC 3 project and add Unity 2.0

Create a new "ASP.NET MVC 3 Web Application" project in Visual Studio 2010. For simplicity, we will use the project template "Internet Application", which adds some some sample controllers and views to the project.

Download Unity 2.0
here from MSDN and run the setup. By default, the setup will extract all Unity files to C:\Program Files (x86)\Microsoft Unity Application Block 2.0\. Copy all dll files from the subfolder bin into your ASP.NET MVC 3 project. It is recommended to save them in a new subfolder (for example "libs") in your project. In detail, the project should now contain the following the dll files:

- Microsoft.Practices.ServiceLocation.dll
- Microsoft.Practices.Unity.Configuration.dll
- Microsoft.Practices.Unity.dll
- Microsoft.Practices.Unity.Interception.Configuration.dll
- Microsoft.Practices.Unity.Interception.dll

In the Solution Explorer, right click on "References" and click on "Add Reference..." and select these five dll files in the tab "Browse" to reference the libraries in your project

Register MVC 3 DependencyResolver

To use the Unity dependency injection container in the newly created ASP.NET MVC 3 project we first need an adapter class, that implements the interface IDependencyResolver and maps the method calls to a concrete Unity dependency injection container (an instance of IUnityContainer, see this post):

public class UnityDependencyResolver : IDependencyResolver
{
  readonly IUnityContainer _container;
  public UnityDependencyResolver(IUnityContainer container)
  {
    this._container = container;
  }
  public object GetService(Type serviceType)
  {
    try
    {
      return _container.Resolve(serviceType);
    }
    catch
    {
      return null;
    }
  }
  public IEnumerable<object>GetServices(Type serviceType)
  {
    try
    {
      return _container.ResolveAll(serviceType);
    }
    catch
    {
      return new List<object>();
    }
  }
}

In the Global.asax.cs file we will set up a Unity dependency injection container in the Application_Start method and use our little adapter class to register the Unity container as the service locator for the ASP.NET MVC application.

protected void Application_Start()
{
  [...] 

  var container = new UnityContainer();
  container.RegisterType<IMessages, Messages>();
  DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

In the above code, we also register a type with the container using the RegisterType method (you can find detailed information about configuring the Unity container and in the MSDN library).
In this simplified example, we just register the type IMessages with the concrete implementation Messages. The next section shows how this type is implemented and used.

Resolving dependencies

To test the dependency resolving, we modify the HomeController.cs and add a new property Messages which is annotated with the Dependency attribute and use this property in the Index action:

public class HomeController : Controller { 

  [Dependency]
  public IMessages Messages { get; set; } 

  public ActionResult Index()
  {
    ViewBag.Message = Messages.Welcome;
    return View();
   } 

  [...]
}

Of course, before we can build our ASP.NET application we need to implement the IMessages interface and Messages class:

public interface IMessages
{
  String Welcome { get; }
} 

public class Messages : IMessages
{
  string IMessages.Welcome
  {
    get { return "Hello world from Unity 2.0!"; }
  }
}

After building and starting the application the Unity dependency injection container should resolve the dependency that is defined in the HomeController and the application's start page should say "Hello world from Unity 2.0!".

I hope you can enjoy this tutorial. If you’re looking for ASP.NET MVC 3 hosting, you can visit our site at
http://asphostportal.com/Cheap-ASPNET-MVC-3-Hosting.aspx.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Global Action Filters in ASP.NET MVC 3

clock April 19, 2011 05:27 by author Jervis

Action Filters are a great way to handle cross-cutting concerns in ASP.NET MVC such as Logging, ExceptionHandling, etc.  In previous versions of MVC3, action filters have to be explicitly added to each controller. 

MVC3 adds the concept of Global Action Filters which allow you to apply action filters globally without the need for explicit declaration.  In this example, we’ll demonstrate how to add a debug action filter attribute that shows debug information for each view using Global Action Filters.

DebugInfoAttribute.cs

/// <summary>
    /// Displays the elapsed time and environment for each executed action in the HTTP Response Stream.
    /// </summary>
    public class DebugInfoAttribute : ActionFilterAttribute
    {
        readonly Stopwatch _startWatch = new Stopwatch();
        private static string _outputFormat = "<h4>Debug Environment Info</h4><div class=\"debuginfo\"><table><tr><td>Web Server:</td><td>{0}</td></tr><tr><td>Browser:</td><td>{1}</td></tr><tr><td>Controller</td><td>{3}</td></tr><tr><td>Action:</td><td>{4}</td></tr><tr><td>Execution Time(ms):</td><td>{5}</td></tr></table></div>";
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _startWatch.Start();
        } 

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            _startWatch.Stop();
            var browser = filterContext.HttpContext.Request.Browser;
            filterContext.HttpContext.Response.Write(string.Format(_outputFormat,
                                                                   HttpContext.Current.Request.ServerVariables[
                                                                       "SERVER_NAME"],
                                                                   String.Format("{0} ({1})",browser.Browser,browser.Version),
                                                                       filterContext.RouteData.Values["controller"],???????????????
                                                                       filterContext.RouteData.Values["action"],
                                                                       _startWatch.ElapsedMilliseconds));
        }
    }

This action filter uses the StopWatch object to clock how long the action took to execute, and displays that information in a view.

It’s applied normally by adding the “DebugInfo” attribute to the top of a controller class, as below.

[DebugInfo]
    public class HomeController : Controller

This results in the output seen below on our views:



If we click the “LogOn” link on our default application, we won’t see this information as we haven’t applied this filter to the “Account” controller.  Lets see how we can set an action filter to display gloablly.

Registering Global Action Filters

MVC3 adds a new function into our Global.asax called Register Global Filters.  To apply a filter globally, simply add a new line specifying your action filter as below.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new DebugInfoAttribute());
        }

Now, when we click on the “Log On” link, we can see the DebugInfo filter has been automatically applied to the Account controller.



Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: How to Install ASP.NET MVC 3

clock April 18, 2011 07:22 by author Jervis

Microsoft's release of ASP.NET MVC 3 offers developers a new and improved framework for building web applications in the Model-View-Controller pattern. As expected, ASP.NET MVC 3 comes with many new features that improve on the ones present in MVC 1 and 2. It can also be installed side-by-side with ASP.NET MVC 2. Before we discuss ASP.NET MVC 3's installation process, let's discuss some of the framework's new features first.

The new Razor view engine comes with plenty of useful features within itself, such as HTML helpers.  It is based on well-known languages such as Visual Basic and C#, so its learning curve is minimal.  The view engine also helps to improve efficiency by cutting down on keystrokes with syntax that is short and to the point.  You can unit test Razor views without having to run an application or launch a web server as well.

ASP.NET MVC 3 also offers support for multiple view engines and implements various controller improvements. The new ViewBag property is one controller improvement that is similar to the ViewData property, but offers a simpler syntax.  Other controller improvements in MVC 3 include some new ActionResult types and global action filters.

The realms of JavaScript and Ajax have drawn some improvements as well.  For example, client-side validation is now enabled by default, and JSON binding support has been integrated.  ASP.NET MVC 3's other highlights include better support for dependency injection, model validation improvements, partial-page output caching, sessionless controller support, and more.

Now that you have a preview of some of the improvements that ASP.NET MVC 3 has to offer, it's time to download and install the framework.

To begin installing ASP.NET MVC 3, visit the following link:

http://www.microsoft.com/web/gallery/install.aspx?appid=MVC3

Before you start the download, there are some system requirements to keep in mind.  For the installer to work, you will need to have administrator privileges on your computer.  You will also need to be using one of the following operating systems:

Windows 7, Windows Vista, Windows Vista SP1, Windows XP SP2+, Windows Server 2008, Windows Server 2008 R2, or Windows Server 2003 SP1+.



Begin the installation by clicking on Install Now.  Depending on which internet browser you are using, you may be asked to either save the installer file or run it.  After you have saved the file and it has downloaded, locate it and double-click to begin the installation using Microsoft's Web Platform Installer.



Once the installer appears, click Install.



A window will appear that displays the different components that will be installed.  Once you have looked over the components, click I Accept.  The installation should now begin.  The process could take a while, so give it some time to complete.



After the installation is completed, a congratulations window will appear.  Click Finish to exit the installation.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Handling Forms in Spring 3.0 MVC

clock April 11, 2011 05:55 by author Jervis

Getting Started

Let us add the contact form to our Spring 3 MVC Hello World application. Open the index.jsp file and change it to following:


File: WebContent/index.jsp

<jsp:forward page="contacts.html"></jsp:forward>

The above code will just redirect the user to contacts.html page.


The View- contact.jsp

Create a JSP file that will display Contact form to our users.
File: /WebContent/WEB-INF/jsp/contact.jsp

<[email protected] uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">   

    <table>
    <tr>
        <td><form:label path="firstname">First Name</form:label></td>
        <td><form:input path="firstname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Last Name</form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Email</form:label></td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Telephone</form:label></td>
        <td><form:input path="telephone" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Add Contact"/>
        </td>
    </tr>
</table>  
  
</form:form>
</body>
</html>

Here in above JSP, we have displayed a form. Note that the form is getting submitted to addContact.html page.

Adding Form and Controller in Spring 3

We will now add the logic in Spring 3 to display the form and fetch the values from it. For that we will create two java files. First the Contact.java which is nothing but the form to display/retrieve data from screen and second the ContactController.java which is the spring controller class.



File: net.viralpatel.spring3.form.Contact

package net.viralpatel.spring3.form;
  
public class Contact {

    private String firstname;
    private String lastname;
    private String email;
    private String telephone;   

    //.. getter and setter for all above fields.

}

The above file is the contact form which holds the data from screen. Note that I haven’t showed the getter and setter methods. You can generate these methods by pressiong Alt + Shift + S, R.

File: net.viralpatel.spring3.controller.ContactController

package net.viralpatel.spring3.controller;   


import net.viralpatel.spring3.form.Contact;   

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;   

@Controller
@SessionAttributes
public class ContactController {   

    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
                            Contact contact, BindingResult result) {   

        System.out.println("First Name:" + contact.getFirstname() +
                    "Last Name:" + contact.getLastname());   

        return "redirect:contacts.html";
    }   

    @RequestMapping("/contacts")
    public ModelAndView showContacts() {   

        return new ModelAndView("contact", "command", new Contact());
    }
}

In above controller class, note that we have created two methods with Request Mapping /contacts and /addContact. The method showContacts() will be called when user request for a url contacts.html. This method will render a model with name “contact”. Note that in the ModelAndView object we have passed a blank Contact object with name “command”. The spring framework expects an object with name command if you are using
in your JSP file.


Also note that in method addContact() we have annotated this method with RequestMapping and passed an attribute method=”RequestMethod.POST”. Thus the method will be called only when user generates a POST method request to the url /addContact.html. We have annotated the argument Contact with annotation @ModelAttribute. This will binds the data from request to the object Contact. In this method we just have printed values of Firstname and Lastname and redirected the view to cotnacts.html.

That’s all folks

The form is completed now. Just run the application in eclipse by pression Alt + Shift + X, R. It will show the contact form. Just enter view values and press Add button. Once you press the button, it will print the firstname and lastname in sysout logs.



Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Tutorial - Getting Started with Spring 3 MVC

clock April 6, 2011 06:16 by author Jervis

The Spring Framework is constantly evolving. Spring MVC has gotten easier and easier to work with and with the SpringSource Tool Suite it gets even easier to get a Spring MVC project up and running. Today I’ll show you how to setup a simple Spring MVC project and add some simple functionality to it.

There are a few things you’ll need to complete this tutorial:

Java JDK installed
SpringSource Tool Suite – I downloaded the installer version, not the plug-in to Eclipse

With those two items installed and ready go ahead and run the SpringSource Tool Suite and create a new project: File -> New -> Spring Template Project



Note: It might prompt you to download the template, go ahead and let it do that.



Once the project has been created we can test out the default Hello World code that is already in-place. Lets add the project to the
SpringSource tc Server and then start it.



Once the SpringSource tc Server is up and running open a browser and head to this url:
http://localhost:8080/EchoSpringMVC/

If everything went well you should see this:









You can leave the SpringSource tc Server running.

Open the HomeController.java file now and add the following imports:

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;

Lets add a new mapping and method for the echo functionality we are going to add.

@RequestMapping(value="/echo", method=RequestMethod.GET)
public String echo(@RequestParam("input1") String input1, Model model) {
    logger.info("Calling echo");
    String output = "Echo: " + input1;
    model.addAttribute("output", output);
    return "echo";
}

We set the mapping to handle any GET requests to echo. The echo method takes one parameter called input1 which we simply use to complete the echo functionality. The echo is passed back to the view (which we will create next).

Your HomeController.java should look like this:

package com.giantflyingsaucer.springmvc;   

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;   

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {   

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

      /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value="/", method=RequestMethod.GET)
    public String home() {
        logger.info("Welcome home!");
        return "home";
    }   

    @RequestMapping(value="/echo", method=RequestMethod.GET)
    public String echo(@RequestParam("input1") String input1, Model model) {
        logger.info("Calling echo");
        String output = "Echo: " + input1;
        model.addAttribute("output", output);
        return "echo";
    }
}

Lets add a new JSP page for our echo view. Right-click on the webapp/WEB-INF/views folder and select:
New -> Other -> Web -> JSP File



Here are the contents for the new echo.jsp file:


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <title>Echo</title>
</head>
<body>
<h1>
    <strong><c:out value="${output}"></c:out></strong>
</h1>
</body>
</html>

Save all the files and the SpringSource tc Server will reload the project automatically. When this has happened use this URL to trigger the echo: http://localhost:8080/EchoSpringMVC/echo?input1=HelloWorld

Your result should be:



Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Problem in implementing IControllerActivator in ASP.NET MVC 3

clock April 5, 2011 07:30 by author Jervis

ASP.NET MVC 3 introduces two new interfaces to allow simple integration of IoC containers into the MVC pipeline, allowing many different types to be resolved using your IoC container of choice. These interfaces are IDependencyResolver and IControllerActivator but before you go ahead and implement both, let’s take a look at whether they are both actually needed.

First some background

If you wanted to inject dependencies into your controllers in ASP.NET MVC 2, you were required to either implement IControllerFactory or subclass DefaultControllerFactory. Typically, you would pass your IoC container into the constructor of your custom controller factory and use it to resolve the controller in the CreateController method. You may also have added custom code in ReleaseController to clean up dependencies

This worked reasonably well, but in ASP.NET MVC 3 things have changed so we can use DI for a whole host of other objects such as filters and view engines

The new interface that we should implement is IDependencyResolver:



The important thing about your implementation of this interface is that it should return null if it cannot resolve a particular object. Below is a simple implementation using Unity:



When an MVC application starts for the first time, the dependency resolver is called with the following types in the following order:
- IControllerFactory
- IControllerActivator
- HomeController
….

If you do not implement IControllerFactory or IControllerActivator, then the MVC framework will try to get the controller from the DependencyResolver itself. As a side note, there is no need to worry about performance (regarding so many calls to the resolver) because MVC will only try to resolve theIControllerFactory and IControllerActivator once on startup and if no implementations are registered then it will subsequently always query the DependencyResolver first

The MVC framework goes on to try to resolve many other types which you probably have not implemented or registered with your IoC container, but as long as your dependency resolver returns null if the type is not registered, MVC will default back to the built-in implementations

If you did not implement your resolver to return null if a type is not registered then you will probably end up seeing an error similar to:

The current type, System.Web.Mvc.IControllerFactory, is an interface and cannot be constructed

The other important thing to note is that both methods on this interface take in the actual service type. This typically means that when you register your controllers with your IoC container, you should only specify the concrete type, not the IController, interface

i.e. using Unity as an example:



rather than:



Failing to register your controllers conrrectly and you will see

No parameterless constructor defined for this object

So at this stage, we have an implementation of IDependencyResolver and nothing else and yet our controller are all resolving correctly. It makes you wonder about whether IControllerActivator is really needed…

About IControllerActivator


IControllerActivator was introduced with ASP.NET MVC 3 to split the functionality of the MVC 2 controller factory into two distinct classes. As far as we can tell, this was done to adhere to the Single Responsibility Principle (SRP). So now in MVC 3, the DefaultControllerFactory outsources the responsibility of actually instantiating the controller to the controller activator. The single method interface is shown below:



If you implement this interface and register your activator with your IoC container, the MVC framework will pick it up and use it when trying to instantiate controllers, but you have to wonder why you would do this instead of just letting your dependency resolver do it directly. Brad Wilson to the rescue:

“If your container can build arbitrary types, you don’t need to write activators. The activator services are there for containers that can’t be arbitrary types. MEF can’t, but you can add [Export] attributes to your controllers to allow MEF to build them…”


This means that if you are working with any competent IoC container* (Castle Windor, Unity, Ninject, StructureMap, Autofac et al), IControllerActivator is not needed and offers no benefit over allowing your DependencyResolver to instantiate your controllers.

* (With the exception of MEF which isn’t an IoC container any way)

So we now know that we are probably not required to implement this interface, but are there any benefits to doing so? Something that we have seen mentioned (we cannot remember where) is that implementing IControllerActivator allows you you can provide a more meaningful error message if resolution fails. It is true that the message you would get otherwise (No parameterless constructor defined for this object) is not 100% clear, but we are not sure that this justifies another class just for this purpose. Surely, once you have seen this message, the next time you encounter, it you will immediately know what the problem is. Even if you do implement IControllerActivator, you will not have access to the (normally) detailed message that you IoC container provides when resolution fails, so you can do little more than say resolution failed – i don’t know why.

Conclusion


So, should you implement IControllerActivator? Probably not. If you are using pretty much any well known IoC container, just implement IDependencyResolver and it will do everything for you. There is also no need for a custom implementation of IControllerFactory. If you are worried about the lack of release method on the dependency resolver, don’t be. The worst case scenario requires a small change to the way that you are using your IoC container. Next time we will talk about how to make sure your dependency resolver plays nicely with IDisposable.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in