标题: VS 2010 and .NET 4 Series [打印本页] 作者: fm_yy 时间: 7-9-2009 23:39 标题: VS 2010 and .NET 4 Series 转自 Scott Gu的blog
英文的没有翻译
http://weblogs.asp.net/scottgu/a ... d-net-4-series.aspx作者: fm_yy 时间: 7-9-2009 23:40 标题: Clean Web.Config Files (VS 2010 and .NET 4.0 Series) Today’s post is about an admittedly small, but I still think kind of nice, change coming with ASP.NET 4.0: clean, simple, web.config files.
You’ll encounter this improvement the first time you do a File->New Project within Visual Studio 2010 and create an empty ASP.NET 4.0 Web application (which is why I thought it might be appropriate to-do as the first post).
Web.config files in .NET 3.0 and 3.5
Over the last few releases, the web.config files within new ASP.NET projects have steadily increased in size. For example: the default web.config file that is added to a new web project in Visual Studio 2008 SP1 is now some 126 lines long, and contains everything from tag definitions to definitions of handlers and modules to be included in the ASP.NET HTTP pipeline.
This increase in size is because .NET 3.0 and .NET 3.5 use the same CLR and machine.config configuration file as those shipped with .NET 2.0 – and simply add and update assemblies in the framework when they are installed. To avoid the risk of us accidentally overwriting customized settings within the original 2.0 machine.config on the machine, we didn’t register the tag definitions, handlers and modules that shipped with the new ASP.NET functionality that came with the .NET 3.0 and .NET 3.5 versions. Instead, we defaulted to having new projects register these settings within the application’s local web.config file instead. This was safer – but caused the web.config files to increase and become more complicated and harder to read.
Web.config files in .NET 4
.NET 4 includes a new version of the CLR, and a new .NET 4 specific machine.config file (which is installed side-by-side with the one used by .NET 2, .NET 3 and .NET 3.5).
The new .NET 4 machine.config file now automatically registers all of the ASP.NET tag sections, handlers and modules that we’ve added over the years, including the functionality for:
* ASP.NET AJAX
* ASP.NET Dynamic Data
* ASP.NET Routing (which can now be used for both ASP.NET WebForms and ASP.NET MVC)
* ASP.NET Chart Control (which now ships built-into ASP.NET V4)
What this means is that when you create a new “Empty ASP.NET application” project in VS 2010, you’ll find that the new default application-level web.config file is now clean and simple:
The first config section above just tells ASP.NET to enable debugging by default for the application, and indicates the version of .NET that Visual Studio should target when it provides intellisense (VS 2010 supports multi-targeting – and the intellisense within the IDE will automatically vary depending on which version of the framework you are targeting).
The second config section indicates whether to use “integrated” mode when running the ASP.NET application within IIS7 – which controls whether to run ASP.NET HttpModules for all requests within the application or just for the ASP.NET specific URLs. We enable this by default at the application level web.config file for new applications – since for compatibility reasons the default IIS7 setting registered at the machine-wide is to run modules only for ASP.NET URLs (and not for all requests).
Summary
The simplified web.config file in .NET 4 is an admittedly small change – but I think a nice one nonetheless, and one which makes the default experience when you create a new ASP.NET application a little cleaner and more approachable.
In the posts ahead I’ll be delving into many of the more substantial improvements coming with ASP.NET 4. (as well as a few more of the “small but nice tweaks” coming too)
Hope this helps,
Scott作者: fm_yy 时间: 7-9-2009 23:42 标题: Starter Project Templates (VS 2010 and .NET 4.0 Series) Today’s post is about another small, but I think nice, change coming with VS 2010 and ASP.NET 4 when you create new ASP.NET Web projects – which is the ability to create both “Empty projects” as well as to create projects that already have some layout and common functionality included in them, and which can help you get started when building a new application.
Creating New Projects
When you use the File->New Project or File->New Web Site menu commands within VS 2010, you’ll see a “New Project” dialog like below that allows you to filter by language and application type and select different project templates to use when creating new projects:
newproject1
VS 2010 ships with “empty” project templates for creating new ASP.NET applications – which will create minimal projects with just the bare essentials needed to get going. My last post in this series included a screenshot that shows what the “Empty ASP.NET Web Application” project template creates when you use it to start a new application.
Creating a New Project using a Starter Template
VS 2010 also ships with starter template projects that allow you to create a new ASP.NET application that has some layout/CSS structure and common functionality already implemented within it.
We first tried this concept with ASP.NET MVC 1.0 – whose project template provides a master page, CSS file, JavaScript libraries, login system, and a “home” and “about” page already wired up and implemented. VS 2010 adds support for this idea when creating new ASP.NET Web Forms projects as well.
When you choose the default “ASP.NET Web Application” project template, you’ll find that the ASP.NET Web Forms project created already has some directories and files contained within it:
It includes a Site.Master master page file that provides an overall layout for the site (with headers, footers, etc), and which uses a CSS stylesheet for all styles. It has a “Scripts” directory that contains jQuery within it (ASP.NET AJAX is available via the script manager control). It includes a “default.aspx” and “about.aspx” pages in the root directory that are based on the master page and include some boiler plate content. And it includes an “Account” directory that has some pages that implement a forms-based authentication system for users to log-in, register and change their passwords:
All of the styles and content within the site are configured using CSS, and take advantage of some of the new features with Web Forms in ASP.NET 4 – including clean client-side “id” names (no more ctrl_ mangled names – ASP.NET 4 gives you complete control over the client id), and CSS based rendering instead of table based rendering for the built-in server controls. I’ll discuss these new Web Forms features in a lot more depth in later posts in this series (along with a lot of other features being added).
Online Template Gallery
In addition to the built-in project templates, VS 2010 also support the ability when inside the “New Project” and “Add Item” dialogs to search an online gallery of additional templates to use. You can contribute your own templates to the gallery, rate and review submissions of others, and search and filter them by project type, keyword and community rating. You can then easily download and install any template locally directly within the dialog:
This will hopefully facilitate the creation of lots of useful project starter kits (of all types of projects – not just web) that people can easily discover and use to quickly get going when building solutions.
Hope this helps,
Scott
[ 本帖最后由 fm_yy 于 7-9-2009 20:48 编辑 ]作者: fm_yy 时间: 7-9-2009 23:49 标题: Multi-Targeting Support (VS 2010 and .NET 4 Series) Today’s post discusses VS 2010’s enhanced multi-targeting support – which allows you to use and target multiple versions of .NET. We did significant architectural work in the VS 2010 release to enable a number of new multi-targeting features, and provide a much better experience.
Understanding Side-by-Side
VS 2010 can be installed “side by side” with previous versions of Visual Studio. What this means is that you can install it on the same machine as VS 2008/VS 2005/VS 2003 – and use all of the versions at the same time if you’d like.
.NET 4.0 can also be installed “side by side” with previous versions of .NET on the same machine. .NET 4.0 has a new version number for both the framework libraries and CLR engine – which means it runs completely independently from .NET 2.0, 3.0 and 3.5. What this means is that you can install .NET 4.0 on a machine that has .NET 2.0/3.0/3.5 installed, and configure some applications to run using .NET 4.0 and others to run using the older .NET versions (the IIS admin tool allows you to configure this for ASP.NET applications). This allows you to use .NET 4.0 for new applications - without having to necessarily test and upgrade all your existing ones.
VS 2008’s Multi-Targeting Support
VS 2008 was the first release of Visual Studio that included multi-targeting support for .NET. What this meant was that you could use VS 2008 to create and edit not only .NET 3.5 projects, but also .NET 3.0 and .NET 2.0 projects as well. This allowed developers to more quickly upgrade and take advantage of new Visual Studio tooling features – without having to necessarily require the newer version of .NET to be installed on the clients and production servers running their applications.
VS 2008’s multi-targeting support was able to take advantage of the fact that .NET 2.0, .NET 3.0, and .NET 3.5 all ran on top of the same version of the CLR – and that the primary difference between the .NET versions was in their framework libraries. As a result, Visual Studio’s compilers were able to generate the same IL output, the debugger was able to debug against the same CLR engine, and the IDE support for multi-targeting was primary focused on filtering out new assemblies and project templates from showing up when they weren’t supported with a given .NET version.
This multi-targeting experience worked – although it wasn’t perfect. Intellisense within VS 2008 always shows the types and members for the .NET 3.5 version of a framework library (even if you are targeting .NET 2.0). This means that you can sometimes inadvertently end up using a method that is only in ASP.NET 3.5 even when you are working on a ASP.NET 2.0 project.
VS 2010’s Multi-Targeting Support
We made some pretty major architectural changes with VS 2010 to enable much better and more accurate multi-targeting support.
VS 2010 now ships what we call “reference assemblies” for each version of .NET. A “reference assembly” contains only the metadata of a particular framework assembly – and not its actual implementation (making it much smaller in size on disk). This metadata is enough, though, to ensure that VS 2010 can always provide 100% accurate intellisense when targeting a particular version of the .NET framework. It also means that properties exposed through the property grid within designers, API listings within the Object Browser, and all the other various places within the IDE accurately reflect the exact API version signature.
We also updated the VS 2010 debugger, profiler and compilers to be able to target multiple versions of the CLR.
Using VS 2010’s Multi-Targeting Support
To get a better understanding of how these new multi-targeting features work, let’s create a new ASP.NET Web Application using VS 2010. To-do this we can use the “File->New Project” menu command to bring up the “New Project” dialog. We’ll use the version drop-down at the top of the dialog to filter the project templates to only show those supported with .NET 2.0. We’ll then create a new ASP.NET 2.0 web application project:
Because we are targeting .NET 2.0 with this project, VS 2010 will automatically filter the toolbox and markup intellisense to only allow us to use those controls that shipped in ASP.NET 2.0. Unlike VS 2008, the VS 2010 property grid now automatically filters to only show those properties that were supported on the ASP.NET 2.0 button control:
When writing code, VS 2010 will also now only show code intellisense for those types and methods/properties/events supported with .NET 2.0. Below you can see intellisense for the ASP.NET 2.0 “Response” object when we type “Response.Re”:
When we run the application using the built-in VS web-server, it will run using the ASP.NET 2.0 version (and the VS 2010 debugger will debug the CLR 2.0 process):
We can optionally retarget our project to work with a later version of .NET by right-clicking on the project within the solution explorer and by bringing up its properties dialog. We can select the “target framework” dropdown within it and select the version of the .NET Framework we want to target:
We can choose from a variety of different .NET versions above. Included in the list is the "Server Core” profile that supports the GUI-less version of Windows Server 2008 R2 – and which does not support certain APIs. Because the reference assemblies we use for metadata and intellisense can support any version or release, we’ll even be able to distribute versions of them with future service packs if they introduce any new APIs (enabling 100% accuracy).
For this walkthrough, we’ll choose to move the project to use .NET 4.0. When we do this, VS 2010 will automatically update the project reference assemblies and the web.config file of our project to properly reflect the new version.
Once we do this, VS 2010 will filter the toolbox and markup intellisense to show us all of the new controls and properties available in the ASP.NET 4.0 version. For example, the property grid below now displays the new “ClientIDMode” property available on all controls in ASP.NET 4.0 - which gives you the ability to control how client id’s are output and avoid ugly client ids (a new ASP.NET 4.0 feature I’ll cover in a later blog post):
Now that we’ve upgraded the project to use .NET 4.0, VS 2010 will also now show us code intellisense for the new types and methods/properties/events on types in .NET 4.0. For example, below you can see some of the new redirect methods available on the ASP.NET 4.0 “Response” object (which previously did not show up when the project was targeting .NET 2.0):
The new Response.RedirectPermanent() method above makes it easy to issue “HTTP 301 Moved” responses – which can avoid your site accumulating stale links in search engines. The URL Routing engine is now supported by both ASP.NET Web Forms and ASP.NET MVC based applications, and the new Response.RedirectToRoute() method allows you to easily redirect to a route declared with it.
And lastly when we run the application using the built-in VS web-server, VS 2010 will now run it using the ASP.NET 4.0 version:
VS 2010’s multi-targeting support enables you to work on projects that target .NET 4.0, .NET 3.5, .NET 3.0 and .NET 2.0. It will allow you to start taking advantage of the new tooling features, without having to immediately upgrade the clients and servers running your application’s to .NET 4.0. The improved multi-targeting support will ensure that this experience is even better and more accurate than before.
Today’s post covers one of the general IDE improvements that I know a lot of people are already eagerly looking forward to with VS 2010 – multiple-monitor support.
Using Multiple Monitors
VS 2008 hosts all documents/files/designers within a single top-level window – which unfortunately means that you can’t partition the IDE across multiple monitors.
VS 2010 addresses this by now allowing editors, designers and tool-windows to be moved outside the top-level window and positioned anywhere you want, and on any monitor on your system. This allows you to significantly improve your use of screen real-estate, and optimize your overall development workflow.
Taking advantage of the multi-monitor feature is really easy to-do. Simply click on a document tab or tool-window and drag it to either a new location within the top-level IDE window – or outside of the IDE to any location on any monitor you want:
You can later drag the document/window back into the main window if you want to re-dock it (or right click and choose the re-dock option).
Visual Studio remembers the last screen position of documents when saved – which means that you can close projects and re-open them and have the layout automatically startup where you last saved it.
Some Multi-Monitor Scenarios
Below are some screen-shots of a few of the scenarios multi-monitor enables (obviously there are many more I’m not covering). Pretend each window in the screenshots below is on a different monitor to get the full idea…
Code source file support:
Demonstrates how code files can be split up across multiple monitors. Below I’ve kept a .aspx file in the main IDE window and then moved a code-behind file and a separate class file to a separate screen:
Demonstrates how any tool window/pane within VS10 can be split across multiple monitors. Below I’ve moved the test runner tool windows to a separate screen:
Demonstrates how a designer within VS can be split across multiple monitors. Below I’ve moved the WPF/Silverlight WYSWIYG designer and the property grid to a separate screen (the code behind file is still in the main window). Note how the VS10 property grid now supports inline color editors, databinding, styles, brushes, and a whole bunch more for WPF and Silverlight applications (I’ll cover this in later blog posts):
If you work on a system that has multiple monitors connected to it, I think you are going to find the new multi-monitor support within VS10 a big productivity boost.
If you don’t already have multiple monitors connected to your computer, this might be a good excuse to get some… :-)
Hope this helps,
Scott
[ 本帖最后由 fm_yy 于 7-9-2009 20:56 编辑 ]作者: fm_yy 时间: 7-9-2009 23:56 标题: Code Optimized Web Development Profile (VS 2010 and .NET 4.0 Series) Today’s post covers a new “Web Development (Code Optimized)” profile option we are introducing with VS 2010 that allows you to optionally configure Visual Studio to run in an IDE layout mode that hides the WYSIWYG web designer and instead optimizes around a rich “source editing focused” tooling experience.
VS 2010 Web Profiles
When you first run VS 2010 it prompts you to select an IDE profile to use. The profile you select will configure how tool windows are displayed/docked in the IDE by default and set the default keyboard shortcuts. You can then customize any of these settings by using the Tools->Options menu within the IDE and then override/change them. You can also later reset your profile and pick a different one by choosing the Tools->Import and Export Settings menu command.
One of the things you’ll notice when you run VS 2010 Beta2 for the first time is the inclusion of two “Web Development” profiles in the list of options:
The first “Web Development” profile option is an evolution of the existing web development profile option from VS 2008 (with some nice improvements that help improve screen real estate usage with VS 2010). It also allows you to take advantage of all the great WYSIWYG HTML and ASP.NET Page designer improvements we’ve done with the VS 2010 release (I’ll cover these in more detail in later blog posts in this series).
The second “Web Development (Code Optimized)” profile option is a new profile we are introducing with VS 2010 that is optimized for web developers who do not want to use a WYSIWYG designer when doing their web development, and who prefer a “source only” editing experience when working on pages. This IDE profile option hides the WYWISYG page designer tabs, and configures a default IDE layout that maximizes the amount of code that is displayed on the screen (with a minimum of toolbars and tool windows). It still provides a full intellisense/debugging and source editor experience for pages.
Comparing the VS 2010 Web Development Profiles
You can get a sense of the difference between the two profiles by comparing screen-shots of the Visual Studio IDE layout immediately after the two different “Web Development” profiles are applied:
Screenshot of the “Web Development” Profile:
The layout below demonstrates the default IDE layout (at a 750x650 monitor resolution) when the standard “Web Development” profile is applied. This profile is an evolution of the existing “Web Development” profile in VS 2008 and exposes design/split/source tabs within the document window of any HTML or ASP.NET page:
Screenshot of the “Web Development (Code Optimized)” Profile:
The screen-shot below demonstrates the default IDE layout (at a 750x650 monitor resolution) when the new “Web Development (Code Optimized)” profile is applied. As you can see, the profile optimizes the screen real estate around displaying and editing code on the screen, hides all toolbars by default, and disables and hides the designer tabs within the document windows of HTML and ASP.NET pages:
2 New Profile Full IDE Single File
Mixing and Matching Features
All of the different features used in both the standard “Web Development” profile and the “Web Development (code optimized)” profile are exposed via Visual Studio’s Tools->Options configuration dialog. This means that you can start with any of the VS profiles (including the General, VB and C# profiles) and turn on or off individual features to customize the IDE layout and editing experience however you want it to be.
For example: below you can see the Tools->Options dialog checkbox to enable or disable the HTML designer (which will configure whether the Design/Split/Source tabs are shown at the bottom of each page):
This gives you the flexibility to customize your development experience however you want and create a personalized tooling experience optimized for you and your preferred way of doing development.
The two web development profiles that ship in the box provide two good preconfigured starting points that we think offer a nice set of defaults for a large set of the web developers out there. You can easily choose to start with whichever one feels best to you, and optionally configure them further however you want.
Summary
We are offering the new profile simply as an option for those who prefer a source-focused web development experience. The WYSIWYG HTML/ASP.NET designer continues to be enabled by default with all the other VS 2010 profiles (just like it does with VS 2008), and we have also made a lot of improvements to it with the VS 2010 release (I’ll blog more details about these in later posts). So don’t worry – the WYSIWYG designer definitely isn’t going away, and will continue to be enhanced and improved with each release.
We think the new “Web Development (Code Optimized)” profile, though, is a nice new option for developers who prefer a “source editing focused” web development experience, and who do not use the WYSIWYG designer. The profile option provides an easy way for them to hide the designer (along with its associated tool windows and toolbars) from the IDE layout and instead use a source-focused web development experience.
Hope this helps,
Scott
[ 本帖最后由 fm_yy 于 7-9-2009 20:59 编辑 ]作者: fm_yy 时间: 7-9-2009 23:59 标题: ASP.NET, HTML, JavaScript Snippet Support (VS 2010 and .NET 4.0 Series) Today’s post covers another useful improvement in VS 2010 – HTML/ASP.NET/JavaScript snippet support. Snippets allow you to be more productive within source view by allowing you to create chunks of code and markup that you can quickly apply and use in your application with a minimum of character typing.
Visual Studio has supported the concept of “snippets” for VB and C# in previous releases – but not for HTML, ASP.NET markup and JavaScript. With VS 2010 we now support snippets for these content types as well.
Using ASP.NET Snippets
Let’s walkthrough how we can use snippets to quickly implement a common security scenario. Specifically, we’ll implement the functionality necessary to display either a “[ Login ]” link or a “[ Welcome UserName ]” message at the the top right of a site depending on whether or not the user is logged in:
The above functionality is automatically added for you when you create a project using the new ASP.NET Project Starter Template in VS 2010. For the purpose of this walkthrough, though, we’ll assume we are starting with a blank master page and will build it entirely from scratch.
We’ll start by adding a standard <div> element to a master page, and then position our cursor within it:
We are going to use the built-in <asp:loginview> control to help implement our scenario. The <asp:loginview> control is a templated control (first introduced with ASP.NET 2.0) that allows us to easily switch between “Anonymous” and “LoggedIn” templates that automatically display depending on whether the user is authenticated. Rather than type the <asp:loginview> markup manually, we’ll instead use the new snippet support in VS 2010.
Typing in “<log” in the editor will bring up intellisense and display available elements, controls and code snippets that start with those characters.
Now that we’ve selected the snippet we want to use, we can hit the “tab” key again to execute the snippet – which will cause it to immediately replace the snippet name with the markup below. Notice below the snippet added a new <asp:loginview> control for us and automatically defined the two most commonly used templates on it. We were able to implement that all with just 6 keystrokes (4 keystrokes to type “<log”, and then 2 tab keystrokes).
We’ll select the built-in “a” code snippet from the above list and hit the “tab” key to complete it. When we hit tab again it will execute the snippet – which will cause it to replace the snippet name with the markup below:
The “href” attribute attribute value and the inner content of the <a> element above are highlighted with a green background color. This indicates that these values are replaceable parameters and that we can automatically tab between them when filling them out – avoiding the need to use the cursor keys or touch the mouse (making things much faster).
Without having to move our cursor or mouse, we can begin typing the login page URL we want to send users to if they are not authenticated on the site:
When done, we can hit the “tab” key and VS will automatically highlight the second content parameter in the editor for us (no manual cursor movement or mouse action required):
Once done with the “<AnonymousTemplate>” we can move onto the "<LoggedInTemplate>”. We’ll type “<log” in the editor to bring up intellisense – and select the built-in “loginname” snippet:
The “FormatString” property value above was automatically populated for us with a default welcome text message. The value is also automatically highlighted in case we want to change it (without having to move the mouse or cursor keys). For this sample we’ll just keep the default text.
The total number of key strokes to implement this entire scenario is less than 15% of what we would previously have had to type. Typing fast, I found I could implement the entire scenario in less than 15 seconds :-)
ASP.NET MVC Snippets
Built-in snippets are available for all ASP.NET controls and HTML markup elements.
Built-in snippets are also available for common ASP.NET MVC view scenarios, and for the built-in ASP.NET MVC HTML helpers.
For example, we can type “<act” within a ASP.NET MVC view and select the “actionlink” snippet:
Notice that the “linktext” and “actionname” values are marked as snippet parameters – which means we can easily replace them without having to use the cursor keys or touch the mouse. The first linktext parameter value is selected by default – which means we can just type to immediately replace the value, then hit tab to immediately select and replace the second actionname parameter:
Visual Studio 2010 will include more than 200 built-in snippets that you can immediately use when you install the product.
What is really nice is that you are not limited to only using the built-in snippets. You can also easily create your own snippets (complete with replaceable parameters) and both import them into VS 2010, as well as easily share them with other developers. This makes it easy for you to quickly automate your own common tasks.
This article describes the snippet support that already exists in VS 2008, and provides a little more context on how to create and manage custom snippets.
Summary
Snippets are a useful feature that enable you to reduce keystrokes within the editor, and allow you to complete scenarios and tasks much faster. Having snippets now enabled in not just VB and C#, but also in HTML, ASP.NET and JavaScript files, makes this capability even more useful – and can make you even more productive.
Hope this helps,
Scott
[ 本帖最后由 fm_yy 于 7-9-2009 21:06 编辑 ]作者: radar 时间: 8-9-2009 22:05
很强大作者: procoder 时间: 9-9-2009 15:15
这么快就关注.net 4了。作者: fm_yy 时间: 9-9-2009 19:52
其实我还在用 2.0
3.0 3.5都不会用作者: fm_yy 时间: 9-9-2009 20:21 标题: What’s new in ASP.NET 4.0 - Part I - View State & SEO Improvements http://geekswithblogs.net/rangan ... in-asp.net-4.0.aspx
UPDATE dated August 17, 2009
Once I posted this entry, there is a lot of interest that has been shown and few queries as well. So I thought I need to update this post.
This is only the first post in the series on ASP.NET 4.0 fetaures. There are lot of ground breaking things and other enhancements that are pretty exciting.
To the folks who asked for "why MS changing dev platform once in 18 months"
There is no change. there are a few enhancements. Post .NET 2.0 there have been a lot of additional APIs such as LINQ, Entity Framework etc., which are different ways of data handling. While core ADO.NET is still valid, these are additional enhancements that can be used at the Developer's / Architect's discretion.
I will be covering more features in the following post.
Thanks for the inerest
With Visual Studio 2010 Beta 1 and .NET Framework Beta 1 out for some time, this post is due from me for a long time. ASP.NET 4.0 has many improvements for different set of scenarios such as Webforms, Dynamic Data & AJAX based web development. There are also a lot of enhancements to the core runtime that powers ASP.NET such as Caching, Session & Request/Response objects.
For this post, we will examine some of the web form enhancements. There are sure a lot of them and we will examine some of them in the future posts.
Controlling View State using the ViewStateMode Property – Performance Enhancement
One of the most complained thing in ASP.NET Webform is the growing viewstate which becomes a concern for performance. While earlier you can set the EnableViewState property to true or false, post that, all the controls, by default inherit and even if you set it to enabled at control level, the behaviour was inconsistent.
With ASP.NET 4.0, the ViewStateMode property helps to determine for every control, whether the ViewState should be enabled, disabled or inherited accordingly. Ex.-
<aspanel ID="pnlViewState" runat="server" ViewStateMode="Disabled">
Disabled: <aspabel ID="label1" runat="server" Text="Value set in markup" ViewStateMode="Inherit" /><br />
Enabled: <aspabel ID="label2" runat="server" Text="Value set in markup" ViewStateMode="Enabled" />
<hr />
<asp:button ID="Button1" runat="server" Text="ostback" />
</aspanel>
In the code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
label1.Text = "Value set in code behind";
label2.Text = "Value set in code behind";
}
}
When you run the above page, you can find that the intial value for both the labels is set to “Value set in code behind” whereas after clicking on the button (postback), the value of label1 changes to “Value set in markup” whereas the value of label2 remains unchanged. As you can see, the Panel which holds both these lables has ViewStateMode set to Disabled and label1 is inherting the mode (this is the default if not specified) and label2 has it enabled. That is the reason label2 maintains viewstate while label1 loses it.
While it is arguably possible using the simple EnableViewState property earlier, it was never consistent. Considering the fact that in most of our performance sessions, we talk about disabling viewstate and then enabling it at control level while it doesnt work, this ViewStateMode is a welcome architectural change to improve performance.
Page Meta Keyword & Description – Search Engine Optimization feature
Upto Visual Studio 2008, one can set the Title of the page declaratively or through program using Page.Title. However, as more and more web traffic is happening through search engines, Page’s Title, Keyword and description become more important. Although the Keyword feature was exploited and hence many search engines today ignore it, Page Description is something still major search engines such as Google, Bing use for identifying and indexing pages based on content.
The new feature in ASP.NET 4.0 allows users to programmatically set the Page Description and Keywords as follows:-
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Title = "My ASP.NET Blog";
this.Page.MetaKeywords = "ASP.NET, Web Development, Blog, ASP.NET Blog";
this.Page.MetaDescription = "This Blog contains posts related to ASP.NET and Web Development";
}
The above code appends the following markup
<meta name="keywords" content="ASP.NET, Web Development, Blog, ASP.NET Blog" />
<meta name="description" content="This Blog contains posts related to ASP.NET and Web Development" />
And the way it works is that, if the meta tags are already present in the HTML markup, whatever is set in the code behind will fill up the “content” part alone if the “name” tag is matching.
Although this looks simple, it is very useful in cases where you want to set these dynamically based on a condition / criteria. So far, these were set statically in the HTML. Now with Page Class level access, these can be set dynamically.
There are many more enhancements to Webforms such as Routing improvements, setting ClientID etc., which we will examine in the future posts.
When I wrote the first post in this series, there was tremendous amount of interest generated and also a lot of feedback requesting to post some of the advanced features. Like I said earlier, ASP.NET 4.0 has lots of new features some of them as simple as Page.Title whereas so as big as caching improvements. This post covers one such feature which is Routing in Webforms. Although Routing was available even in .NET 3.5 SP1, (check this excellent post by Phil Haack on implementing Routing in ASP.NET 3.5 with .NET 3.5 SP1), it was kind of less known. Also the plumbing work was too much for getting it implemented.
However, this has been much simplified in ASP.NET 4.0. To give a background, System.Web.Routing is the namespace that provides the all important RouteTable & PageRouteHandler class. Initially System.Web.Routing was an integral part of ASP.NET MVC. However, the team must have anticipated that Routing is more important even for Webforms and hence they moved this DLL outside the scope of just MVC and made it available to Webforms as well.
Importance of Routing: Getting friendlier URLs which help in better search engine optimization and indexing. Cleaner URLs that can be bookmarked than the unfriendly querystring based approach. As more and more URLs are available, the chances of improvement in search engine ranking becomes higher. These are some of the general advantages of Routing and friendly URLs.
Ok, now that the context is established, lets start with our sample. To begin with, I am using Visual Studio 2010 Beta 1 (download link) and Northwind Sample Database (download link)
I created a “File – New Project – ASP.NET Web Application” leaving the default .NET 4.0 as the framework option. Then, I created a bunch of pages i.e Products.aspx, Categories.aspx and also the Global.asax (Add – New Item – Global Application Class)
On the Default.aspx page, I added a GridView and configured it to use the Northwind Database Connection String and the Categories Table therein. I modified the auto-generated bound columns with a Template Column to accomodate our link to Categories Page. The modified GridView code looks as below:-
As you can see, the Item Template for Category Name is modified to sport a hyperlink to “Categories” page followed by the CategoryName itself. This would mean that the URL for a category, say Beverages would point to Categories/Beverages
Similarly, on the Categories page, I added a GridView and configured it to use the “Allphabetical List of Products” Table. I also modified the Bound field for ProductName to a template column to have a link to another Products Page. The modified GridView code looks as below:-
Note, while configuring above GridView, in the screen where we configure DataSource, I also added a where condition to accomodate the Route Request. The screen looks as below:-
Note that I had selected the Where condition from the first screen and specified “CategoryName” under Column,“=” under Operator and “Route” under Source. Also specified are the RouteKey “catname” and DefaultValue “Beverages”. Post this, I just had to click on “Add” and then “Ok” to get a conditional select statement in the SQL DataSource (note: for the purpose of this demo, I have used SQL DataSource. But this would work even if you used any other datasource type / written ADO.NET Code). The “Route” type is new feature added under Source in Visual Studio 2010.
Once the above configuration is done, the SQL DataSource code looks as below:-
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
C
SelectCommand="SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued] FROM [Alphabetical list of products] WHERE ([CategoryName] LIKE '%' + @CategoryName + '%')">
<SelectParameters>
<asp:RouteParameter DefaultValue="Beverages" Name="CategoryName"
RouteKey="catname" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
I have also added a label to the page just to show the term used to filter and the value for that can be picked up from the Page.RouteData values in the codebehind as follows:-
Before getting into Route Configuration, I also added a DetailsView control in the Products.aspx page to show the complete details of a product. And when configuring the DataSource for the DetailsView, I again specified the WHERE condition to the picked up from the RouteData that would come from the above GridView in Catagories Page.
Once this is done, all that is pending is to configure the Route Values. In .NET 3.5 SP1 if you want to establish routing, you would have to manually create the WebFormRouteHandler Class and make sure all the pages inherit from this class. However, in .NET 4.0, it has been much simplied. All I had to do was open the Global.asax and add the following
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add("roductRoute", new Route("Categories/Products/{productname}",
new PageRouteHandler("~/Products.aspx")));
RouteTable.Routes.Add("CategoryRoute", new Route("Categories/{catname}",
new PageRouteHandler("~/Categories.aspx")));
}
(note you would need to add System.Web.Routing namespace to be able to use PageRouteHandler, RouteTable classes etc.,)
So, in the Default.aspx page, all the Catagories would have a link that points to /Categories/<CategoryName> and in the Categories.aspx page, all the ProductNames would have a link that points to /Categories/Products/<roductName>
A typical URL is http://localhost/Categories/Condiments and http://localhost/Categories/Products/Aniseed%20Syrup
Note that similarly, we have close to 10 URLs for Beverages and around 80 URLs (a URL for each product as above) for Products in this particular application.
You can download the sample from (Add your connectionstring to Northwind Database in the web.config file)