ASP.NET MVC V2 Preview 1 Released
The ASP.NET team just released the first public preview of ASP.NET MVC Version 2.
Today’s preview works with .NET 3.5 SP1 and VS 2008, and can be installed side-by-side on the same machine as ASP.NET MVC 1.0 (meaning they don’t conflict and your existing ASP.NET MVC 1.0 projects will not be impacted if you install it). If you have both ASP.NET MVC 1.0 and ASP.NET MVC 2.0 installed you’ll see two ASP.NET MVC project templates within Visual Studio 2008’s “New Project” dialog:
The release notes that come with the ASP.NET MVC 2 Preview release detail how to upgrade existing ASP.NET MVC 1.0 projects to use V2 if you’d like to migrate them forward to take advantage of the new features.
New Features
ASP.NET MVC V2 will include a bunch of new capabilities and features (some of these have already been called out on the ASP.NET MVC roadmap page). Today’s “Preview 1” release contains a first look at some of the new features. Many more features will show up in future preview builds. The Preview 1 bits are still relatively early - the team is releasing today’s build to start receiving and incorporating feedback.
Below are some quick details about some of the new Preview 1 capabilities:
Areas Support
ASP.NET MVC 2 includes support for a new feature called “areas” that allow you to more easily partition and group functionality across an MVC application.
Areas provide a means of grouping controllers and views to allow building subsections of a large application in relative isolation to other sections. Each area can be implemented as a separate ASP.NET MVC project which can then be referenced by the main application. This helps manage the complexity when building a large application and facilitates multiple teams working together on a single application together.
Below is a screen-shot that shows a single solution that has three projects. One of the projects is named “CompanySite” and includes the core site content, layout and controllers and views. There are then two separate “Area” projects - “Blogs” and “Forums”. These projects implement the functionality that exists under the /Blogs and /Forums URL sections of the site – and encapsulate all of the routing rules, controllers and views implementing these sections:
The Preview 1 release includes the first part of the areas feature implementation. It doesn’t include any tool support yet (right now you need to manually add a build task to create an area project and set it up). Future preview releases will include tooling support, and expand and refine the feature-set further.
DataAnnotation Validation Support
ASP.NET MVC 2 now includes built-in support for the DataAnnotation validation support that first shipped with .NET 3.5 SP1 – and which is used with ASP.NET Dynamic Data and .NET RIA Services. DataAnnotations provides an easy way to declaratively add validation rules to Model and ViewModel classes within an application, and have automatic binding and UI helper validation support within ASP.NET MVC.
To see this feature in action, we can create a new “Customer” ViewModel class like below that has five properties on it (implemented using the C# automatic property feature).
We can then decorate the properties with appropriate validation rules using the DataAnnotation attributes implemented within the System.ComponentModel.DataAnnotations namespace. The code below uses 4 different built-in validation rules – [Required], [StringLength], [Range], and [RegularExpression]. The namespace also includes a base class (ValidationAttribute) that you can subclass to create your own custom validation attributes.
We can then create a CustomersController class that has two Create action methods on it. The first Create action method handles HTTP GET requests to the “/Customers/Create” URL, and renders a view template based on an empty Customer object. The second Create action method handles HTTP POST requests to the same URL (and takes a Customer object as a method parameter). It checks if there are any model binding errors to the input submitted, and if there are errors it redisplays the view template using the already entered data. If there are no errors it displays a success view to the user:
Finally, we can right-click within either of the Create action methods above, choose the “Add View” context menu command, and automatically “scaffold” a “create” view template that is based on the Customer object. When we do this the generated scaffolded view template will contain the below HTML <form> for our Customer:
And now when we request the “/Customers/Create” URL in our browser we’ll get an initial empty form like below:
If we enter invalid input and perform a post to the server, the ASP.NET MVC 2 model binder will detect that there are DataAnnotations attributes on our Customer class, and automatically validate the posted form input using them. If there are errors our controller action method redisplays the form – which will cause the appropriate validation error messages to be rendered to the user like below. Note how the validation property error message strings we specified using the DataAnnotation attributes are displayed to the user by the Html.Validation helper methods. No extra code is required to enable this.

The above form will redisplay with error messages each time the user enters invalid input and attempts to perform a form post.
In a future ASP.NET MVC 2 preview we are planning to ship the jQuery Validation plugin as part of the default project template, and add support for the automatic client-side JavaScript enforcement of DataAnnotation validation rules as well. This will enable developers to easily add validation rules in one place on either a Model or ViewModel object, and have them be enforced both client and server-side everywhere it is used within the application.
If you do not wish to annotate your model or viewmodel classes directly, you can alternatively create a “buddy class” that accompanies your model class and encapsulates the DataAnnotaton rules separately. This capability is also useful for scenarios where VS is code-generating/updating the properties on a class directly and you cannot easily add attributes to the generated code (for example: classes generated by the LINQ to SQL or LINQ to Entities designers).
In addition to providing built-in support for DataAnnotations, the DefaultModelBinder class in ASP.NET MVC V2 now has new virtual methods that can be overridden to easily integrate other validation frameworks as well (for example: Castle Validator, EntLib Validation, etc). The validation UI helper methods in ASP.NET MVC are designed to support any type of validation framework (they have no direct knowledge of DataAnnotations).
Strongly Typed UI Helpers
ASP.NET MVC V2 includes new HTML UI helpers that enable you to use strong-typed lambda expressions when referencing the view template’s model object. This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code intellisense support within view templates.
You can see an example of the better intellisense in action below – notice how I am getting a full listing of the customer model object’s properties when using the new Html.EditorFor() helper method:
Preview 1 has built-in support for new Html.EditorFor(), Html.LabelFor(), and Html.DisplayFor() helpers. An updated MVC futures assembly that we are shipping this week adds additional Html.TextBoxFor(), Html.TextAreaFor(), Html.DropDownListFor(), Html.HiddenFor(), and Html.ValidationMessageFor() helper methods as well (overtime these will move into the core ASP.NET MVC 2 assembly too).
Below you can see an updated version of the “create” view template for our customer creation scenario. Notice how instead of using string expressions to reference the customer object we are instead using strongly-typed lambda expressions with the UI helpers. We can get full intellisense and compile-time checking with all of them:
The Html.LabelFor() helper method above generates <label for="Name">Name:</label> HTML markup.
The Html.EditorFor() helper method can be used for any datatype value. By default it is smart and will output an appropriate HTML <input/> element based on the type to be edited. For example, it will generate <input type=”text”/> elements for the first four properties above (which are strings and integers). It will generate a <input type=”checkbox”/> element for the final “IsActive” property – which is of type boolean.
In addition to supporting simple data-types, the Html.EditorFor() helper method also allows you to pass more complex objects with multiple properties to it. By default it will loop over the public properties of the object and generate a <label>, <input/> element, and any appropriate validation message for each property it finds. For example, we could re-write the above view to have just a single Html.EditorFor() call for the Customer object to conceptually output the same markup as above:
The strongly typed helpers allow you to optionally decorate the properties of the Customer ViewModel class with [DisplayName] attributes to control the label string that is output for each property used (for example: instead of having a label text of “IsActive” we could apply a [DisplayName(“Is Active Customer:”)] attribute).
You can also add [ScaffoldColumn(false)] attributes to indicate that a particular property shouldn’t be rendered at all in scenarios like above where complex objects are passed to Html.EditorFor().
UI Helper Templating Support
The Html.EditorFor() and Html.DisplayFor() helper methods have built-in support for rendering both standard data-types as well as complex objects with multiple properties. As noted above, they also support basic customization of rendering by applying attributes like [DisplayName] and [ScaffoldColumn] to the ViewModel.
Often developers want to be able to customize the output from UI helpers even further, though, and have total control over what is generated. The Html.EditorFor() and Html.DisplayFor() helper methods support this via a templating mechanism that allows you to define external templates that can override and completely control the output rendered. Better yet, you can customize the content rendered on a per-datatype/class basis.
With Preview 1 you can now optionally add an “EditorTemplates” and/or “DisplayTemplates” folder underneath either a \Views\[controllername] directory (if you want to customize the rendering for views used by a specific controller) or underneath the \Views\Shared folder (if you want to customize the rendering for all views and controllers in an application).
You can then add partial template files to these folders to customize the output rendering performed on an individual datatype and/or class basis. For example, below I have added an EditorTemplates folder underneath the \Views\Shared folder – and added three custom template files to it:
The “Customer.ascx” template above indicates that I want to customize the output anytime Html.EditorFor() is passed a Customer object (for example: I could customize the exact ordering/layout of the Customer properties). The “DateTime.ascx” template above indicates that I want to customize the output anytime Html.EditorFor() is passed a DateTime property (for example: I might want to use a JavaScript datepicker instead of a plain textbox). I could optionally add an “Object.ascx” template to the folder if I wanted to override the default rendering of all objects.
In addition to customizing rendering on a per-type basis, you can also add “named templates” to the folder. A common scenario might be a “CountryDropDown” template that handles a string datatype – but instead of providing a standard textbox instead renders a <select> dropdownlist of country values that a user can pick from. Below is what this editor template might look like:
We can explicitly indicate that we want to use the above template by passing its name as an argument when we invoke the Html.EditorFor() helper method. For example, below in addition to specifying a lambda expression for our Country property, we are also specifying the name of the editor template to use when rendering it:
Alternatively, you can specify “UIHint” attributes on your ViewModel properties and types. This allows you to indicate the default editor or display template to use in a single place, and have it be used in all views across your application (without having to explicitly pass it as an argument to Html.EditorFor).
Below is an example of how to indicate using a UIHint attribute that the Customer.Country property (which is of type string) should by default use the CountryDropDown template when being rendered:
Once we set the above attribute on our ViewModel we no longer need to specify a template name explicitly when we use that property with Html.EditorFor(). And now when we hit refresh on our /Customers/Create URL our Country property will be rendered as a dropdown instead of a standard textbox:
Other Cool Features
ASP.NET MVC 2 Preview 1 includes a number of other small, but really nice, feature additions. A few of my favorites include:
New [HttpPost] Attribute
It is pretty common with ASP.NET MVC to split up the handling of a URL across two action methods – one that handles GET requests and one that handles POST requests.
With ASP.NET MVC 1 you used an [AcceptVerbs(HttpVerbs.Post)] attribute to indicate the “Post” version of an action method:
This still works with ASP.NET MVC 2. Alternatively, though, you can also now take advantage of a terser [HttpPost] attribute that does the same thing:
Default Parameter Values
Handling optional parameters is a pretty common web scenario. With ASP.NET MVC 1 you could handle optional parameters either by registering a custom routing rule and specifying a default value with it, or by marking an action method parameter as nullable and then adding code within your action method to handle whether it was null (and if so provide a default value).
ASP.NET MVC 2 Preview 1 now supports decorating action method parameters with the DefaultValueAttribute from the System.ComponentModel namespace. This allows you to specify a parameter value that ASP.NET MVC should pass in if it is not present as part of the request. For example, below is an example of how we could handle both the /Products/Browse/Beverages and /Products/Browse/Beverages?page=2 URLs – and have the “page” parameter value be “1” if it isn’t provided as part of the querystring:
VB today allows you to specify default parameter values directly within the VB language (avoiding the need to explicitly specify the DefaultValue attribute like above). C# in VS2010 will also support default values with optional parameters – which will enable you to rewrite the above code simply as:
This should make handling default/optional scenarios really easy and clean.
Binding Binary Data
ASP.NET MVC Preview 1 adds support for binding base64-encoded string values to properties of type byte[] and System.Data.Linq.Binary. There are now two overloaded versions of Html.Hidden() that can take these data-types. These can be useful for scenarios where you want to enable concurrency control within your application and want to roundtrip timestamp values of database rows within your forms.
Posted in: asp.net | Tags: asp.net asp.net mvc mvc mvc 2.0 v2 vs 2008 new project web application mvc web applicationReading Routing Information in a Web Forms Page
In the code of the Web Forms physical page, you can access the information that routing has extracted from the URL (or other information that another object has added to the RouteData object) by using two new properties: HttpRequest.RequestContext and Page.RouteData. (Page.RouteData wraps HttpRequest.RequestContext.RouteData.) The following example shows how to use Page.RouteData.
protected void Page_Load(object sender, EventArgs e)
{
string searchterm = Page.RouteData.Values["searchterm"] as string;
label1.Text = searchterm;
}
The code extracts the value that was passed for the searchterm parameter, as defined in the example route earlier. Consider the following request URL:
http://localhost/search/scott/
When this request is made, the word "scott" would be rendered in the search.aspx page.
Accessing Routing Information in Markup
The method described in the previous section shows how to get route data in code in a Web Forms page. You can also use expressions in markup that give you access to the same information. Expression builders have been described as a "hidden gem of ASP.NET" (see the entry Express Yourself With Custom Expression Builders on Phil Haack's blog). It is unfortunate that they are not better known, because expression builders are a powerful and elegant way to work with declarative code.
ASP.NET 4 includes two new expression builders for Web Forms routing. The following example shows how to use them.
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="<%$RouteUrl:SearchTerm=scott%>">Search for Scott</asp:HyperLink>
In the example, the RouteUrl expression is used to define a URL that is based on a route parameter. This saves you from having to hard-code the complete URL into the markup, and lets you change the URL structure later without requiring any change to this link.
Based on the route defined earlier, this markup generates the following URL:
http://localhost/search/scott
ASP.NET automatically works out the correct route (that is, it generates the correct URL) based on the input parameters. You can also include a route name in the expression, which lets you specify a route to use.
The following example shows how to use the RouteValue expression.
<asp:Label ID="Label1" runat="server" Text="<%$RouteValue:SearchTerm%>" />
When the page that contains this control runs, the value "scott" is displayed in the label.
The RouteValue expression makes it very simple to use route data in markup, and it avoids having to work with the more complex Page.RouteData["x"] syntax in markup.
Posted in: asp.net | Tags: asp.net asp.net 4.0 webform web application routing web formBest blog system – WordPress, using php and mysql
WordPress started in 2003 with a single bit of code to enhance the typography of everyday writing and with fewer users than you can count on your fingers and toes. Since then it has grown to be the largest self-hosted blogging tool in the world, used on millions of sites and seen by tens of millions of people every day.
Everything you see here, from the documentation to the code itself, was created by and for the community. WordPress is an Open Source project, which means there are hundreds of people all over the world working on it. (More than most commercial platforms.) It also means you are free to use it for anything from your cat’s home page to a Fortune 500 web site without paying anyone a license fee and a number of other important freedoms.
About WordPress.org
On this site you can download and install a software script called WordPress. To do this you need a web host who meets the minimum requirements and a little time. WordPress is completely customizable and can be used for almost anything. There is also a service called WordPress.com which lets you get started with a new and free WordPress-based blog in seconds, but varies in several ways and is less flexible than the WordPress you download and install yourself.
A Little History
WordPress was born out of a desire for an elegant, well-architectured personal publishing system built on PHP and MySQL and licensed under the GPL. It is the official successor of b2/cafelog. WordPress is fresh software, but its roots and development go back to 2001. It is a mature and stable product. We hope by focusing on user experience and web standards we can create a tool different from anything else out there.
2005 was a very exciting year for WordPress, as it saw the release of our 1.5 version (introduced themes) which was downloaded over 900,000 times, the start of hosted service WordPress.com to expand WP's reach, the founding of Automattic by several core members of the WP team, and finally the release of version 2.0.
After 1.5 we seemed to have something people really liked and we've experienced some fairly rapid growth. Here are some metrics for 2006 and 2007.
In 2006 we had 1,545,703 downloads, in 2007 we had 3,816,965!
As for plugins we had 191,567 downloads of 371 unique plugins in 2006. In 2007 there were 2,845,884 downloads (15x growth) of 1,384 plugins.
2006 saw the introduction of the first WordCamp in San Francisco.
In 2007 we adopted a regular release schedule, putting out major feature releases roughly every 3-4 months, or three times a year.
Because of the number of improvements in version 2.5 we took an extra 3 months on it, but 2008 looks on track to do three major releases again. It will be a very exciting year.
There are now dozens of WordCamps around the world, from Vancouver to Dallas to Milan, Italy.
To run WordPress your host just needs a couple of things:
* PHP version 4.3 or greater
* MySQL version 4.0 or greater
That's really it. We recommend Apache or Litespeed as the most robust and featureful server for running WordPress, but any server that supports PHP and MySQL will do. That said, we can’t test every possible environment and each of the hosts on our hosting page supports the above and more with no problems.
Key Features
* Full standards compliance — We have gone to great lengths to make sure every bit of WordPress generated code is in full compliance with the standards of the W3C. This is important not only for interoperability with today's browser but also for forward compatibility with the tools of the next generation. Your web site is a beautiful thing, and you should demand nothing less.
* No rebuilding — Changes you make to your templates or entries are reflected immediately on your site, with no need for regenerating static pages.
* WordPress Pages — Pages allow you to manage non-blog content easily, so for example you could have a static "About" page that you manage through WordPress. For an idea of how powerful this is, the entire WordPress.org site could be run off WordPress alone. (We don't for technical mirroring reasons.)
* WordPress Links -- Links allows you to create, maintain, and update any number of blogrolls through your administration interface. This is much faster than calling an external blogroll manager.
* WordPress Themes — WordPress comes with a full theme system which makes designing everything from the simplest blog to the most complicated webzine a piece of cake, and you can even have multiple themes with totally different looks that you switch with a single click. Have a new design every day.
* Cross-blog communication tools— WordPress fully supports both the Trackback and Pingback standards, and we are committed to supporting future standards as they develop.
* Comments — Visitors to your site can leave comments on individual entries, and through Trackback or Pingback can comment on their own site. You can enable or disable comments on a per-post basis.
* Spam protection — Out of the box WordPress comes with very robust tools such as an integrated blacklist and open proxy checker to manage and eliminate comment spam on your blog, and there is also a rich array of plugins that can take this functionality a step further.
* Full user registration — WordPress has a built-in user registration system that (if you choose) can allow people to register and maintain profiles and leave authenticated comments on your blog. You can optionally close comments for non-registered users. There are also plugins that hide posts from lower level users.
* Password Protected Posts — You can give passwords to individual posts to hide them from the public. You can also have private posts which are viewable only by their author.
* Easy installation and upgrades — Installing WordPress and upgrading from previous versions and other software is a piece of cake. Try it and you'll wonder why all web software isn't this easy.
* Easy Importing — We currently have importers for Movable Type, Textpattern, Greymatter, Blogger, and b2. Work on importers for Nucleus and pMachine are under way.
* XML-RPC interface — WordPress currently supports an extended version of the Blogger API, MetaWeblog API, and finally the MovableType API. You can even use clients designed for other platforms like Zempt.
* Workflow — You can have types of users that can only post drafts, not publish to the front page.
* Typographical niceties — WordPress uses the Texturize engine to intelligently convert plain ASCII into typographically correct XHTML entities. This includes quotes, apostrophes, ellipses, em and en dashes, multiplication symbols, and ampersands. For information about the proper use of such entities see Peter Sheerin's article The Trouble With Em ’n En.
* Intelligent text formatting — If you've dealt with systems that convert new lines to line breaks before you know why they have a bad name: if you have any sort of HTML they butcher it by putting tags after every new line indiscriminately, breaking your formatting and validation. Our function for this intelligently avoids places where you already have breaks and block-level HTML tags, so you can leave it on without worrying about it breaking your code.
* Multiple authors — WordPress' highly advanced user system allows up to 10 levels of users, with different levels having different (and configurable) privileges with regard to publishing, editing, options, and other users.
* Bookmarklets — Cross-browser bookmarklets make it easy to publish to your blog or add links to your blogroll with a minimum of effort.
* Ping away — WordPress supports pinging Ping-O-Matic, which means maximum exposure for your blog to search engines.
Project Template Changes in Visual Studio 2010
In earlier versions of ASP.NET, when you use Visual Studio to create a new Web Site project or Web Application project, the resulting projects contain only a Default.aspx page, a default Web.config file, and the App_Data folder, as shown in the following figure:
Visual Studio also supports an Empty Web Site project type, which contains no files at all, as shown in the following figure:
The result is that for the beginner, there is very little guidance on how to build a production Web application. Therefore, ASP.NET 4 Beta 2 introduces three new templates, one for an empty Web application project, and one each for a Web Application and Web Site project.
Empty Web Application Template
As the name suggests, the Empty Web Application template is a stripped-down Web Application project. You select this project template from the Visual Studio New Project dialog box, as shown in the following figure:
When you create an Empty ASP.NET Web Application, Visual Studio creates the following folder layout:
This is similar to the Empty Web Site layout from earlier versions of ASP.NET, with one exception. In Visual Studio 2010 Beta 2, Empty Web Application and Empty Web Site projects contain the following minimal Web.config file that contains information used by Visual Studio to identify the framework that the project is targeting:
Without this targetFramework property, Visual Studio defaults to targeting the .NET Framework 2.0 in order to preserve compatibility when opening older applications.
Web Application and Web Site Project Templates
The other two new project templates that are shipped with Visual Studio 2010 Beta 2 contain major changes. The following figure shows the project layout that is created when you create a new Web Application project. (The layout for a Web Site project is virtually identical.)
The project includes a number of files that were not created in earlier versions. In addition, the new Web Application project is configured with basic membership functionality, which lets you quickly get started in securing access to the new application. Because of this inclusion, the Web.config file for the new project includes entries that are used to configure membership, roles, and profiles. The following example shows the Web.config file for a new Web Application project. (In this case, roleManager is disabled.)
The project also contains a second Web.config file in the Account directory. The second configuration file provides a way to secure access to the ChangePassword.aspx page for non-logged in users. The following example shows the contents of the second Web.config file.
The pages created by default in the new project templates also contain more content than in previous versions. The project contains a default master page and CSS file, and the default page (Default.aspx) is configured to use the master page by default. The result is that when you run the Web application or Web site for the first time, the default (home) page is already functional. In fact, it is similar to the default page you see when you start up a new MVC application.
The intention of these changes to the project templates is to provide guidance on how to start building a new Web application. With semantically correct, strict XHTML 1.0-compliant markup and with layout that is specified using CSS, the pages in the templates represent best practices for building ASP.NET 4 Web applications. The default pages also have a two-column layout that you can easily customize.
For example, imagine that for a new Web Application you want to change some of the colors and insert your company logo in place of the My ASP.NET Application logo. To do this, you create a new directory under Content to store your logo image:
To add the image to the page, you then open the Site.Master file, find where the My ASP.NET Application text is defined, and replace it with an image element whose src attribute is set to the new logo image, as in the following example:
You can then go into the Site.css file and modify CSS class definitions to change the background color of the page as well as that of the header, as in the following example:
The result of these changes is that you can display a customized home page with very little effort:
Posted in: General | Tags: web application vsts vs 2010 web site project templates web application template web site template rolemanager