Tuesday, June 15, 2010

Features and Functionality of BCL in .Net 4.0

Since the launch of .Net 4.0 BCL has been in focus. BCL stands for Base Class Library. Following are the features of BCL that are included in .Net 4.0.


Summary of New BCL Functionality in .NET 4.0

  • Complex Number
  • Location
  • IObservable
  • Stream.CopyTo
  • Guid.TryParse, Version.TryParse, and Enum.TryParse
  • Enum.HasFlag
  • String.Concat and String.Join overloads that take IEnumerable
  • String.IsNullOrWhiteSpace
  • Environment.SpecialFolder additions
  • Environment.Is64BitProcess and Environment.Is64BitOperatingSystem
  • Path.Combine params support
  • TimeSpan Globalized Formatting and Parsing
  • Stopwatch.Restart
  • StringBuilder.Clear
  • IntPtr and UIntPtr Addition and Subtraction operators
  • ServiceInstaller.DelayedAutoStart
  • ObservableCollection moved to System.dll

Complex Number

System.Numerics.Complex represents a complex number comprised of a real number and imaginary number.  Complex supports both rectangular coordinates (real and imaginary) and polar coordinates (magnitude and phase measured in radians) and supports arithmetic and trigonometric operations.  Complex numbers are used in a number of areas including high-performance computing, graphing and charting, electrical engineering (e.g. Fourier transforms), and other numerical applications.

Location

System.Device.Location (which can be found in System.Device.dll) enables .NET applications running on Windows 7 to determine the current geo-location (e.g. latitude/longitude) of the device.  Windows 7 supports a number of different location sensors, including GPS devices and WWAN radios, and automatically handles transitioning between different sensors — if multiple sensors are available — to provide the most accurate data for the current situation. .NET applications will be able to use this new API to access the following data (if available): latitude, longitude, altitude, horizontal and vertical accuracy, course, speed, and civic address (i.e. country/region, state/province, city, postal code, street, building, floor level). 

IObservable

System.IObservable and System.IObserver provide a general mechanism for push-based notifications and can be used to represent push-based, or observable, collections.  Anyone familiar with design patterns will recognize these interfaces as representations of the well-known observer pattern.  IObservable opens up the doors to some exciting new paradigms for event-based and asynchronous programming on .NET.  A great example of this is the Reactive Framework (RX), which is a library of extension methods (not included as part of .NET 4) that implement the LINQ Standard Query Operators and other useful stream transformation functions for IObservable.  F# first-class events also support IObservable and F# includes a library of Observable operators similar to those available in RX.  Imagine being able to do LINQ-style queries against events; this is just one of the kinds of things that IObservable enables.  To help grasp the power of IObservable, I encourage you to watch the Channel 9 videos of Erik Meijer introducing RX and Wes Dyer and Kim Hamilton discussing IObservable in the BCL.
You may be wondering if IObservable is meant to replace events in .NET.  The answer is largely “no,” but you certainly could use it in place of events if you wanted to.  Events are a well-known mechanism for notification in .NET and are already familiar to .NET developers.  As such, they will continue to be the primary mechanism for notification that we recommend for .NET APIs.  The great thing about IObservable is that it is fairly straightforward for callers to convert any existing event into an IObservable.  RX provides built-in methods that do this conversion and F# has support for this built-in to the language.  Stay tuned to this blog for more news about RX in the future.

Stream.CopyTo

When working with Streams, how many times have you had to write the following boiler-plate code to read from one stream and write the contents to another stream?
Stream source = ...;
Stream destination = ...;
byte[] buffer = new byte[4096];
int read;
while ((read = source.Read(buffer, 0, buffer.Length)) != 0) {
    destination.Write(buffer, 0, read);
}
In .NET 4, you no longer have to write this code.  We’ve added a new CopyTo method to Stream that allows you to simply write:
Stream source = ...;
Stream destination = ...;
source.CopyTo(destination);


Guid.TryParse, Version.TryParse, and Enum.TryParse

We’ve added TryParse to System.GuidSystem.Version, and System.Enum.  Enum.TryParse is generic, a nice improvement over the existing non-generic Parse method, which leads to much cleaner code.
On previous versions of .NET, to parse an enum value, you’d write something like this:
try {
    string value = Console.ReadLine();
    FileOptions fo = (FileOptions)Enum.Parse(typeof(FileOptions), value);
    // Success
}
catch {
    // Error
}

On .NET 4, you can use the new generic TryParse method:

string value = Console.ReadLine();
FileOptions fo;
if (Enum.TryParse(value, out fo)) {
    // Success
}


Enum.HasFlag

We’ve added a new convenience method to System.Enum that makes it super easy to determine if a flag is set on a particular Flags enum, without having to remember how to use the bitwise operators.  This also allows for more readable code.

In VB:

Dim cm As ConsoleModifiers = ConsoleModifiers.Alt 
Or ConsoleModifiers.Shift
Dim hasAlt1 As Boolean = (cm And ConsoleModifiers.Alt) = 
ConsoleModifiers.Alt ' using bitwise operators
Dim hasAlt2 As Boolean = cm.HasFlag(ConsoleModifiers.Alt) 'using HasFlag

In C#:

ConsoleModifiers cm = ConsoleModifiers.Alt | ConsoleModifiers.Shift;
bool hasAlt1 = (cm & ConsoleModifiers.Alt) == ConsoleModifiers.Alt; 
// using bitwise operators
bool hasAlt2 = cm.HasFlag(ConsoleModifiers.Alt); // using HasFlag


String.Concat and String.Join overloads that take IEnumerable

We’ve added new overloads of String.Concat and String.Join that take IEnumerable, adding to the existing overloads that take arrays.  This means you can pass any collection that implements IEnumerable to these APIs without having to first convert the collection into an array.  We’ve also added “params” support to the existing array-based String.Join overload, which allows you to write more succinct code.  In C#:

String.Join(", ", new string[] { "A", "B", "C", "D" }); 
// you used to have to write this
String.Join(", ", "A", "B", "C", "D"); // now you can write this


String.IsNullOrWhiteSpace

This new convenience method is similar to the existing IsNullOrEmpty method, but in addition to checking if the string is null or empty, it also checks to see if the string only consists of white-space characters, as defined by Char.IsWhiteSpace.  It works great for Code Contract preconditions.

Environment.SpecialFolder additions

We’ve added a number of new values to the Environment.SpecialFolder enum:
  • AdminTools
  • CDBurning
  • CommonAdminTools
  • CommonDesktopDirectory
  • CommonDocuments
  • CommonMusic
  • CommonOemLinks
  • CommonPictures
  • CommonProgramFilesX86
  • CommonPrograms
  • CommonStartMenu
  • CommonStartup
  • CommonTemplates
  • CommonVideos
  • Fonts
  • LocalizedResources
  • MyVideos
  • NetworkShortcuts
  • PrinterShortcuts
  • ProgramFilesX86
  • Resources
  • SystemX86
  • Templates
  • UserProfile
  • Windows
We’ve also added a new overload to Environment.GetFolderPath that takes a newSpecialFolderOption enum, allowing you to specify some additional options, such as “Create” (to create the directory if it doesn’t exist) and “DoNotVerify” (to just return the path without checking if it exists, which can help reduce lag time if the directory is on a network share).

Environment.Is64BitProcess and Environment.Is64BitOperatingSystem

These new convenience APIs make it easy to determine the bitness of the current process and operating system.  Environment.Is64BitProcess is equivalent to calling IntPtr.Size == 8.  Environment.Is64BitOperatingSystem will tell you if the underlying OS is 64-bit.  Note that it is possible for Environment.Is64BitProcess to return false and Environment.Is64BitOperatingSystem to return true if the process is a 32-bit process running on a 64-bit operating system under WOW64.

Path.Combine params support

Have you ever had to nest calls to Path.Combine like this:

Path.Combine("dir1", Path.Combine("dir2", Path.Combine("dir3", "dir4")));

With .NET 4, you can simply write:

Path.Combine("dir1", "dir2", "dir3", "dir4");


TimeSpan Globalized Formatting and Parsing

In previous versions of .NET, TimeSpan only supported a single culture-agnostic format for formatting and parsing.  This meant if you called ToString on a French machine the output would not match culture settings, making the application appear not to be globalized.  This is often noticeable in apps that display results from SQL databases that use the frequently used Time column type, because SQL’s Time maps to TimeSpan in .NET.  For example:
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Console.WriteLine(new TimeSpan(0, 1, 1, 1, 1));
Console.WriteLine(12.34);
Output:
01:01:01.0010000
12,34
The output from TimeSpan.ToString is a culture-agnostic format so it uses a '.' as the decimal separator, whereas Double uses ',' based on the current culture.
In .NET 4, System.TimeSpan now supports formatting and parsing based on culture settings via new overloads of ToStringParse, and TryParse, and new ParseExact andTryParseExact methods.  The default ToString overload still behaves the same for backwards compatibility, outputting a constant, culture-agnostic format, but the new overloads allow you to specify additional culture-sensitive formats.  You can pass the “g” format (general format) to the new ToString overload to specify a culture-sensitive format:
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Console.WriteLine(new TimeSpan(0, 1, 1, 1, 1).ToString("g"));
Console.WriteLine(12.34);
Output:
01:01:01,0010000
12,34
With this new format, the output from TimeSpan is in line with the user’s culture settings.

Stopwatch.Restart

This is a new convenience method that is equivalent to calling Stopwatch.Reset followed by Stopwatch.Start.

StringBuilder.Clear

In previous versions of .NET, you could clear StringBuilder by setting the Length property to 0.  This isn’t very discoverable, so we’ve added StringBuilder.Clear as a more discoverable equivalent.

IntPtr and UIntPtr Addition and Subtraction operators

Adding an offset to an IntPtr or UIntPtr can be error prone and often introduces subtle bugs on 64-bit machines if not done correctly.  .NET 4 includes addition and subtractionoperators on these types, along with Add and Subtract methods, to help prevent these kinds of errors.

ServiceInstaller.DelayedAutoStart

.NET-based services that start automatically can now set a new DelayedAutoStart property to true (recommended), which will delay auto-starting the service until after other auto-start services are started plus a short delay to improve system boot performance when running on Vista or greater.

ObservableCollection moved to System.dll

We’ve type-forward System.Collections.ObjectModel.ObservableCollection, System.Collections.ObjectModel.ReadOnlyObservableCollection, and System.Collections.Specialized.INotifyCollectionChanged from WindowsBase.dll (a WPF assembly) to System.dll.  This allows you to use these collections without taking a dependency on a WPF assembly and enables a cleaner separation between model and view.
We hope you like what we’ve added to the BCL in .NET 4 Beta 2.  Download Visual Studio 2010 and .NET 4 Beta 2 today.  Be sure to let us know what you think and report any bugs you run into.
Update: Added links to the MSDN documentation for each feature throughout. We'd appreciate any feedback on the docs as well. Also updated ServiceInstaller with the correct name (fixed from ServiceProcessInstaller).


For more refer msdn article.


New Features of WCF

What's New in Windows Communication Foundation
This topic discusses features new to Windows Communication Foundation (WCF).

Configuration Based Activation

Normally when hosting a Windows Communication Foundation (WCF) service under Internet Information Services (IIS) or Windows Process Activation Service (WAS), you must provide a .svc file. The .svc file contains the name of the service and an optional custom service host factory. This additional file adds manageability overhead. The configuration-based activation feature removes the requirement to have a .svc file and therefore the associated overhead. For more information, see Configuration-Based Activation in IIS and WASConfiguration-Based Activation.

System.Web.Routing Integration

When hosting a Windows Communication Foundation (WCF) service in IIS, you place a .svc file in the virtual directory. This .svc file specifies the service host factory to use as well as the class that implements the service. When making requests to the service you specify the .svc file in the URI, for example: http://contoso.com/EmployeeServce.svc. For programmers writing REST services, this type of URI is not optimal. URIs for REST services specify a specific resource and normally do not have any extensions. The System.Web.Routing integration feature allows you to host a WCF service that responds to URIs without an extension. For more information, see System.Web.Routing IntegrationSystemWebRouting Integration Sample.

Multiple IIS Site Bindings Support

When hosting a Windows Communication Foundation (WCF) service under Internet Information Services (IIS) 7.0, you may want to provide multiple base addresses that use the same protocol on the same site. This allows the same service to respond to a number of different URIs. This is useful when you want to host a service that listens on http://www.contoso.com and http://contoso.com. It is also useful to create a service that has a base address for internal users and a separate base address for external users. For more information, see Supporting Multiple IIS Site Bindings,

Routing Service

The Routing Service is a generic SOAP intermediary that acts as a message router. The core functionality of the Routing Service is the ability to route messages based on the message content, which allows a message to be forwarded to a client endpoint based on a value within the message itself, in either the header or the message body. For more information, see RoutingRouting Services .

Support for WS-Discovery

The Service Discovery feature enables client applications to dynamically discover service addresses at runtime in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message exchange patterns (MEPs) required for performing light-weight discovery of services, both by multicast (ad hoc) and unicast (utilizing a network resource). For more information, see WCF DiscoveryDiscovery (Samples).

Support for HTTP Decompression

WCF clients now have built-in support for HTTP decompression. A client can decompress received messages that were compressed with the gzip/deflate format.
The following table contains links that instruct how to enable an IIS server for compression.

IIS 6.0http://go.microsoft.com/fwlink/?LinkID=189308&clcid=0x409
IIS 7.0http://go.microsoft.com/fwlink/?LinkId=189309

By default, a WCF client sends an Accept-Encoding header to the server to notify that it can decompress data. This default behavior can be turned off by creating a custom binding based on the HttpTransportBindingElementand setting the DecompressionEnabled property to false.

Standard Endpoints

Standard endpoints are pre-defined endpoints that have one or more of their properties (address, binding, contract) fixed. For example, all metadata exchange endpoints specify IMetadataExchange as their contract, so the developer does not have to specify the contract. The standard MEX endpoint therefore has a fixed IMetadataExchange contract. For more information, see Standard Endpoints, .

Workflow Services

With the introduction of a set of messaging activities, it is easier than ever to implement workflows that send and receive data. These messaging activities allow you to model complex message exchange patterns that go outside of the traditional send/receive or RPC-style method invocation. For more information, see Workflow ServicesServicesServices.

Target Framework Attribute

The target framework attribute is used to specify the version of the .NET Framework an application hosted in IIS or WAS is targeting. It allows you to build applications that target .NET Framework 2.0, 3.5, or 4 using Visual Studio. It is an attribute set within a <compilation> tag in an application's Web.config file as shown in the following example.



<compilation debug="false"
        targetFramework="4.0">


        <assemblies>
 <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
 <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
 <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
 <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
 </assemblies>
 </compilation>
When an application hosted in IIS or WAS targets a version of the .NET Framework that is not installed, an exception is thrown that indicates the problem. If the target framework moniker is not specified in the application's Web.config file, the value is inferred from the application pool version configured in IIS.
Because of this new feature, if you try to host a WCF service written with .NET Framework 3.5 on a machine running .NET Framework 4, you may get a ProtocolException with the following text:



Unhandled Exception: System.ServiceModel.ProtocolException: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is 
implemented properly. The first 1024 bytes of the response were: '            ...




This error occurs because the application domain that IIS is running within is running .NET Framework 4 and the WCF service is expecting to run under .NET Framework 3.5. For more information about how to fix this problem, see How to: Host a WCF Service Written with .NET Framework 3.5 in IIS Running Under .NET Framework 4.

WCF REST


Caching

The .NET Framework 4 enables you to leverage the declarative caching mechanism already available in ASP.NET in your WCF REST services. This allows you to cache responses from your WCF REST service operations. When a user sends an HTTP GET to your service that is configured for caching, ASP.NET sends back the cached response and the service method is not called. When the cache expires, the next time a user sends an HTTP GET, your service method is called and the response is once again cached.
The .NET Framework 4 also allows you to implement conditional HTTP GET caching. In REST scenarios a conditional HTTP GET is often used by services to implement intelligent HTTP caching as described in the HTTP Specification. For more information, see Caching Support for WCF Web HTTP ServicesCaching and Automatic Help Page.


Formats Support

The WCF web HTTP programming model allows you to dynamically determine the best format for a service operation to return its response in. Responses can be set automatically for XML and JSON based on the accept header. Helper APIs have been added to programmatically set the format of an operation. For more information, see WCF Web HTTP FormattingAutomatic Format SelectionAdvanced Format Selection.


HTTP REST Error Handling

WCF web HTTP error handling enables you to return errors from WCF REST services that specify an HTTP status code and return error details using the same format as the operation (for example, XML or JSON). For more information, see WCF Web HTTP Error Handling, .


Deployment Features

The configuration needed to run a service has been simplified and new standard endpoints have been introduced to further simply service configuration. For more information about the new simplified configuration see, Simplified Configuration. For more information about standard endpoints see, Standard Endpoints.
When hosting a Windows Communication Foundation (WCF) service in IIS you place a .svc file in the virtual directory. This .svc file specifies the service host factory to use as well as the class that implements the service. When making requests to the service you specify the .svc file in the URI, for example: http://contoso.com/EmployeeServce.svc. For programmers writing REST services this type of URI is not optimal. URIs for REST services specify a specific resource and normally do not have any extensions. The System.Web.Routing integration feature allows you to host a WCF REST service that responds to URIs without an extension. For more information, see System.Web.Routing Integration.


Cross Domain JavaScript

JSON Padding (JSONP) is a mechanism that enables cross site scripting support in web browsers. JSONP is designed around the ability of web browsers to load scripts from a site different from the one the current loaded document was retrieved from. The mechanism works by padding the JSON payload with a user-defined callback function name, for example:



callback({ “a” = \“b\” });
In the above example the JSON payload, {“a” = \”b\”}, is wrapped in a function call, callback. The callback function must already be defined in the current web page. The content type of a JSONP response is “application/javascript”. For more information, see JSONP.


WCF REST Service Help Page

.NET Framework version 4 provides an automatic help page for WCF REST services. This help page lists a description of each operation, request and response formats, and schemas. For more information, see WCF Web HTTP Service Help PageCaching and Automatic Help Page.


References

For more reading refer msdn article.




Monday, June 14, 2010

Changes and Differences between Asp.Net 4.0 , 3.5 and 2.0

Ever since the launch of .Net 4.0 many programmers and developers get confused in mapping the various changes that have taken place in Asp.Net. In this post I am going to discuss the changes that are there in Asp.Net starting from .Net 2.0 to .Net 3.5 and .Net 4.0 respectively.

Some of the major changes are as follows:


ControlRenderingCompatabilityVersion Setting in the Web.config File


ASP.NET controls have been modified in the .NET Framework version 4 in order to let you specify more precisely how they render markup. In previous versions of the .NET Framework, some controls emitted markup that you had no way to disable. By default, ASP.NET 4 this type of markup is no longer generated.

If you use Visual Studio 2010 to upgrade your application from ASP.NET 2.0 or ASP.NET 3.5, the tool automatically adds a setting to the Web.config file that preserves legacy rendering. However, if you upgrade an application by changing the application pool in IIS to target the .NET Framework 4, ASP.NET uses the new rendering mode by default. To disable the new rendering mode, add the following setting in the Web.config file:

<pages controlRenderingCompatibilityVersion="3.5" />


The major rendering changes that the new behavior brings are as follows:


  • The Image and ImageButton controls no longer render a border="0" attribute.
  • The BaseValidator class and validation controls that derive from it no longer render red text by default.
  • The HtmlForm control does not render a name attribute.
  • The Table control no longer renders a border="0" attribute.
  • Controls that are not designed for user input (for example, the Label control) no longer render the disabled="disabled" attribute if their Enabled property is set to false (or if they inherit this setting from a container control).

ClientIDMode Changes

The ClientIDMode setting in ASP.NET 4 lets you specify how ASP.NET generates the id attribute for HTML elements. In previous versions of ASP.NET, the default behavior was equivalent to the AutoID setting of ClientIDMode. However, the default setting is now Predictable.

If you use Visual Studio 2010 to upgrade your application from ASP.NET 2.0 or ASP.NET 3.5, the tool automatically adds a setting to the Web.config file that preserves the behavior of earlier versions of the .NET Framework. However, if you upgrade an application by changing the application pool in IIS to target the .NET Framework 4, ASP.NET uses the new mode by default. To disable the new client ID mode, add the following setting in the Web.config file:

<pages ClientIDMode="AutoID" / >


HtmlEncode and UrlEncode Now Encode Single Quotation Marks

In ASP.NET 4, the HtmlEncode and UrlEncode methods of the HttpUtility and HttpServerUtility classes have been updated to encode the single quotation mark character (') as follows:


  • The HtmlEncode method encodes instances of the single quotation mark as ' .
  • The UrlEncode method encodes instances of the single quotation mark as %27.
  • ASP.NET Page (.aspx) Parser is Stricter


The page parser for ASP.NET pages (.aspx files) and user controls (.ascx files) is stricter in ASP.NET 4 and will reject more instances of invalid markup. For example, the following two snippets would successfully parse in earlier releases of ASP.NET, but will now raise parser errors in ASP.NET 4.

<asp:HiddenField runat="server" ID="SomeControl" Value="sampleValue" ; />

Notice the invalid semicolon at the end of the HiddenField tag.

<asp:LinkButton runat="server" ID="SomeControl" onclick="someControlClicked"
style="display:inline; CssClass="searchLink" />


Notice the unclosed style attribute that runs into the CssClass attribute.

Browser Definition Files Updated

The browser definition files have been updated to include information about new and updated browsers and devices. Older browsers and devices such as Netscape Navigator have been removed, and newer browsers and devices such as Google Chrome and Apple iPhone have been added.

If your application contains custom browser definitions that inherit from one of the browser definitions that have been removed, you will see an error. For example, if the App_Browsers folder contains a browser definition that inherits from the IE2 browser definition, you will receive the following configuration error message:

The browser or gateway element with ID 'IE2' cannot be found.

Note The HttpBrowserCapabilities object (which is exposed by the page’s Request.Browser property) is driven by the browser definitions files. Therefore, the information returned by accessing a property of this object in ASP.NET 4 might be different than the information returned in an earlier version of ASP.NET.

You can revert to the old browser definition files by copying the browser definition files from the following folder:

Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers
Copy the files into the corresponding \CONFIG\Browsers folder for ASP.NET 4. After you copy the files, run the Aspnet_regbrowsers.exe command-line tool.

For more information, download the ASP.NET Browser Definition Files release from http://aspnet.codeplex.com/releases/view/41420. This download includes the old browser definition files, the new browser definition files, and instructions for installing the files.

System.Web.Mobile.dll Removed from Root Web Configuration File

In previous versions of ASP.NET, a reference to the System.Web.Mobile.dll assembly was included in the root Web.config file in the assemblies section under . In order to improve performance, the reference to this assembly was removed.

The System.Web.Mobile.dll assembly is included in ASP.NET 4, but it is deprecated. If you want to use types from the System.Web.Mobile.dll assembly, add a reference to this assembly to either the root Web.config file or to an application Web.config file. For example, if you want to use any of the (deprecated) ASP.NET mobile controls, you must add a reference to the System.Web.Mobile.dll assembly to the Web.config file.

ASP.NET Request Validation

The request validation feature in ASP.NET provides a certain level of default protection against cross-site scripting (XSS) attacks. In previous versions of ASP.NET, request validation was enabled by default. However, it applied only to ASP.NET pages (.aspx files and their class files) and only when those pages were executing.

In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.

As a result, request validation errors might now occur for requests that previously did not trigger errors. To revert to the behavior of the ASP.NET 2.0 request validation feature, add the following setting in the Web.config file:

<httpRuntime requestValidationMode="2.0" />


However, we recommend that you analyze any request validation errors to determine whether existing handlers, modules, or other custom code accesses potentially unsafe HTTP inputs that could be XSS attack vectors.

Default Hashing Algorithm Is Now HMACSHA256

ASP.NET uses both encryption and hashing algorithms to help secure data such as forms authentication cookies and view state. By default, ASP.NET 4 now uses the HMACSHA256 algorithm for hash operations on cookies and view state. Earlier versions of ASP.NET used the older HMACSHA1 algorithm.

Your applications might be affected if you run mixed ASP.NET 2.0/ASP.NET 4 environments where data such as forms authentication cookies must work across.NET Framework versions. To configure an ASP.NET 4 Web application to use the older HMACSHA1 algorithm, add the following setting in the Web.config file:

<machineKey validation="SHA1" />


Configuration Errors Related to New ASP.NET 4 Root Configuration

The root configuration files (the machine.config file and the root Web.config file) for the .NET Framework 4 (and therefore ASP.NET 4) have been updated to include most of the boilerplate configuration information that in ASP.NET 3.5 was found in the application Web.config files. Because of the complexity of the managed IIS 7 and IIS 7.5 configuration systems, running ASP.NET 3.5 applications under ASP.NET 4 and under IIS 7 and IIS 7.5 can result in either ASP.NET or IIS configuration errors.

We recommend that you upgrade ASP.NET 3.5 applications to ASP.NET 4 by using the project upgrade tools in Visual Studio 2010, if practical. Visual Studio 2010 automatically modifies the ASP.NET 3.5 application's Web.config file to contain the appropriate settings for ASP.NET 4.

However, it is a supported scenario to run ASP.NET 3.5 applications using the .NET Framework 4 without recompilation. In that case, you might have to manually modify the application's Web.config file before you run the application under the .NET Framework 4 and under IIS 7 or IIS 7.5.

Windows Vista SP1 or Windows Server 2008 SP1, where neither hotfix KB958854 nor SP2 are installed. In this configuration, the IIS 7 configuration system incorrectly merges an application's managed configuration by comparing the application-level Web.config file to the ASP.NET 2.0 machine.config files. Because of this, application-level Web.config files from the .NET Framework 3.5 or later must have a system.web.extensions configuration section definition (the element) in order not to cause an IIS 7 validation failure.

However, manually modified application-level Web.config file entries that do not precisely match the original boilerplate configuration section definitions that were introduced with Visual Studio 2008 will cause ASP.NET configuration errors. (The default configuration entries that are generated by Visual Studio 2008 work correctly.) A common problem is that manually modified Web.config files leave out the allowDefinition and requirePermission configuration attributes that are found on various configuration section definitions. This causes a mismatch between the abbreviated configuration section in application-level Web.config files and the complete definition in the ASP.NET 4 machine.config file. As a result, at run time, the ASP.NET 4 configuration system throws a configuration error.

Windows Vista SP2, Windows Server 2008 SP2, Windows 7, Windows Server 2008 R2, and also Windows Vista SP1 and Windows Server 2008 SP1 where hotfix KB958854 is installed.

In this scenario, the IIS 7 and IIS 7.5 native configuration system returns a configuration error because it performs a text comparison on the type attribute that is defined for a managed configuration section handler. Because all Web.config files that are generated by Visual Studio 2008 and Visual Studio 2008 SP1 have "3.5" in the type string for the system.web.extensions (and related) configuration section handlers, and because the ASP.NET 4 machine.config file has "4.0" in the type attribute for the same configuration section handlers, applications that are generated in Visual Studio 2008 or Visual Studio 2008 SP1 always fail configuration validation in IIS 7 and IIS 7.5.

Resolving These Issues

The workaround for the first scenario is to update the application-level Web.config file by including the boilerplate configuration text from a Web.config file that was generated automatically by Visual Studio 2008.

An alternative workaround for the first scenario is to install Service Pack 2 for Vista or Windows Server 2008 on your computer or to install hotfix KB958854 (http://support.microsoft.com/kb/958854) to fix the incorrect configuration-merge behavior of the IIS configuration system. However, after you perform either of these actions, your application will likely encounter a configuration error due to the issue described for the second scenario.

The workaround for the second scenario is to delete or comment out all the system.web.extensions configuration section definitions and configuration section group definitions from the application-level Web.config file. These definitions are usually at the top of the application-level Web.config file and can be identified by the configSections element and its children.

For both scenarios, it is recommended that you also manually delete the system.codedom section, although this is not required.

ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications

ASP.NET 4 applications that are configured as children of applications that run earlier versions of ASP.NET might fail to start because of configuration or compilation errors. The following example shows a directory structure for an affected application.

/parentwebapp (configured to use ASP.NET 2.0 or ASP.NET 3.5)
/childwebapp (configured to use ASP.NET 4)

The application in the childwebapp folder will fail to start on IIS 7 or IIS 7.5 and will report a configuration error. The error text will include a message similar to the following:

The requested page cannot be accessed because the related configuration data for the page is invalid.

The configuration section 'configSections' cannot be read because it is missing a section declaration.

On IIS 6, the application in the childwebapp folder will also fail to start, but it will report a different error. For example, the error text might state the following:

The value for the 'compilerVersion' attribute in the provider options must be 'v4.0' or later if you are compiling for version 4.0 or later of the .NET Framework. To compile this Web application for version 3.5 or earlier of the .NET Framework, remove the 'targetFramework' attribute from the element of the Web.config file

These scenarios occur because the configuration information from the parent application in the parentwebapp folder is part of the hierarchy of configuration information that determines the final merged configuration settings that are used by the child web application in the childwebapp folder. Depending on whether the ASP.NET 4 Web application is running on IIS 7 (or IIS 7.5) or on IIS 6, either the IIS configuration system or the ASP.NET 4 compilation system will return an error.

The steps that you must follow to resolve this issue and to get the child ASP.NET 4 application to work depend on whether the ASP.NET 4 application runs on IIS 6 or on IIS 7 (or IIS 7.5).

ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed

Web servers that run SharePoint have a Web.config file that is deployed at the root of a SharePoint Web site (for example, c:\inetpub\wwwroot\web.config for Default Web Site). In this Web.config file, SharePoint sets a custom partial-trust level named WSS_Minimal.

If you try to run an ASP.NET 4 Web site that is deployed as a child of this type of SharePoint Web site, you will see the following error:

Could not find permission set named 'ASP.Net'.

This error occurs because the ASP.NET 4 code access security (CAS) infrastructure looks for a permission set named ASP.Net. However, the partial trust configuration file that is referenced by WSS_Minimal does not contain any permission sets with that name.

Currently there is not a version of SharePoint available that is compatible with ASP.NET. As a result, you should not attempt to run an ASP.NET 4 Web site as a child site underneath SharePoint Web sites.

The HttpRequest.FilePath Property No Longer Includes PathInfo Values

Previous versions of ASP.NET included a PathInfo value in the value returned from various file path-related properties, including HttpRequest.FilePath, HttpRequest.AppRelativeCurrentExecutionFilePath, and HttpRequest.CurrentExecutionFilePath. ASP.NET 4 no longer includes the PathInfo value in the return values from these properties. Instead, the PathInfo information is available in HttpRequest.PathInfo. For example, imagine the following URL fragment:

/testapp/Action.mvc/SomeAction

In earlier versions of ASP.NET, HttpRequest properties have the following values:

HttpRequest.FilePath: /testapp/Action.mvc/SomeAction

HttpRequest.PathInfo: (empty)

In ASP.NET 4, HttpRequest properties instead have the following values:

HttpRequest.FilePath: /testapp/Action.mvc

HttpRequest.PathInfo: SomeAction

ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd

After ASP.NET 4 has been enabled on IIS 6, ASP.NET 2.0 applications that run on IIS 6 (in either Windows Server 2003 or Windows Server 2003 R2) might generate errors such as the following:

System.Web.HttpException: Path '/[yourApplicationRoot]/eurl.axd/[Value]' was not found.

This error occurs because when ASP.NET detects that a Web site is configured to use ASP.NET 4, a native component of ASP.NET 4 passes an extensionless URL to the managed portion of ASP.NET for further processing. However, if virtual directories that are below an ASP.NET 4 Web site are configured to use ASP.NET 2.0, processing the extensionless URL in this way results in a modified URL that contains the string "eurl.axd". This modified URL is then sent to the ASP.NET 2.0 application. ASP.NET 2.0 cannot recognize the "eurl.axd" format. Therefore, ASP.NET 2.0 tries to find a file named eurl.axd and execute it. Because no such file exists, the request fails with an HttpException exception.

You can work around this issue using one of the following options.

Option 1

If ASP.NET 4 is not required in order to run the Web site, remap the site to use ASP.NET 2.0 instead.

Option 2

If ASP.NET 4 is required in order to run the Web site, move any child ASP.NET 2.0 virtual directories to a different Web site that is mapped to ASP.NET 2.0.

Option 3

If it is not practical to remap the Web site to ASP.NET 2.0 or to change the location of a virtual directory, explicitly disable extensionless URL processing in ASP.NET 4. Use the following procedure:

In the Windows registry, open the following node:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\4.0.30319.0

Create a new DWORD value named EnableExtensionlessUrls.
Set EnableExtensionlessUrls to 0. This disables extensionless URL behavior.
Save the registry value and close the registry editor.
Run the iisreset command-line tool, which causes IIS to read the new registry value.
Note Setting EnableExtensionlessUrls to 1 enables extensionless URL behavior. This is the default setting if no value is specified.

Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode

ASP.NET 4 includes modifications that change how the action attribute of the HTML form element is rendered when an extensionless URL resolves to a default document. An example of an extensionless URL resolving to a default document would be http://contoso.com/, resulting in a request to http://contoso.com/Default.aspx.

ASP.NET 4 now renders the HTML form element’s action attribute value as an empty string when a request is made to an extensionless URL that has a default document mapped to it. For example, in earlier releases of ASP.NET, a request to http://contoso.com would result in a request to Default.aspx. In that document, the opening form tag would be rendered as in the following example:

<form action="Default.aspx" />

In ASP.NET 4, a request to http://contoso.com also results in a request to Default.aspx. However, ASP.NET now renders the HTML opening form tag as in the following example:

<form action="" />

This difference in how the action attribute is rendered can cause subtle changes in how a form post is processed by IIS and ASP.NET. When the action attribute is an empty string, the IIS DefaultDocumentModule object will create a child request to Default.aspx. Under most conditions, this child request is transparent to application code, and the Default.aspx page runs normally.

However, a potential interaction between managed code and IIS 7 or IIS 7.5 Integrated mode can cause managed .aspx pages to stop working properly during the child request. If the following conditions occur, the child request to a Default.aspx document will result in an error or in unexpected behavior:

An .aspx page is sent to the browser with the form element’s action attribute set to "".

The form is posted back to ASP.NET. A managed HTTP module reads some part of the entity body. For example, a module reads Request.Form or Request.Params. This causes the entity body of the POST request to be read into managed memory. As a result, the entity body is no longer available to any native code modules that are running in IIS 7 or IIS 7.5 Integrated mode.

The IIS DefaultDocumentModule object eventually runs and creates a child request to the Default.aspx document. However, because the entity body has already been read by a piece of managed code, there is no entity body available to send to the child request. When the HTTP pipeline runs for the child request, the handler for .aspx files runs during the handler-execute phase.
Because there is no entity body, there are no form variables and no view state, and therefore no information is available for the .aspx page handler to determine what event (if any) is supposed to be raised. As a result, none of the postback event handlers for the affected .aspx page run.
You can work around this behavior in the following ways:

Identify the HTTP module that is accessing the request's entity body during default document requests and determine whether it can be configured to run only for managed requests. In Integrated mode for both IIS 7 and IIS 7.5, HTTP modules can be marked to run only for managed requests by adding the following attribute to the module's system.webServer/modules entry:
precondition="managedHandler"

This setting disables the module for requests that IIS 7 and IIS 7.5 determine as not being managed requests. For default document requests, the first request is to an extensionless URL. Therefore, IIS does not run any managed modules that are marked with a precondition of managed Handler during initial request processing. As a result, managed modules will not accidentally read the entity body and thus the entity body is still available and is passed along to the child request and to the default document.

If the problematic HTTP modules have to run for all requests (for static files, for extensionless URLs that resolve to the DefaultDocumentModule object, for managed requests, etc.), modify the affected .aspx pages by explicitly setting the Action property of the page’s System.Web.UI.HtmlControls.HtmlForm control to a non-empty string. For example, if the default document is Default.aspx, modify the page's code to explicitly set the HtmlForm control’s Action property to "Default.aspx".

Changes to the ASP.NET Code Access Security (CAS) Implementation

ASP.NET 2.0, and by extension the ASP.NET features that were added in 3.5, use the .NET Framework 1.1 and 2.0 code access security (CAS) model. However, the implementation of CAS in ASP.NET 4 has been substantially overhauled. As a result, partial-trust ASP.NET applications that rely on trusted code running in the global assembly cache (GAC) might fail with various security exceptions. Partial-trust applications that rely on extensive modifications to machine CAS policy might also fail with security exceptions.

You can revert partial-trust ASP.NET 4 applications to the behavior of ASP.NET 1.1 and 2.0 using the new legacyCasModel attribute in the trust configuration element, as shown in the following example:

<trust level= "Medium" legacyCasModel="true" />

When you revert to the legacy CAS model, the following old CAS behaviors are enabled:

Machine CAS policy is honored. Multiple different permission sets in a single application domain are allowed.
Explicit permission assertions are not required for assemblies in the GAC that are invoked when only ASP.NET or other .NET Framework code is on the stack.

One scenario cannot be reverted in the .NET Framework 4: non-Web partial-trust applications can no longer call certain APIs in System.Web.dll and System.Web.Extensions.dll. In previous versions of the .NET Framework, it was possible for non-Web partial-trust applications to be explicitly granted AspNetHostingPermission permissions. These applications could then use System.Web.HttpUtility, types in the System.Web.ClientServices.* namespaces, and types related to membership, roles, and profiles. Calling these types from non-Web partial trust applications is no longer supported in the .NET Framework 4.

Note The HtmlEncode and HtmlDecode functionality of the System.Web.HttpUtility class was moved to the new .NET Framework 4 System.Net.WebUtility class. If that was the only ASP.NET functionality that was being used, modify the application's code to use the new WebUtility class instead.

The following is a high-level summary of the changes to the default CAS implementation in ASP.NET 4:

ASP.NET application domains are now homogeneous application domains. Only partial-trust and full-trust grant sets are available in an application domain. ASP.NET partial-trust grant sets are independent from any enterprise-level, machine-level, or user-level CAS policy. ASP.NET assemblies that shipped in 3.5 and 3.5 SP1 have been converted to use the .NET Framework 4 transparency model. Use of the ASP.NET AspNetHostingPermission attribute has been substantially reduced. Most instances of this attribute have been removed from the public ASP.NET APIs.

Dynamically compiled assemblies that are created by ASP.NET build providers have been updated to explicitly mark assemblies as transparent. All ASP.NET assemblies are now marked in such a way that the APTCA attribute is honored only in Web hosting environments. Partially trusted non-Web hosting environments like ClickOnce will not be able to call into ASP.NET assemblies.


These are some of the changes as reflected in the article on Asp.Net website. For more refer it.

LinkWithin

Related Posts with Thumbnails