ASPHostCentral.com ASP.NET MVC Hosting BLOG

All about ASP.NET MVC 4.0 Hosting, ASP.NET MVC 3.0 Hosting and ASP.NET MVC Hosting articles

ASP.NET MVC 3.0 Hosting :: Working with ServiceLocator in ASP.NET MVC 3.0

clock December 16, 2010 12:56 by author Administrator

For past couple of days we were checking out features of the new ASP.NET MVC Preview 3.There are couple of interesting new additions like integration with the new Razor viewengine,improvements in Model Validation,AJAX support and Dependency Injection. In this post we will discuss on, how ASP.NET MVC 3 has streamlined the ability to register/retrieve objects/services in a loosely coupled manner by incorporating support for the Common Service Locator framework.

What is Common Service Locator?Today we have many Inversion of Control/Dependency Injection Containers like NInject,StructureMap,Unity,.. etc in the .NET world.Most of these vary quite widely in terms of configuration and initialization/registration of the instances.But they provide more or less similar interface while resolving the dependencies and returning object instances.Common Service Locator framework extracts these commonalities out and provides an abstraction on top of these IoC/DI containers.This is now part of the Enterprise Library 5.0 and used in the Enterprise Library code to create/retrieve objects.Common Service Locator provides an interface IServiceLocator


It is quite evident from the method signatures that these are only related to retrieval of right object instances with proper resolution of the dependencies based upon different parameters.

Another important class related to the Common Service Locator is the ActivationException which needs to be thrown whenever there is exception in instantiating the objects /resolving the dependencies.

We were planning to use StructureMap as the DI Container and a StructureMap Adapter for Service Locator was available in Codeplex but that seemed far from complete.

So we went ahead to write few lines of code and develop a service locator which will use StructureMap as the DI container as shown below:

 

This class accepts an instance of the StructureMap.Container in the constructor and uses it to resolve dependencies and instantiate objects.In the implementation of the IServiceLocator methods we have to just map them suitably to StructureMap.Container.GetAllInstances and StructureMap.Container.GetInstance methods (and their overloads).The code which depends on IServiceLocator will perform exception handling based on ActivationException class whereas StructureMap raises StructureMap.StructureMapException in most of the cases.So we need to catch StructureMapException in this class and throw a ActivationException.The complete code is given below:

 

So we have our Service Locator class ready.In next part of the post we will see how we can plug this into the ASP.NET MVC 3.0 Framework

Currently rated 1.9 by 18 people

  • Currently 1.888889/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting :: Introduction to ASP.NET MVC 3 Service Location

clock November 18, 2010 11:42 by author Administrator

Introduction

One of the new features in ASP.NET MVC 3 is the ability to register a service locator that will be used by the framework. Prior versions of the MVC framework have offered opportunities for introducing concepts like service location and dependency injection (DI); in MVC 3, we have formalized the process and opened up several new opportunities for developers

This first post in the series will discuss the general strategy for service location in MVC 3. Later posts will discuss specific ways to perform service location and DI with existing and new features

ASP.NET MVC 3 Hosting

Disclaimer

This blog post talks about ASP.NET MVC 3 Preview 1, which is a pre-release version. Specific technical details may change before the final release of MVC 3. This release is designed to elicit feedback on features with enough time to make meaningful changes before MVC 3 ships


General Strategy

The most important part of the strategy with service location is that it's going to be optional. This means that if you are not interested in working with a service locator, you won't be forced to. We will always offer a way to perform customization functions without requiring you to employ a service locator. We will also work to preserve backward compatibility as much as possible when introducing new service location capability into existing features of MVC

When using the registered service locator, MVC will generally employ one of three strategies, depending on the kind of work it's trying to do

1. Locating a singly registered service


There are several services which MVC uses today which have the ability to register a single instance of such a service. One example is the controller factory, which implements IControllerFactory. There is a single controller factory that's used for the entire application

When MVC attempts to use a singly registered service, it will first ask the service locator whether it has an instance of that service available. If it does, then MVC will use that; if it does not, then it will fall back to the singleton registration that's available for non-service locator users

The upside of this means that service locator users won't be required to fill their locator/container with all the existing default services used by MVC, because it will automatically fall back to these defaults when nothing exists in the locator. The potential downside of this means that it is theoretically possible to register a custom service in both places, but only the one in the locator will be used

2. Locating a multiply registered service


There are several services which MVC uses today which have the ability to register multiple instances of such a service. One example of this is the view engine, which implements IViewEngine. Typically, MVC offers a registration point which acts like a list of such services, and also offers an API which acts as a facade and figures out the appropriate way to do the work. In the case of view engines, this facade (ViewEngines.Engines) takes the form of "go to each view engine on the list and ask it for a view until one of them can provide it". There are also multiply registered services where the facade uses all the services (ModelValidatorProviders.Providers) and aggregates all the responses together

When MVC attempts to use a multiply registered service, it will continue to ask the collection facade to do the work. The collection facade will use both the statically registered instances of the service as well as any of the instances registered with the service locator, and combines them together in the way that is most appropriate for the facade. Where service order is important (as with view engines, for example), this usually means that the service locator instances will come before the statically registered instances

Like the single registration strategy, the upside of this means that service locator users won't be required to fill their locator/container with the existing default service instances. The potential downside of this is that most containers don't offer a native ordering function for multi-registration of services, so where ordering is important, it may be necessary to use the non-service locator APIs. In practice, however, it probably won't be much of an issue, as most applications don't generally need to rely on ordering (for example, they will only primarily use a single view engine), especially since service locator services generally go before the existing pre-registered services

3. Creating arbitrary objects

The final way that MVC may use a service locator is in the creation of arbitrary objects. (This is where we stray from the strictly service location functionality and use it more like a dependency injection container.) Where we've found it appropriate that an object we create may be in need of dependency injection of services, we will attempt to create that object through the service locator. One example is controller objects, which may want to take service dependencies to do their work

When MVC attempts to create an arbitrary object in this way, it will ask the service locator to create the object on its behalf. If the service locator cannot fulfill this object creation, it will generally fall back to the existing behavior in prior versions of MVC 2; usually, this means calling Activator.CreateInstance



IMvcServiceLocator and MvcServiceLocator

To enable service location in MVC, we've introduced a new interface (IMvcServiceLocator) and a new static singleton registration class (MvcServiceLocator). For Preview 1, we have also replicated the existing Common Service Locator interface (IServiceLocator) and exception class (ActivationException) in the System.Web.Mvc namespace

public interface IServiceLocator : IServiceProvider { 
    IEnumerable<TService> GetAllInstances<TService>(); 
    IEnumerable<object> GetAllInstances(Type serviceType); 
    TService GetInstance<TService>(); 
    TService GetInstance<TService>(string key); 
    object GetInstance(Type serviceType); 
    object GetInstance(Type serviceType, string key);
  
public interface IMvcServiceLocator : IServiceLocator { 
    void Release(object instance);
  
public static class MvcServiceLocator { 
    public static IMvcServiceLocator Current { get; } 
    public static IMvcServiceLocator Default { get; } 
    public static void SetCurrent(IServiceLocator locator);

The registration point is MvcServiceLocator.SetCurrent(), and only requires the service locator to support IServiceLocator. However, you'll notice that MvcServiceLocator.Current always returns an implementation of IMvcServiceLocator. We will automatically create the implementation of IMvcServiceLocator.Release() if one does not exist, which will call Dispose on the object if it implements Idisposable

It's also worth noting that there will always be a service locator available, even if you've never registered one. Our default service locator is not a full fledged service locator, as it only calls Activator.CreateInstance and offers no registration system. It is not meant to be a replacement for a real service locator or dependency injection container


No Configuration

MVC's usage of service location is limited to retrieving services. MVC has no need to configure the existing service locator. As such, we have made no effort to hide the configuration/registration process inherent to existing service locators or DI containers

We feel that most people will choose the container they want to use based on its registration and configuration APIs, so attempting to hide them would be counter productive


Complex Dependency Injection Needs

A common question might be why we chose to use Common Service Locator, when many container offer the ability to have extremely complex dependency injection systems (for example, nested containers for lifetime management tied to request lifetime).

Whenever possible, we will continue to offer factory-style services to allow complex dependency injection needs. For example, we will continue to offer IControllerFactory as a service, even though most users will be able to just registered their service locator without need to provide a custom controller factory any more. If you do need complex lifetime management, though, you can still opt to provide a controller factory which gives the flexibility to open up those complex creation options

Open Question: To Common Service Locator Or Not?


We are currently debating internally as to whether or not to take the dependency on CSL. The advantage would be that container users would be able to leverage the existing implementations of CSL that most dependency injection containers come with (although they would need to add the implementation of IMvcServiceLocator, if desired). The disadvantage is that it creates a runtime dependency on an additional DLL that is not likely to be on the developer's machine or on the server, since CSL is not part of the .NET Framework. This slightly complicates the bin deployment story for MVC by adding a new DLL to remember to deploy, which would need to be in place whether the user uses a service locator or not.

Currently rated 1.0 by 1 people

  • Currently 1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3.0 Hosting :: Working with RAZOR Model Keyword in ASP.NET MVC 3.0

clock November 8, 2010 16:08 by author Administrator

Razor is the new view engine that is available for ASP.NET MVC 3 Beta. Razor has directives that are the same as the WebForms view engine, so you can define namespaces at the top of the Razor file so you don’t have to use the fully qualified name when referencing objects. One of the keywords available is the new @model keyword. This keyword defines the model that is being used in the view. By default the default value is dynamic, which means you’re using a dynamic model for your view. However you can change this so you can use a strongly typed view. This article will demonstrate how to use both

ASP.NET MVC 3.0 Hosting

Before moving on, you need to download ASP.NET MVC 3 Beta and NuPack. Click
here to download and install them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. The new MVC 3 Beta dialog can be seen below

ASP.NET MVC 3.0 Hosting

Choose Razor as the view engine and click OK

We’re going to add a model called FavouriteGivenName which will store the most popular given names in Australia for 2009. We’re going to add a new controller named MostPopular and add the following code:


private readonly List<FavouriteGivenName> _mostPopular = null;
        public MostPopularController()
        {
            _mostPopular = new List<FavouriteGivenName>()
                {
                    new FavouriteGivenName() {Name = "Jack"},
                    new FavouriteGivenName() {Name = "Riley"},
                    new FavouriteGivenName() {Name = "William"},
                    new FavouriteGivenName() {Name = "Oliver"},
                    new FavouriteGivenName() {Name = "Lachlan"},
                    new FavouriteGivenName() {Name = "Thomas"},
                    new FavouriteGivenName() {Name = "Joshua"},
                    new FavouriteGivenName() {Name = "James"},
                    new FavouriteGivenName() {Name = "Liam"},
                    new FavouriteGivenName() {Name = "Max"}
                };
        }

        public ActionResult DynamicView()
        {
            return View(_mostPopular);
        }

We’ll add a new view, but we won’t select Create a strongly-typed view

ASP.NET MVC 3.0 Hosting

Upon completion the view’s HTML is the following


@model dynamic
@{
    View.Title = "DynamicView";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";
}

<h2>Dynamic View</h2>

You’ll notice in the code above, the first line contains the @model keyword and it’s dynamic.

@model dynamic


This means you won’t have access to a strongly-typed object when you code this view. You can use the following code to render the popular names to the view.

@model dynamic
@{

    View.Title = "DynamicView";

    Layout = "~/Views/Shared/_LayoutPage.cshtml";

}

<h2>Dynamic View</h2>

<p>
      @foreach(var givenName in Model) {

            @givenName.Name <br />

      }

</p>


ASP.NET MVC 3.0 Hosting

On the other hand you wanted a strong-typed view and not rely on dynamic views, it’s easy. Add another action and create a new view, but this time select Create a strongly-typed view

ASP.NET MVC 3.0 Hosting

By default you’ll now have a strongly typed view as shown in the code snippet below

@model IEnumerable<MvcApplication5.Models.FavouriteGivenName>

@{

    View.Title = "StronglyTypedView";

    Layout = "~/Views/Shared/_LayoutPage.cshtml";

}

<h2>Strongly Typed View</h2>

Now the model is a list of strongly-typed FavouriteName objects. Intellisense doesn’t work in the beta version, so we are unable to show you the benefits of using a strongly-typed view. You can use the following code to render the favourite given names:

@model IEnumerable<MvcApplication5.Models.FavouriteGivenName>
@{
    View.Title = "StronglyTypedView";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";
}

<h2>Strongly Typed View</h2>
<p>
      @foreach(var givenName in Model) {
            @givenName.Name <br />
      }
</p>

The @model keyword is easy to miss when you’re using the beta version of ASP.NET MVC 3 Beta, but it’s something you’ll learn once and never forget it’s there.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC 3 Hosting with ASPHostCentral.com

clock September 29, 2010 15:11 by author Administrator

Brief Description

ASP.NET MVC 3 Preview 1 provides a new Model-View-Controller (MVC) framework on top of the existing ASP.NET 4 runtime


Overview


ASP.NET MVC 3 is a framework for developing highly testable and maintainable Web applications by leveraging the Model-View-Controller (MVC) pattern. The framework encourages developers to maintain a clear separation of concerns among the responsibilities of the application – the UI logic using the view, user-input handling using the controller, and the domain logic using the model. ASP.NET MVC applications are easily testable using techniques such as test-driven development (TDD).

The installation package includes templates and tools for Visual Studio 2010 to increase productivity when writing ASP.NET MVC applications. For example, the Add View dialog box takes advantage of customizable code generation (T4) templates to generate a view based on a model object. The default project template allows the developer to automatically hook up a unit-test project that is associated with the ASP.NET MVC application.
Because the ASP.NET MVC framework is built on ASP.NET 4, developers can take advantage of existing ASP.NET features like authentication and authorization, profile settings, localization, and so on


System Requirements


Supported Operating Systems:
Windows 7;Windows Server 2003;Windows Server 2008;Windows Vista

.NET 4, ASP.NET 4, Visual Studio 2010 or Visual Web Developer 2010 are required to use certain parts of this feature


Instructions


For more information about installing the release, see the ASP.NET MVC 3 Preview 1 Release Notes


Top Reasons to trust your ASP.NET MVC 3 website to ASPHostCentral.com


What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC 3 Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Currently rated 1.5 by 4 people

  • Currently 1.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: 13 ASP.NET MVC Extensibility Points You Must to Know

clock April 29, 2010 14:37 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site.

One of the main design principles ASP.NET MVC has been designed with is extensibility. Everything (or most of) in the processing pipeline is replaceable so, if you don’t like the conventions (or lack of them) that ASP.NET MVC uses, you can create your own services to support your conventions and inject them into the main pipeline.

In this post we are going to show 13 extensibility points that every ASP.NET MVC developer should know, starting from the beginning of the pipeline and going forward till the rendering of the view.

1. RouteConstraint

Usually you could put some constrains on url parameters using regular expressions, but if your constrains depend on something that is not only about the single parameter, you can implement the
IRouteConstrains’s method and put your validation logic in it.

One example of this is the validation of a date: imagine an url that has year, month and date on different url tokens, and you want to be able to validate that the three parts make a valid date.

2. RouteHandler

Not really specific to ASP.NET MVC, the
RouteHandler is the component that decide what to do after the route has been selected. Obviously if you change the RouteHandler you end up handling the request without ASP.NET MVC, but this can be useful if you want to handle a route directly with some specific HttpHanlders or even with a classic WebForm.

3. ControllerFactory

The controller factory is the component that, based on the route, chooses which controller to instantiate and instantiate it. The default factory looks for anything that implements
IController and whose name ends with Controller, and than create an instance of it through reflection, using the parameter-less constructor.

But if you want to use Dependency Injection you cannot use it, and you have to use a IoC aware controller factory: there are already controller factory for most of the IoC containers. You can find them in MvcContrib or having a look at the Ninject Controller Factory.

4. ActionInvoker

ActionInvoker is responsible for invoking the action based on it’s name. The default action invoker looks for the action based on the method name, the action name and possibly other selector attributes. Then it invokes the action method together with any filter defined  and finally it executes the action result.

If you read carefully you probably understood that most of the execution pipeline is inside the logic of the default
ControllerActionInvoker class. So if you want to change any of these conventions, from the action method’s selection logic, to the way http parameters are mapped to action parameters, to the way filters are chosen and executed, you have to extend that class and override the method you want to change.

5. ActionMethodSelectorAttribute

Actions, with the default action invoker, are selected based on their name, but you can finer tune the selection of actions implementing your own Method Selector. The framework already comes with the
AcceptVerbs attribute that allows you to specify to which HTTP Verb an action has to respond to.

A possible scenario for a custom selector attribute is if you want to choose one action or another based on languages supported by the browser or based on the type of browser, for example whether it is a mobile browser or a desktop browser.

6. AuthorizationFilter

These kind of filters are executed before the action is executed, and their role is to make sure the request is “valid”.

There are already a few Authorization filters inside the framework, the most “famous” of which is the
Authorize attribute that checks whether the current user is allowed to execute the action. Another is the the ValidateAntiForgeryToken that prevents CSRF attacks. If you want to implement your own authorization schema, the interface you have to implement is IAuthorizationFilter. An example could be the hour of the day.

7. ActionFilter

Action Filters are executed before and after an action is executed. One of the core filters is the
OutputCache filter, but you can find many other usages for this filter. This is the most likely extension point you are going to use, as, IMHO, it’s critical to a good componentization of views: the controller only has to do its main stuff, and all the other data needed by the view must be retrieved from inside action filters.

8. ModelBinder

The default model binder maps HTTP parameters to action method parameters using their names: a http parameter named user.address.city will be mapped to the City property of the Address object that itself is a property of the method parameter named user. The
DefaultModelBinder works also with arrays, and other list types.

But it can be pushed even further: for example you might use it to convert the id of the person directly to the Person object looking up on the database. This approach is explained better in the following post Timothy Khouri (aka SingingEels): Model Binders in ASP.NET MVC. The code is based on the preview 5, but the concept remains the same.

9. ControllerBase

All controllers inherit from the base class
Controller. A good way to encapsulate logic or conventions inside your actions is to create you own layer supertype and have all your controllers to inherit from it.

10. ResultFilter

Like the ActionFiters, the ResultFilters are execute before and after the ActionResult is executed. Again, the OutputCache filter is an example of a ResultFilter. The usual example that is done to explain this filter is logging. If you want to log that a page has been returned to the user, you can write a custom RenderFilter that logs after the ActionResult has been executed.

11. ActionResult

ASP.NET MVC comes with many different kind of results to render views, to render JSON, plain text, files and to redirect to other actions. But if you need some different kind of result you can write your own
ActionResult and implement the ExecuteResult method. For example, if you want to send a PDF file as result you could write your own ActionResult that use a PDF library to generate the PDF. Another possible scenario is the RSS feed: read more about how to write a RssResult in this post.

Look at implementing a custom action result when the only peculiarity is how the result is returned to the user.

12. ViewEngine

Probably you are not going to write your own view engine, but there are a few that you might consider using instead of the default WebForm view engine.

13. HtmlHelper

Views must be very dumb and thin, and they should only have html markup and calls to HtmlHelpers. There should be no code inside the views, so helpers come very handy for extracting the code from the view and putting it into something that is testable.

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Currently rated 1.8 by 26 people

  • Currently 1.769231/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: An Architectural View of the ASP.NET MVC Framework

clock April 27, 2010 19:35 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site.

Introduction

At DevConnections Fall and TechEd Europe, Microsoft recently unveiled the ASP.NET MVC Framework. MVC stands for Model-View-Controller and is one of the most popular design patterns for decoupling data access and business logic from data presentation and user interaction. At the time of this writing, the framework is not available yet, not even as a CTP. However, the first CTP is expected to ship in just a few weeks.

In any case, the ASP.NET MVC Framework is definitely worth a look since it addresses aspects of programming that are extremely important for developers and their productivity such as code reusability, testing, and separation of presentation and business logic concerns. At the same time, an early look at the MVC Framework may generate good feedback to Microsoft and help them to deliver a better and richer product in full accordance with the community expectations and needs.

Motivating the Hype on MVC

Most applications, and especially Web applications, have their presentation layer mixed up with some business logic and data access code. As an example, think of a classic ASP.NET page. You define the user interface by composing and configuring server controls until you obtain the desired markup. Next, you use a code-behind class to add some handlers for the various events fired by controls and provide any required glue code. In such pages, more often than not, data access code is interspersed with presentation logic. In ASP.NET 2.0, the introduction of data source controls certainly didn't make this mixture more unlikely. Some data source controls, such as the SqlDataSource control, are a sinful temptation for developers as they see in it the way to go down to SQL queries and stored procedures - the raw data - very quickly. Without beating the bush around, such ASP.NET pages whose code-behind classes contain a mixture of presentation, business and data access code, are quite difficult to maintain. And they are definitely challenging to test appropriately.

User interface facilities (i.e., wizards and tools in Visual Studio) tend to encourage developers to put in the presentation layer more than it should. The presentation layer acts as a catch-all for logic that reasonably belongs to other layers. At the end of the day, you can still have the application working and perform well. Behind the scene, though, you get a too high level of coupling and subsequently high costs of maintenance. What if, in fact, at some point you need to add a new feature or re-implement an existing one? Not having a well designed structure of classes and lacking a clean separation of presentation, business and data layers, most that you can do is cutting and pasting code and run pages over and over again to test results against expectations.

There's not much of reusability too, but quite the reverse we'd say. Code duplication is not unlikely and the need of changing the view for the same data may often result in serious trouble.

Sure, there are architectural design patterns to give you guidance on the best way to design Web applications with cleanly separated layers. However, these patterns require a lot of coding, sometimes repetitive code, which doesn't always sit well with the rush of delivering applications that just work. While the startup costs of implementing recognized patterns manually will certainly pay you off in the context of complex enterprise applications, it seems to be an unnecessary complication in simpler, but still realistic, scenarios.

The classic code-behind model of ASP.NET provides the tools for building great and well-designed applications, but it leaves most of it up to the individual developer or team. As a result, too many applications out there work well, but are not well designed. Over the years, this fact raised the need of a radically different approach to Web programming. The MVC pattern was soon identified as an excellent approach to Web development. MVC ensures a clean separation between the data model and the user interface in such a way that changes to the user interface don't affect data handling. At the same time, the data model and related access code can be refactored without the need of changing the user interface accordingly.

Where Did We See This Already?

Tools like Castle MonoRail have been created to simplify Web development by leveraging the MVC pattern. Where's the difference between MonoRail and ASP.NET? It mostly lies in an extremely simplified form of the code that backs a page up. It's like breaking the code you have in, and reference from, the code-behind class into distinct elements. The controller handles application flow; the model represents the data; the view takes care of presentation. The underlying engine automates some tasks for you (i.e., binding data to form elements) and exposes just plugs for you to connect and customize the engine. As a result, you write less code and have highly specialized components that are easier to test and maintain.  

At the same time, MonoRail is not necessarily better than Web Forms and may not be the right choice for just everybody. Because it propounds a different paradigm, it may not be the ideal environment for those who have strong ASP.NET skills and find it difficult (or just not affordable) to convert large applications.

By the way, regardless of the Mono prefix in the name there's no necessary connection between this project and the Mono project aimed at providing the code to run .NET applications on multiple platforms.

Comparing the MVC Framework to Classic ASP. Net

The ASP.NET MVC Framework is essentially the Microsoft's attempt to create an ASP.NET programming environment centered around the MVC pattern. For the time being (nobody can reasonably foresee future evolutions), the MVC Framework should be considered an alternative to Web Forms. To some extent, the MVC Framework and Web Forms have in common more or less what cars and motorcycles share. Both can take you somewhere else, but with different speed, comfort, sense of freedom, size of the trunk.

The MVC Framework doesn't support classic postbacks and viewstate and doesn't consider any URL as the endpoint to a physical server file to parse and compile to a class. In ASP.NET, you have a 1:1 correspondence between a URL and a resource. The only exception to this rule is when you use completely custom HTTP handlers bound to a particular path.

In the MVC Framework, a URL is seen as the mean to address a logical server resource, but not necessarily an ASPX file to parse. So the URLs employed by the pages of an MVC Framework application have a custom format that the application itself mandates. In the end, the MVC Framework employs a centralized HTTP handler that recognizes an application-specific syntax for links. In addition, each addressable resource exposes a well-known set of operations and a uniform interface for executing operations.

Have you ever heard about Representational State Transfer, or REST for short?

Well, REST is an architectural pattern that defines how network resources should be defined and addressed in order to gain shorter response times, clear separation of concerns between the front-end and back-end of a networked system. REST is based on three following principles:

1. An application expresses its state and implements its functionality by acting on logical resources
2. Each resource is addressed using a specific URL syntax
3. All addressable resources feature a contracted set of operations

As you can see, the MVC Framework fulfills it entirely.

So here's an alternate way of looking at the MVC Framework. It is an ASP.NET framework that performs data exchange by using a REST model versus the postback model of classic ASP.NET. Each page is split into two distinct components -controller and view - that operate over the same model of data. This is opposed to the classic code-behind model where no barrier is set that forces you to think in terms of separation of concerns and controllers and views. However, by keeping the code-behind class as thin as possible, and designing the business layer appropriately, a good developer could achieve separation of concerns even without adopting MVC and its overhead. MVC, however, is a model superior to a properly-done code-behind for its inherent support for test-driven development.

While MVC is definitely a key part of the framework, we wouldn't consider it is the most compelling part. REST is a possible alternative to the postback model, whereas MVC is an alternative to code-behind.

Explaining the MVC Framework to ASP. Net Developers

We wonder what's the quickest and most effective way to explain the MVC Framework to seasoned ASP.NET developers. It's like having a central HTTP handler that captures all requests to resources identified with a new extension. This HTTP handler analyzes the syntax of the URL and maps it to a special server component known as the controller. The controller supports a number of predefined actions. The requested action is somehow codified in the URL according to an application-specific syntax. The central HTTP handler invokes the action on the controller and the controller will process the request up to generating the response in whatever response format you need. The response is generated through a view component.

What here we called the "central HTTP handler" plays the same role that was of the System.Web.UI.Page class in classic ASP.NET. The Page is the handler responsible for any .aspx request
and generates the markup using the code-behind class and serves it back using postbacks. In the MVC Framework, this pattern - hard-coded in the ASP.NET runtime and not subject to change until the whole ASP.NET platform is rewritten - is simply implemented using an alternative HTTP handler and an alternative model based on REST and MVC.

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: Performing Validation in ASP.NET MVC Application

clock April 25, 2010 14:47 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site.

Abstract:

Validation is one of the most important aspects of an application. ASP.NET MVC framework provides multiple ways to validate the user input. In this article we are going to demonstrate how to perform validation in an ASP.NET application using Controller action, IDataErrorInfo and DataAnnotations methods.

Simple Validation:

The most simple way to perform validation is to perform it inside the Controller. The controller will be responsible for checking for the validity of the data. Let's check out the code for the view.

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Simple Validation</h2>
        
   <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   
   LastName: <%= Html.TextBox("LastName")%>
    
    <input type="submit" value="Save" />
    
    <% } %>

</asp:Content>

As, you can see the view is very simple and consists of FirstName and LastName TextBoxes. The submit button will submit the form and invoke the "SimpleValidation" action of the controller.

The controller used in this case is the HomeController. The SimpleValidation action is responsible for performing the validation on the data. The implementation of the SimpleValidation action is shown below:

public ActionResult SimpleValidation(Customer customer)
        {
            if(String.IsNullOrEmpty(customer.FirstName))
                ModelState.AddModelError("FirstName","FirstName cannot be blank!");

            if(String.IsNullOrEmpty(customer.LastName))
                ModelState.AddModelError("LastName","LastName cannot be blank!");

            if (!ModelState.IsValid)
                return View("SimpleValidation");

            return View("Confirmation");
        }

The SimpleValidation action accepts the Customer object as an input parameter. This is performed by Model Binders feature in ASP.NET MVC framework.

Inside the SimpleValidation action the ModelState.AddModelError method is used to populate the error collection of the model. The ModelState.IsValid property represents if there are any errors in the model. If the model is invalid then we simply return the current view which in this case is "SimpleValidation". If the model is valid then we return the "Confirmation" view.

Finally, make the adjustments in the view to display the errors. This is performed by the HTML helpers ValidationMessage as shown below:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Simple Validation</h2>
        
   <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
        
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   <%= Html.ValidationMessage("FirstName","*") %>
   
   LastName: <%= Html.TextBox("LastName")%>
    <%= Html.ValidationMessage("LastName","*") %>
    
    <input type="submit" value="Save" />
    
    <% } %>

</asp:Content>

Now, run the above page and click on the "submit" page without inputting the values for the FirstName and LastName. You will realize that the page was not submitted successfully since it was invalid. You can even make the errors more visible by using the ValidationSummary HTML helper as shown below:

 <% using (var form = Html.BeginForm(new { Action = "SimpleValidation" }))
      { %>     
        
        
    <%= Html.ValidationSummary("Errors") %>     
        
   FirstName:  <%= Html.TextBox("FirstName")%>
   <%= Html.ValidationMessage("FirstName","*") %>
   
   LastName: <%= Html.TextBox("LastName")%>
    <%= Html.ValidationMessage("LastName","*") %>
    
    <input type="submit" value="Save" />
    
    <% } %>

Validation Using IDataErrorInfo:

T
he second method of performing validation in an ASP.NET MVC application is by using the IDataErrorInfo class. This method involves the model class to inherit from the IDataErrorInfo interface. The implementation is shown below:

 public class Customer  : IDataErrorInfo
    {
        private string _firstName;
        private string _lastName;
        private Dictionary<String,String> _errors = new Dictionary<string, string>();

        
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                if(String.IsNullOrEmpty(value))
                    _errors.Add("FirstName","FirstName cannot be blank!");

                _firstName = value;
            }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                if(String.IsNullOrEmpty(value))        
                    _errors.Add("LastName","LastName cannot be blank!");

                _lastName = value;
            }
        }
        
        public string this[string columnName]
        {
            get
            {
                if (_errors.ContainsKey(columnName))
                    return _errors[columnName];

                return String.Empty;
            }
        }

        public string Error
        {
            get { return String.Empty;  }
        }
    }

Using this method the controller action is simplified as the validation is now moved into the model itself. The implementation is shown below:

public ActionResult ValidationUsingIDataErrorInfo(Customer customer)
        {
            if (!ModelState.IsValid)
                return View("ValidationUsingIDataErrorInfo");

            return View("Confirmation");
        }

Using DataAnnotations
:

The DataAnnotations provides the most easiest way to perform validation in an ASP.NET MVC application. It uses attributes to perform validation.

You need to download "Data Annotations Model Binder Sample". Once, it is downloaded you need to build the solution in Visual Studio which will create the "Microsoft.Web.Mvc.DataAnnotations" and System.ComponentModel.DataAnnotations" assemblies. The final step is to set the DataAnnotations default binder to the Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();  in the Global.asax file as shown below:

protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();

        }

Now, in order to use the validation you will simply use the attributes on the model properties as shown below:

public class Customer
    {
        [Required(ErrorMessage = "FirstName cannot be blank")]
        public string FirstName { get; set; }

        [Required(ErrorMessage ="LastName cannot be blank!")]  
        public string LastName { get; set; }
    }

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: ASP.NET MVC Sample Application

clock April 22, 2010 22:08 by author Richard

This topic contains a brief description about ASP.NET MVC. If you are looking for ASP.NET MVC Hosting, you can always consider ASPHostCentral.com and you can start from our lowest Standard Plan @$4.99/month to host your .NET MVC site. We promise we’ll not disappoint you and we will give the best service for you. For us, the most important thing is you.

The application is intentionally simple. The goal was to provide members of the ASP.NET community with an application that they could use to quickly learn how to build new applications with ASP.NET MVC.

The Contact Manager application is an address book application. The application enables you to list, create, edit, and delete contacts.

We built the application over multiple iterations. With each iteration, we gradually improved the application. The goal of this multiple iteration approach was to enable you to understand the reason for each change.

Literation 1:
Create the application. In the first iteration, we create the Contact Manager in the simplest way possible. We add support for basic database operations: Create, Read, Update, and Delete (CRUD).

Literation 2:
Make the application look nice. In this iteration, we improve the appearance of the application by modifying the default ASP.NET MVC view master page and cascading style sheet.

Literation 3:
Add form validation. In the third iteration, we add basic form validation. We prevent people from submitting a form without completing required form fields. We also validate email addresses and phone numbers.

Literation 4:
Make the application loosely coupled. In this third iteration, we take advantage of several software design patterns to make it easier to maintain and modify the Contact Manager application. For example, we refactor our application to use the Repository pattern and the Dependency Injection pattern.

Literation 5:
Create unit tests. In the fifth iteration, we make our application easier to maintain and modify by adding unit tests. We mock our data model classes and build unit tests for our controllers and validation logic.

Literation 6:
Use test-driven development. In this sixth iteration, we add new functionality to our application by writing unit tests first and writing code against the unit tests. In this iteration, we add contact groups.

Literation 7:
Add Ajax functionality. In the seventh iteration, we improve the responsiveness and performance of our application by adding support for Ajax.

Each literation has an associated tutorial.

Top Reasons to trust your ASP.NET MVC website to ASPHostCentral.com

What we think makes ASPHostCentral.com so compelling is how deeply integrated all the pieces are. We integrate and centralize everything--from the systems to the control panel software to the process of buying a domain name. For us, that means we can innovate literally everywhere. We've put the guys who develop the software and the admins who watch over the server right next to the 24-hour Fanatical Support team, so we all learn from each other:

- 24/7-based Support - We never fall asleep and we run a service that is operating 24/7 a year. Even everyone is on holiday during Easter or Christmas/New Year, we are always behind our desk serving our customers
- Excellent Uptime Rate - Our key strength in delivering the service to you is to maintain our server uptime rate. We never ever happy to see your site goes down and we truly understand that it will hurt your onlines business. If your service is down, it will certainly become our pain and we will certainly look for the right pill to kill the pain ASAP
- High Performance and Reliable Server - We never ever overload our server with tons of clients. We always load balance our server to make sure we can deliver an excellent service, coupling with the high performance and reliable server
- Experts in ASP.NET MVC Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostCentral
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control Panel in 1 minute!

Happy hosting!

Currently rated 1.0 by 1 people

  • Currently 1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: ASP.NET MVC Sample Applications, Open-Source Examples and Tutorials

clock February 10, 2010 16:22 by author Administrator

ASP.NET MVC is a free, fully supported, Microsoft product that enables developers to easily build great web applications. It provides total control over your HTML and URLs, enables rich AJAX integration, and facilitates test driven development.


Here is a list of various ASP.NET MVC Sample Applications demonstrating the new ASP.NET MVC Framework from Microsoft. If you like to have any of these applications hosted on a server, you can consider ASPHostCentral.com as your ASP.NET MVC hosting provider. With a package starting from only $4.99/month, you can have the latest ASP.NET MVC 2 RC framework running on our server.


CarTrackr

CarTrackr is a sample application for the ASP.NET MVC framework using the repository pattern and dependency injection using the Unity application block. It was written for various demos in presentations done by Maarten Balliauw. CarTrackr is an online software application designed to help you understand and track your fuel usage and kilometers driven. You will have a record on when you filled up on fuel, how many kilometers you got in a given tank, how much you spent and how much liters of fuel you are using per 100 kilometer. CarTrackr will enable you to improve your fuel economy and save money as well as conserve fuel. Fuel economy and conservation is becoming an important way to control your finances with the current high price


http://cartrackr.codeplex.com/


Codecampserver

This is the source code repository for CodeCampServer, a free, open source Code Camp management web application.

http://code.google.com/p/codecampserver/


Contact Manager

In this series of tutorials, Stephen Walther demonstartes how to use the ASP.NET MVC framework to build an entire Contact Manager application using unit tests, test-driven development, Ajax, and software design principles and patterns


http://www.asp.net/mvc/


FlickrXplorer

The project is an open source initiative to present users a fast photo explorer and search tool to browse millions of photos in flickr. The app is made with a bit of jQuery blend using Asp.net MVC and custom LINQ. The project also embodies a cloud computing scenario where the actual datastore lies millions of miles away invoked though simple API. The Application gives a nice starting point for Asp.net MVC, it also shows a strong integration of jQuery with Asp.net MVC as a client framework. It uses Athena (http://www.codeplex.com/LinqFlickr) LINQ to flickr API for fetching in and out data which is made on a custom LINQ provider toolkit made best for creating LINQ to Cloud APIs (http://www.codeplex.com/LinqExtender).

http://flickrxplorer.codeplex.com/


Kigg

KiGG is a Web 2.0 style social news web application developed in Microsoft supported technologies. The project uses ASP.NET MVC, Linq To SQL, MS Patterns & Practices Enterprise Library and Unity, jQuery, xUnit.net, Moq, HtmlAgilityPack, DotNetOpenId, and other 3rd party libraries


http://www.codeplex.com/Kigg


MVC StoreFront

I'm creating an ongoing series of webcasts and blog posts, documenting the building of an eCommerce storefront using ASP.NET MVC

http://blog.wekeroad.com/mvc-storefront/


Nerddinner

NerdDinner.com is an event management site so computer folks can meet and talk technology over a meal. It uses ASP.NET MVC along with jQuery, ASP.NET Ajax, Virtual Earth Javascript controls, and LINQ to SQL. It’s also a real site running at NerdDinner.com that you can use to schedule geek meet ups and nerd dinners in your neighborhood!

http://nerddinner.codeplex.com/


Oxite

Oxite is an open source, web standards compliant, blog engine built on ASP.NET MVC and LINQ To SQL. Oxite supports all the features we consider essential to a blog engine, including the MetaWebLog API (to allow you to use LiveWriter or similar tools to add/edit your posts), trackbacks, pingbacks, Sitemaps (for search engines), RSS and ATOM feeds (at the site, blog, tag and post level ... plus feeds of all new comments... great for the site owner), tags, integrated search, web based admin features (including editing posts, your site settings, etc.), email subscriptions for new comments, basic support to publish 'pages' (non-blog content) and more.

http://www.codeplex.com/oxite

Currently rated 2.3 by 4 people

  • Currently 2.25/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting :: Specifications and Functions

clock July 24, 2009 13:00 by author Administrator
The ASP.NET MVC Framework couples the models, views and controllers using interface-based contracts, thereby allowing each component to be easily tested independently. By default, the view engine in the MVC framework uses regular .aspx pages to design the layout of the user interface pages onto which the data is composed.

However, different View Engines can be used (for example, you can create a View Engine based on XSLT files. Additionally, rather than the default ASP.NET post back model, any interactions are routed to the controllers using the ASP.NET 3.5 SP1 Routing mechanism.
The ASP.NET MVC Framework is a Model-view-controller framework which Microsoft is adding to ASP.NET. It allows software developers to build a Web application as a composition of three roles: Model, View and Controller. A Model represents the state of a particular aspect of the application. Frequently, a model maps to a database table with the entries in the table representing the state of the table. A Controller handles interactions and updates the model to reflect a change in state of the application. A View extracts necessary information from a model and renders a user interface to display it.

More information on Model View Controller (MVC) Framework or
ASP.NET MVC hosting plans, log on to http://www.asphostcentral.com/ASP-NET-MVC-Hosting.aspx or contact ASPHostCentral.com at http://www.asphostcentral.com


 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC Hosting

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!


Sign in