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

WCF Hosting :: Guidelines to WCF Versioning

clock January 9, 2011 16:01 by author Administrator

Overview

Services exist in order to serve external clients. They do so by exposing a wide range of external interfaces which are later used by the clients to interact with the service.

After initial deployment, and potentially several times during their lifetime, services may need to be changed for a variety of reasons, such as changing business needs, re-factorization of code, or to address other issues.

Each change introduces a new version of the service. Each new service version potentially introduces changes to the external interfaces exposed by the service.

Our goal, as developers, is to be able to freely change our service internals (and sometimes, when needed, external interfaces), and on the same time, allow existing and new clients to keep using the service.

In order to do so, we need to form a set of versioning guidelines.

This article will cover basic concepts related to versioning issues and will provide a set of guidelines which aim to provide a simple solution for the versioning problem domain.

All the information exists freely on the Internet. We didn’t invent anything new. We just gathered most of the information in one simple blog post, for your convenience.

A lot of the guidelines below were taken from an excellent set of MSDN articles:

http://msdn.microsoft.com/en-us/library/ms731060.aspx and http://msdn.microsoft.com/en-us/library/ms733832.aspx. These articles are very good reading material.  


Reduce the Problem Domain

Services interact with external services in many different ways. They can use WCF to send and receive information. They can connect to external databases directly (by using ADO.NET, for example) and many more.

Instead of forming a set of guidelines for each protocol, the simplest way is to reduce the problem domain to one protocol and use only one set of guidelines for this protocol.

For example, instead of connecting to a database directly, it is possible to create an abstraction layer on top of the database, which will expose WCF interface to the clients. This layer will be upgraded together with the database, creating a coupling between this layer and the database. The exposed WCF interface will follow the versioning guidelines that we will mention later, thus keeping all the clients compatible with the database service, even when it is being upgraded.

To sum it up, if you like the WCF versioning guidelines that we’ll mention later on, use WCF interfaces whenever possible to expose your service functionality.  


Versioning Terminology

Strict Versioning – In many scenarios when a change is required to an external interface, the service developer does not have control over the clients and therefore cannot make assumptions about how they would react to changes in the message XML or schema. The recommended approach in such scenarios is to treat existing data contracts as immutable and create new data contracts (with unique XML qualified names) instead.

Lax Versioning – In many other scenarios, the service developer can make the assumption that adding a new, optional member to the data contract will not break existing clients. This requires the service developer to investigate whether existing clients are not performing schema validation and that they ignore unknown data members. In these scenarios, it is possible to take advantage of data contract features for adding new members in a non-breaking way. WCF support Lax versioning: that is, they do not throw exceptions for new unknown data members in received data, unless requested otherwise.

When a connection is made between a client and a server of a different version, and a strict versioning is used, the client won’t be able to connect to a service of a different version. When lax versioning is used, the client will be able to connect and it is up to the developer to handle backward and forward compatibility.  


Client\Server Paradigm

In a client\server world, a client sends requests to a server, which, in turn, responds back to the client.

When versioning is introduced into the system, we may encounter the following scenarios:

Client and server use the same version.
Client is older than the server.
Client is newer than the server.

Each scenario should be handled separately, but there is one rule which applies to all: Newer element knows more than older element, therefore, newer elements should be the more proactive elements in the versioning game.

This means the following:

Client and server use the same version – No problem here. Communication will work as expected.

Client is older than the server – The server should support both older and current clients. When Lax Versioning is used, the server is allowed to add new data members and new operations (according to Lax guidelines which will be described later on). It must expose the same WCF service, on the same contract with the same name and namespace. When Strict Versioning is used, the server must expose (at least) two WCF services (and WCF contracts). The first is the new WCF service, on the new contract with a new namespace and name, and the rest are all the supported old WCF services with their original contacts, namespaces and names.

Client is newer than the server – The client must avoid using unsupported operations on an older server. When Lax versioning is used, the client is not allowed to call new operations (which don’t exist on the server side). When Strict versioning is used, the client must use a WCF endpoint which exposes a contract matching the one used by the server. In both approaches, the client must know the version of the server. This is performed by some kind a version discovery mechanism (more on this below).  

Note – If an element acts both as a client and as a server, it is very reasonable that it would suffer from both issues above, during the upgrade period. This means that it will probably have a local client newer than a remote server and a local server newer than a remote client. In these situations, each direction should be handled separately.    


Version Discovery Basics

When a client is newer than the server, as we already know, it must protect itself when communicating with an older server.

For example, if Lax versioning is used, the client should be responsible not to call new operations which are not supported by the server.

When Strict versioning is used, it should find a matching contract, support by the server, to communicate on.

In order to do that, the client must discover the server’s version. This is called Version Discovery.

There are several ways to discover the server’s version:

Get Version API – The server should expose its version somehow. The client should use this API to discover the server’s version before attempting to communicate with the server.

Fallback – The client tries to communicate with the server with the newest contract version known to the client, and falls back to older versions when the communication fails until it finds a contract version match (of course, this can only work with Strict versioning).

Configuration – The server version is stored somewhere in local configuration and the client can read it before attempting to connect to the server.   


Versioning Guidelines

So far we had a long introduction to the versioning world. It’s time to actually discuss some actual versioning guidelines.

First we will try to understand when to use Lax versioning and when to use Strict versioning. Later on, we will provide a set of guidelines for each versioning schema.

When building a complex system, involving multiple machines working together to expose one big external service, we can distinguish between two types of communication flows, inner communication an external communication.

Inner Communication – This covers all communication flows between the system’s machines. In such systems, usually, the developers have control on all components involved in the communication flows. Therefore, the natural versioning schema should be Lax versioning. As a reminder, Lax versioning can be used when we know something about the involved components and can enforce several assumptions on them. Of course, if we can’t make these assumptions, or if we require huge contract changes which can’t be covered by the Lax versioning guidelines (which will be covered later on), we can always fallback to Strict versioning.

External Communication – This covers all communication between internal endpoints (controlled by the system developers) to external endpoints (not controlled by the system developers, naturally). Since we don’t control one side of the conversation, Strict versioning is the only way to go. This means that whenever a new version is available, we create a new contract to represent it, while keeping the old contract intact. We must publish both the new contract and the old contract (or contracts, if we want to support several versions back) simultaneously. We might also consider providing some assistance in terms of providing some version discovery mechanisms. If clients are newer than the server, they will have to use one of the version discovery mechanisms to survive.   


Lax Versioning Guidelines

The guidelines are divided to service contract guidelines and data contract guidelines.

Lax Service Contract:

Namespace and Name – DO NOT change namespace or name between versions. Do not add namespace or name, if the contract didn’t have namespace or name in the previous version (unless you want to add the default namespace and name)

Operations Addition – Adding service operations exposed by the service can be considered as a non-breaking change because existing (older) clients need not be concerned about those new operations. Newer clients must use version discovery methods before contacting an older server and avoid calling new operations. If version discovery is impossible, adding operations is considered as a breaking change (strict).

Operations Removal – Removing operations is considered to be a breaking change and therefore, NOT ALLOWED. To make such a change, strict versioning should be used (define a new service contract and expose it on a new endpoint). It is still possible to remove operations, but this can be performed only after the versioning difference between a client and a server exceeds the maximum allowed by the system (for example, we support only one version back and we now upgrade to version N+2).

Operation Parameters Types – Changing parameter types or return types generally is considered to be a breaking change unless the new type implements the same data contract implemented by the old type. Other type changes are NOT ALLOWED. To make such changes, add a new operation to the service contract or use strict versioning.

Operation Parameters Addition/Removal – Adding or removing an operation parameter is a breaking change, therefore, it is NOT ALLOWED. To make such a change, add a new operation to the service contract or use strict versioning.

Operation Parameters Aggregation – It is recommended to use one aggregated data contract as an operation parameter, rather than separate multiple parameters. By using a data contract as aggregated parameter, while keeping the Lax guidelines for data contracts (see below), it is easier to keep an operation backward compatible. It is possible to change internal parameters without being limited to the above restrictions.

Fault Contracts – The list of faults described in a service’s contract is not considered exhaustive. At any time, an operation may return faults that are not described in its contract. Therefore changing the set of faults described in the contract is not considered a breaking change. For example, adding a new fault to the contract using the FaultContractAttribute or removing an existing fault from the contract is allowed.

Lax Data Contract:

Namespace and Name – DO NOT change namespace or name between versions. Do not add namespace or name, if the contract didn’t have namespace or name in the previous version (unless you want to add the default namespace and name)

Data Contract Names - In later versions, DO NOT change the data contract name or namespace. If changing the name or namespace of the type underlying the data contract, be sure to preserve the data contract name and namespace by using the appropriate mechanisms, such as the Name property of the DataContractAttribute.

Data Members Names – In later versions, DO NOT change the names of any data members. If changing the name of the field, property, or event underlying the data member, use the Name property of the DataMemberAttribute to preserve the existing data member name.

Data Members Types – In later versions, DO NOT change the type of any field, property, or event underlying a data member such that the resulting data contract for that data member changes. Keep in mind that interface types are equivalent to Object for the purposes of determining the expected data contract.

Data Members Addition – In later versions, new data members can be added. They should always follow these rules:

a. The IsRequired property should always be left at its default value of false.
b. If a default value of null or zero for the member is unacceptable, a callback method should be provided using the OnDeserializingAttribute to provide a reasonable default in case the member is not present in the incoming stream.
c. The Order property on the DataMemberAttribute should be used to make sure that all of the newly added data members appear after the existing data members. The recommended way of doing this is as follows: None of the data members in the first version of the data contract should have their Order property set. All of the data members added in version 2 of the data contract should have their Order property set to 2. All of the data members added in version 3 of the data contract should have their Order set to 3, and so on. It is permissible to have more than one data member set to the same Order number.

Data Members Order – In later versions, DO NOT change the order of the existing data members by adjusting the Order property of the DataMemberAttribute attribute.

Data Members Removal – DO NOT remove data members in later versions, even if the IsRequired property was left at its default property of false in prior versions.

Data Members IsRequired –
a. DO NOT change the IsRequired property on any existing data members from version to version.
b. For required data members (where IsRequired is true), DO NOT change the EmitDefaultValue property from version to version.

Branching – DO NOT attempt to create branched versioning hierarchies. That is, there should always be a path in at least one direction from any version to any other version using only the changes permitted by these guidelines. For example, if version 1 of a Person data contract contains only the Name data member, you should not create version 2a of the contract adding only the Age member and version 2b adding only the Address member. Going from 2a to 2b would involve removing Age and adding Address; Going in the other direction would entail removing Address and adding Age. Removing members is not permitted by these guidelines.

Known Types – You should generally not create new subtypes of existing data contract types in a new version of your application. Likewise, you should not create new data contracts that are used in place of data members declared as Object or as interface types. For example, in version 1 of your application, you may have the LibraryItem data contract type with the Book and Newspaper data contract subtypes. LibraryItem would then have a known types list that contains Book and Newspaper. Suppose you now add a Magazine type in version 2 which is a subtype of LibraryItem. If you send a Magazine instance from version 2 to version 1, the Magazine data contract is not found in the list of known types and an exception is thrown. Creating these new classes is allowed only when you know that you can add the new types to the known types list of all instances of your old application or if newer instances use version discovery and will not send new types to an old server.

Enumerations – DO NOT add or remove enumeration members between versions. You should also not rename enumeration members; unless you use the Name property on the EnumMemberAttribute attribute to keep their names in the data contract model the same.

Inheritance –

DO NOT attempt to version data contracts by type inheritance. To create later versions, either change the data contract on an existing type (Lax) or create a new unrelated type (Strict).

The use of inheritance together with data contracts is allowed, provided that inheritance is not used as a versioning mechanism and that certain rules are followed. If a type derives from a certain base type, do not make it derive from a different base type in a future version (unless it has the same data contract). There is one exception to this: you can insert a type into the hierarchy between a data contract type and its base type, but only if it does not contain data members with the same names as other members in any possible versions of the other types in the hierarchy. In general, using data members with the same names at different levels of the same inheritance hierarchy can lead to serious versioning problems and therefore, it is prohibited.

Collections – Collections are interchangeable in the data contract model. This allows for a great degree of flexibility. However, make sure that you do not inadvertently change a collection type in a non-interchangeable way from version to version. For example, do not change from a non-customized collection (that is, without the CollectionDataContractAttribute attribute) to a customized one or a customized collection to a non-customized one. Also, do not change the properties on the CollectionDataContractAttribute from version to version. The only allowed change is adding a Name or Namespace property if the underlying collection type’s name or namespace has changed and you need to make its data contract name and namespace the same as in a previous version.

Round Tripping – In some scenarios, there is a need to “round-trip” unknown data that comes from members added in a new version. For example, a “versionNew” service sends data with some newly added members to a “versionOld” client. The client ignores the newly added members when processing the message, but it resends that same data, including the newly added members, back to the versionNew service. The typical scenario for this is data updates where data is retrieved from the service, changed, and returned. If the data contract is expected to be used in a round tripping scenario, then starting with the first version of a data contract, always implement IExtensibleDataObject to enable round-tripping. If you have released one or more versions of a type without implementing this interface, it is usually recommended to implement it in the next version of the type.  


Strict Versioning Guidelines

Strict versioning guidelines are also divided into service contract and data contract guidelines, although they are very similar.

Strict Service Contract:

Namespace and Name – At least one of the namespace or name MUST be changed in later version, in order to break the contract compatibility. If the contract didn’t have namespace or name in previous version, namespace and name must be added to the contract (and must have different values than the default values)

Cascading Break – If a service contract exposes a data contract directly or via operations parameters or return value, and this data contract compatibility is broken (namespace or name replaced), then the service is also broken and MUST be treated as such, thus, a new contract should be created.

Immutability – When breaking a service contract, a new service contract MUST be created with a unique Namespace and Name, while the old contract MUST be kept intact and treated as immutable.

Strict Data Contract:

Namespace and Name – At least one of the namespace or name MUST be changed in later version, in order to break the contract compatibility. If the contract didn’t have namespace or name in previous version, namespace and name MUST be added to the contract (and must have different values than the default values)

Immutability – When breaking a data contract, a new data contract MUST be created with a unique Namespace and Name, while the old contract MUST be kept intact and treated as immutable.

Cascading Break – If a data contract is contained in a different data contract or exposed by a service contract directly or indirectly, and this data contract compatibility is broken (namespace or name replaced), then all contracts containing or exposing this data contract MUST be broken as well

Currently rated 1.5 by 6 people

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


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 2.0 by 26 people

  • Currently 2/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 2.1 by 9 people

  • Currently 2.111111/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.

Currently rated 2.3 by 8 people

  • Currently 2.25/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 2.3 by 9 people

  • Currently 2.333333/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.9 by 34 people

  • Currently 1.882353/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!

Currently rated 2.3 by 8 people

  • Currently 2.25/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!

Currently rated 2.3 by 8 people

  • Currently 2.25/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 2.7 by 6 people

  • Currently 2.666667/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

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