What’s new in ASP.NET 4.0

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.-

<asp:Panel ID="pnlViewState" runat="server" ViewStateMode="Disabled">
      Disabled: <asp:Label ID="label1" runat="server"  Text="Value set in markup" ViewStateMode="Inherit"  /><br />
           Enabled: <asp:Label ID="label2"  runat="server" Text="Value set in markup" ViewStateMode="Enabled" />
  <hr />
  <asp:button ID="Button1" runat="server"  Text="Postback" />
    </asp:Panel>

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.

Cheers !!!

Posted in: asp.net | Tags: asp.net asp.net 4.0 .net 4.0 meta keyword description seo eventargs webform clientid

ASP.NET MVC improvement in Visual studio 2010

ASP.NET MVC was introduced as an add-on framework to ASP.NET 3.5 SP1 in March 2009. Visual Studio 2010 will include a preview of ASP.NET MVC 2. When Visual Studio 2010 ships, it will include the RTM version of ASP.NET MVC 2. The version of ASP.NET MVC 2 that is included in ASP.NET 4 Beta 2 includes new features and capabilities.

Areas Support

Areas let you group controllers and views into sections of a large application in relative isolation from other sections. Each area can be implemented as a separate ASP.NET MVC project that can then be referenced by the main application. This helps manage complexity when you build a large application and makes it easier for multiple teams to work together on a single application.

Data-Annotation Attribute Validation Support

DataAnnotations attributes let you attach validation logic to a model by using metadata attributes. DataAnnotations attributes were introduced in ASP.NET Dynamic Data in ASP.NET 3.5 SP1. These attributes have been integrated into the default model binder and provide a metadata-driven means to validate user input.

Templated Helpers

Templated helpers let you automatically associate edit and display templates with data types. For example, you can use a template helper to specify that a date-picker UI element is automatically rendered for a System.DateTime value. This is similar to field templates in ASP.NET Dynamic Data.

The Html.EditorFor and Html.DisplayFor helper methods have built-in support for rendering standard data types as well as complex objects with multiple properties. They also support basic customization of rendering by letting you apply data-annotation attributes like DisplayName and ScaffoldColumn to the ViewModel object.

Often you want to customize the output from UI helpers even further and have total control over what is generated. The Html.EditorFor and Html.DisplayFor helper methods support this using a templating mechanism that lets you define external templates that can override and control the output rendered. The templates can be rendered on a per-class basis.

From: http://aspnetmvc.info/wp/2009/09/asp-net-mvc-improvement-in-visual-studio-2010/ Posted in: General asp.net | Tags: .net 4.0 mvc visual studio visual studio 2010 asp.net mvc framework data annotation attribute validation support html.editrofor displayname vewmodel

Visual Studio 2010 Web Designer Improvements

The Web page designer in Visual Studio 2010 has been enhanced for greater CSS compatibility, includes additional support for HTML and ASP.NET markup snippets, and features a redesigned version of IntelliSense for JScript.

Improved CSS Compatibility

The Visual Web Developer designer in Visual Studio 2010 has been updated to improve CSS 2.1 standards compliance. The designer better preserves integrity of the HTML source and has greater overall robustness than in previous versions of Visual Studio. Under the hood, architectural improvements have also been made that will better enable future enhancements in rendering, layout, and serviceability.

HTML and JScript Snippets

In the HTML editor, IntelliSense auto-completes tag names. The IntelliSense Snippets feature auto-completes entire tags and more. In Visual Studio 2010, IntelliSense snippets are supported for JScript, alongside C# and Visual Basic, which were supported in earlier versions of Visual Studio.

Visual Studio 2010 includes over 200 snippets that help you auto-complete common ASP.NET and HTML tags, including required attributes (such as runat="server") and common attributes specific to a tag (such as ID, DataSourceID, ControlToValidate, and Text).

You can download additional snippets, or you can write your own snippets that encapsulate the blocks of markup that you or your team use for common tasks.

JScript IntelliSense Enhancements

In Visual 2010, JScript IntelliSense has been redesigned to provide an even richer editing experience. IntelliSense now recognizes objects that have been dynamically generated by methods such as registerNamespace and by similar techniques used by other JavaScript frameworks. Performance has been improved to analyze large libraries of script and to display IntelliSense with little or no processing delay. Compatibility has been dramatically increased to support nearly all third-party libraries and to support diverse coding styles. Documentation comments are now parsed as you type and are immediately leveraged by IntelliSense.

Posted in: programming software | Tags: .net 4.0 javascript visual studio 2010 html.editrofor web designer improvements html and jscript snippets css compatibility datasourceid controltovalidate jscript intellisense registernamespace intellisense

Named and Optional Arguments in C# 4.0

Named and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.

Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.

Even in APIs for .NET however you sometimes find yourself compelled to write many overloads of a method with different combinations of parameters, in order to provide maximum usability to the callers. Optional parameters are a useful alternative for these situations.

Optional parameters

A parameter is declared optional simply by providing a default value for it:

public void M(int x, int y = 5, int z = 7);

Here y and z are optional parameters and can be omitted in calls:

M(1, 2, 3); // ordinary call of M
M(1, 2); // omitting z – equivalent to M(1, 2, 7)
M(1); // omitting both y and z – equivalent to M(1, 5, 7)

Named and optional arguments

C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead any argument can be passed by name. Thus if you want to omit only y from a call of M you can write:

M(1, z: 3); // passing z by name

or

M(x: 1, z: 3); // passing both x and z by name

or even

M(z: 3, x: 1); // reversing the order of arguments

All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1.

Optional and named arguments can be used not only with methods but also with indexers and constructors.

Overload resolution

Named and optional arguments affect overload resolution, but the changes are relatively simple:

A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type.

Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes.

If two signatures are equally good, one that does not omit optional parameters is preferred.

M(string s, int i = 1);
M(object o);
M(int i, string s = “Hello”);
M(int i);

M(5);

Given these overloads, we can see the working of the rules above. M(string,int) is not applicable because 5 doesn’t convert to string. M(int,string) is applicable because its second parameter is optional, and so, obviously are M(object) and M(int).

M(int,string) and M(int) are both better than M(object) because the conversion from 5 to int is better than the conversion from 5 to object.

Finally M(int) is better than M(int,string) because no optional arguments are omitted.

Thus the method that gets called is M(int).

Posted in: programming | Tags: c# .net 4.0 c# 4.0 named and optional arguments optional parameters resolution

Features for COM interop in C# 4.0

Dynamic lookup as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove even more of the speed bumps, a couple of small COM-specific features are also added to C# 4.0.

Dynamic import

Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance.

In order to facilitate a smoother experience, you can now choose to import these COM APIs in such a way that variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them.

This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say

excel.Cells[1, 1].Value = "Hello";

instead of

((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";

and

Excel.Range range = excel.Cells[1, 1];

instead of

Excel.Range range = (Excel.Range)excel.Cells[1, 1];

Compiling without PIAs

Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application.

The no-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded.

Omitting ref

Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters.

It therefore seems unreasonable that a C# programmer should have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such a method, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference.

Open issues

A few COM interface features still are not surfaced in C#. Most notably these include indexed properties and default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them.

There are currently no plans to address these remaining speed bumps in C# 4.0.

Posted in: programming | Tags: c# .net 4.0 dynamic c# 4.0 dynamic import interop open issues omitting ref